Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/__config__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/_distributor_init.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/conftest.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/version.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/__init__.py +90 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_download_all.py +74 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_fetchers.py +229 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_registry.py +26 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_utils.py +84 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/differentiate/__init__.py +27 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/differentiate/_differentiate.py +1140 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/__init__.py +103 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_basic.py +428 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_helper.py +115 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_pseudo_diffs.py +554 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_realtransforms.py +598 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/basic.py +20 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/helper.py +19 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/pseudo_diffs.py +22 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/realtransforms.py +19 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_bsplines.py +2614 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_cubic.py +1029 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_fitpack.cpython-311-x86_64-linux-gnu.so +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_ndbspline.py +518 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_ndgriddata.py +330 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_pade.py +67 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_polyint.py +1029 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_rbf.py +292 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_rbfinterp_common.py +32 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_rbfinterp_xp.py +266 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_rgi.py +812 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/dfitpack.py +24 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/fitpack.py +31 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/fitpack2.py +29 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/interpnd.py +21 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/ndgriddata.py +23 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/polyint.py +24 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/__init__.py +121 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/_fortran.py +354 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/_idl.py +917 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/_mmio.py +968 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/_netcdf.py +1104 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/harwell_boeing.py +17 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/idl.py +17 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/mmio.py +17 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/netcdf.py +17 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/wavfile.py +944 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/linalg/__init__.pxd +1 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/linalg/__init__.py +234 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/__config__.cpython-311.pyc
ADDED
|
Binary file (5.82 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (4.5 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/_distributor_init.cpython-311.pyc
ADDED
|
Binary file (895 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/conftest.cpython-311.pyc
ADDED
|
Binary file (29 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/__pycache__/version.cpython-311.pyc
ADDED
|
Binary file (592 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/__init__.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
================================
|
| 3 |
+
Datasets (:mod:`scipy.datasets`)
|
| 4 |
+
================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.datasets
|
| 7 |
+
|
| 8 |
+
Dataset Methods
|
| 9 |
+
===============
|
| 10 |
+
|
| 11 |
+
.. autosummary::
|
| 12 |
+
:toctree: generated/
|
| 13 |
+
|
| 14 |
+
ascent
|
| 15 |
+
face
|
| 16 |
+
electrocardiogram
|
| 17 |
+
|
| 18 |
+
Utility Methods
|
| 19 |
+
===============
|
| 20 |
+
|
| 21 |
+
.. autosummary::
|
| 22 |
+
:toctree: generated/
|
| 23 |
+
|
| 24 |
+
download_all -- Download all the dataset files to specified path.
|
| 25 |
+
clear_cache -- Clear cached dataset directory.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
Usage of Datasets
|
| 29 |
+
=================
|
| 30 |
+
|
| 31 |
+
SciPy dataset methods can be simply called as follows: ``'<dataset-name>()'``
|
| 32 |
+
This downloads the dataset files over the network once, and saves the cache,
|
| 33 |
+
before returning a `numpy.ndarray` object representing the dataset.
|
| 34 |
+
|
| 35 |
+
Note that the return data structure and data type might be different for
|
| 36 |
+
different dataset methods. For a more detailed example on usage, please look
|
| 37 |
+
into the particular dataset method documentation above.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
How dataset retrieval and storage works
|
| 41 |
+
=======================================
|
| 42 |
+
|
| 43 |
+
SciPy dataset files are stored within individual GitHub repositories under the
|
| 44 |
+
SciPy GitHub organization, following a naming convention as
|
| 45 |
+
``'dataset-<name>'``, for example `scipy.datasets.face` files live at
|
| 46 |
+
https://github.com/scipy/dataset-face. The `scipy.datasets` submodule utilizes
|
| 47 |
+
and depends on `Pooch <https://www.fatiando.org/pooch/latest/>`_, a Python
|
| 48 |
+
package built to simplify fetching data files. Pooch uses these repos to
|
| 49 |
+
retrieve the respective dataset files when calling the dataset function.
|
| 50 |
+
|
| 51 |
+
A registry of all the datasets, essentially a mapping of filenames with their
|
| 52 |
+
SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
|
| 53 |
+
the downloads on function call. After downloading the dataset once, the files
|
| 54 |
+
are saved in the system cache directory under ``'scipy-data'``.
|
| 55 |
+
|
| 56 |
+
Dataset cache locations may vary on different platforms.
|
| 57 |
+
|
| 58 |
+
For macOS::
|
| 59 |
+
|
| 60 |
+
'~/Library/Caches/scipy-data'
|
| 61 |
+
|
| 62 |
+
For Linux and other Unix-like platforms::
|
| 63 |
+
|
| 64 |
+
'~/.cache/scipy-data' # or the value of the XDG_CACHE_HOME env var, if defined
|
| 65 |
+
|
| 66 |
+
For Windows::
|
| 67 |
+
|
| 68 |
+
'C:\\Users\\<user>\\AppData\\Local\\<AppAuthor>\\scipy-data\\Cache'
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
In environments with constrained network connectivity for various security
|
| 72 |
+
reasons or on systems without continuous internet connections, one may manually
|
| 73 |
+
load the cache of the datasets by placing the contents of the dataset repo in
|
| 74 |
+
the above mentioned cache directory to avoid fetching dataset errors without
|
| 75 |
+
the internet connectivity.
|
| 76 |
+
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
from ._fetchers import face, ascent, electrocardiogram
|
| 81 |
+
from ._download_all import download_all
|
| 82 |
+
from ._utils import clear_cache
|
| 83 |
+
|
| 84 |
+
__all__ = ['ascent', 'electrocardiogram', 'face',
|
| 85 |
+
'download_all', 'clear_cache']
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
from scipy._lib._testutils import PytestTester
|
| 89 |
+
test = PytestTester(__name__)
|
| 90 |
+
del PytestTester
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_download_all.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Platform independent script to download all the
|
| 3 |
+
`scipy.datasets` module data files.
|
| 4 |
+
This doesn't require a full scipy build.
|
| 5 |
+
|
| 6 |
+
Run: python _download_all.py <download_dir>
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from scipy._lib._array_api import xp_capabilities
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
try:
|
| 13 |
+
import pooch
|
| 14 |
+
except ImportError:
|
| 15 |
+
pooch = None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if __package__ is None or __package__ == '':
|
| 19 |
+
# Running as python script, use absolute import
|
| 20 |
+
import _registry # type: ignore
|
| 21 |
+
else:
|
| 22 |
+
# Running as python module, use relative import
|
| 23 |
+
from . import _registry
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@xp_capabilities(out_of_scope=True)
|
| 27 |
+
def download_all(path=None):
|
| 28 |
+
"""
|
| 29 |
+
Utility method to download all the dataset files
|
| 30 |
+
for `scipy.datasets` module.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
path : str, optional
|
| 35 |
+
Directory path to download all the dataset files.
|
| 36 |
+
If None, default to the system cache_dir detected by pooch.
|
| 37 |
+
|
| 38 |
+
Examples
|
| 39 |
+
--------
|
| 40 |
+
Download the datasets to the default cache location:
|
| 41 |
+
|
| 42 |
+
>>> from scipy import datasets
|
| 43 |
+
>>> datasets.download_all()
|
| 44 |
+
|
| 45 |
+
Download the datasets to the current directory:
|
| 46 |
+
|
| 47 |
+
>>> datasets.download_all(".")
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
if pooch is None:
|
| 51 |
+
raise ImportError("Missing optional dependency 'pooch' required "
|
| 52 |
+
"for scipy.datasets module. Please use pip or "
|
| 53 |
+
"conda to install 'pooch'.")
|
| 54 |
+
if path is None:
|
| 55 |
+
path = pooch.os_cache('scipy-data')
|
| 56 |
+
# https://github.com/scipy/scipy/issues/21879
|
| 57 |
+
downloader = pooch.HTTPDownloader(headers={"User-Agent": "SciPy"})
|
| 58 |
+
for dataset_name, dataset_hash in _registry.registry.items():
|
| 59 |
+
pooch.retrieve(url=_registry.registry_urls[dataset_name],
|
| 60 |
+
known_hash=dataset_hash,
|
| 61 |
+
fname=dataset_name, path=path, downloader=downloader)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def main():
|
| 65 |
+
parser = argparse.ArgumentParser(description='Download SciPy data files.')
|
| 66 |
+
parser.add_argument("path", nargs='?', type=str,
|
| 67 |
+
default=pooch.os_cache('scipy-data'),
|
| 68 |
+
help="Directory path to download all the data files.")
|
| 69 |
+
args = parser.parse_args()
|
| 70 |
+
download_all(args.path)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_fetchers.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
from numpy import array, frombuffer, load
|
| 4 |
+
from ._registry import registry, registry_urls
|
| 5 |
+
|
| 6 |
+
from scipy._lib._array_api import xp_capabilities
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
import pooch
|
| 10 |
+
except ImportError:
|
| 11 |
+
pooch = None
|
| 12 |
+
data_fetcher = None
|
| 13 |
+
else:
|
| 14 |
+
data_fetcher = pooch.create(
|
| 15 |
+
# Use the default cache folder for the operating system
|
| 16 |
+
# Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
|
| 17 |
+
# select an appropriate directory for the cache on each platform.
|
| 18 |
+
path=pooch.os_cache("scipy-data"),
|
| 19 |
+
|
| 20 |
+
# The remote data is on Github
|
| 21 |
+
# base_url is a required param, even though we override this
|
| 22 |
+
# using individual urls in the registry.
|
| 23 |
+
base_url="https://github.com/scipy/",
|
| 24 |
+
registry=registry,
|
| 25 |
+
urls=registry_urls
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def fetch_data(dataset_name, data_fetcher=data_fetcher):
|
| 30 |
+
if data_fetcher is None:
|
| 31 |
+
raise ImportError("Missing optional dependency 'pooch' required "
|
| 32 |
+
"for scipy.datasets module. Please use pip or "
|
| 33 |
+
"conda to install 'pooch'.")
|
| 34 |
+
# https://github.com/scipy/scipy/issues/21879
|
| 35 |
+
downloader = pooch.HTTPDownloader(
|
| 36 |
+
headers={"User-Agent": f"SciPy {sys.modules['scipy'].__version__}"}
|
| 37 |
+
)
|
| 38 |
+
# The "fetch" method returns the full path to the downloaded data file.
|
| 39 |
+
return data_fetcher.fetch(dataset_name, downloader=downloader)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@xp_capabilities(out_of_scope=True)
|
| 43 |
+
def ascent():
|
| 44 |
+
"""
|
| 45 |
+
Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
|
| 46 |
+
use in demos.
|
| 47 |
+
|
| 48 |
+
The image is derived from
|
| 49 |
+
https://pixnio.com/people/accent-to-the-top
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
None
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
ascent : ndarray
|
| 58 |
+
convenient image to use for testing and demonstration
|
| 59 |
+
|
| 60 |
+
Examples
|
| 61 |
+
--------
|
| 62 |
+
>>> import scipy.datasets
|
| 63 |
+
>>> ascent = scipy.datasets.ascent()
|
| 64 |
+
>>> ascent.shape
|
| 65 |
+
(512, 512)
|
| 66 |
+
>>> ascent.max()
|
| 67 |
+
np.uint8(255)
|
| 68 |
+
|
| 69 |
+
>>> import matplotlib.pyplot as plt
|
| 70 |
+
>>> plt.gray()
|
| 71 |
+
>>> plt.imshow(ascent)
|
| 72 |
+
>>> plt.show()
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
import pickle
|
| 76 |
+
|
| 77 |
+
# The file will be downloaded automatically the first time this is run,
|
| 78 |
+
# returning the path to the downloaded file. Afterwards, Pooch finds
|
| 79 |
+
# it in the local cache and doesn't repeat the download.
|
| 80 |
+
fname = fetch_data("ascent.dat")
|
| 81 |
+
# Now we just need to load it with our standard Python tools.
|
| 82 |
+
with open(fname, 'rb') as f:
|
| 83 |
+
ascent = array(pickle.load(f))
|
| 84 |
+
return ascent
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@xp_capabilities(out_of_scope=True)
|
| 88 |
+
def electrocardiogram():
|
| 89 |
+
"""
|
| 90 |
+
Load an electrocardiogram as an example for a 1-D signal.
|
| 91 |
+
|
| 92 |
+
The returned signal is a 5 minute long electrocardiogram (ECG), a medical
|
| 93 |
+
recording of the heart's electrical activity, sampled at 360 Hz.
|
| 94 |
+
|
| 95 |
+
Returns
|
| 96 |
+
-------
|
| 97 |
+
ecg : ndarray
|
| 98 |
+
The electrocardiogram in millivolt (mV) sampled at 360 Hz.
|
| 99 |
+
|
| 100 |
+
Notes
|
| 101 |
+
-----
|
| 102 |
+
The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
|
| 103 |
+
(lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
|
| 104 |
+
PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
|
| 105 |
+
heartbeats as well as pathological changes.
|
| 106 |
+
|
| 107 |
+
.. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
|
| 108 |
+
|
| 109 |
+
.. versionadded:: 1.1.0
|
| 110 |
+
|
| 111 |
+
References
|
| 112 |
+
----------
|
| 113 |
+
.. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
|
| 114 |
+
IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
|
| 115 |
+
(PMID: 11446209); :doi:`10.13026/C2F305`
|
| 116 |
+
.. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
|
| 117 |
+
Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
|
| 118 |
+
PhysioToolkit, and PhysioNet: Components of a New Research Resource
|
| 119 |
+
for Complex Physiologic Signals. Circulation 101(23):e215-e220;
|
| 120 |
+
:doi:`10.1161/01.CIR.101.23.e215`
|
| 121 |
+
|
| 122 |
+
Examples
|
| 123 |
+
--------
|
| 124 |
+
>>> from scipy.datasets import electrocardiogram
|
| 125 |
+
>>> ecg = electrocardiogram()
|
| 126 |
+
>>> ecg
|
| 127 |
+
array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
|
| 128 |
+
>>> ecg.shape, ecg.mean(), ecg.std()
|
| 129 |
+
((108000,), -0.16510875, 0.5992473991177294)
|
| 130 |
+
|
| 131 |
+
As stated the signal features several areas with a different morphology.
|
| 132 |
+
E.g., the first few seconds show the electrical activity of a heart in
|
| 133 |
+
normal sinus rhythm as seen below.
|
| 134 |
+
|
| 135 |
+
>>> import numpy as np
|
| 136 |
+
>>> import matplotlib.pyplot as plt
|
| 137 |
+
>>> fs = 360
|
| 138 |
+
>>> time = np.arange(ecg.size) / fs
|
| 139 |
+
>>> plt.plot(time, ecg)
|
| 140 |
+
>>> plt.xlabel("time in s")
|
| 141 |
+
>>> plt.ylabel("ECG in mV")
|
| 142 |
+
>>> plt.xlim(9, 10.2)
|
| 143 |
+
>>> plt.ylim(-1, 1.5)
|
| 144 |
+
>>> plt.show()
|
| 145 |
+
|
| 146 |
+
After second 16, however, the first premature ventricular contractions,
|
| 147 |
+
also called extrasystoles, appear. These have a different morphology
|
| 148 |
+
compared to typical heartbeats. The difference can easily be observed
|
| 149 |
+
in the following plot.
|
| 150 |
+
|
| 151 |
+
>>> plt.plot(time, ecg)
|
| 152 |
+
>>> plt.xlabel("time in s")
|
| 153 |
+
>>> plt.ylabel("ECG in mV")
|
| 154 |
+
>>> plt.xlim(46.5, 50)
|
| 155 |
+
>>> plt.ylim(-2, 1.5)
|
| 156 |
+
>>> plt.show()
|
| 157 |
+
|
| 158 |
+
At several points large artifacts disturb the recording, e.g.:
|
| 159 |
+
|
| 160 |
+
>>> plt.plot(time, ecg)
|
| 161 |
+
>>> plt.xlabel("time in s")
|
| 162 |
+
>>> plt.ylabel("ECG in mV")
|
| 163 |
+
>>> plt.xlim(207, 215)
|
| 164 |
+
>>> plt.ylim(-2, 3.5)
|
| 165 |
+
>>> plt.show()
|
| 166 |
+
|
| 167 |
+
Finally, examining the power spectrum reveals that most of the biosignal is
|
| 168 |
+
made up of lower frequencies. At 60 Hz the noise induced by the mains
|
| 169 |
+
electricity can be clearly observed.
|
| 170 |
+
|
| 171 |
+
>>> from scipy.signal import welch
|
| 172 |
+
>>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
|
| 173 |
+
>>> plt.semilogy(f, Pxx)
|
| 174 |
+
>>> plt.xlabel("Frequency in Hz")
|
| 175 |
+
>>> plt.ylabel("Power spectrum of the ECG in mV**2")
|
| 176 |
+
>>> plt.xlim(f[[0, -1]])
|
| 177 |
+
>>> plt.show()
|
| 178 |
+
"""
|
| 179 |
+
fname = fetch_data("ecg.dat")
|
| 180 |
+
with load(fname) as file:
|
| 181 |
+
ecg = file["ecg"].astype(int) # np.uint16 -> int
|
| 182 |
+
# Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
|
| 183 |
+
ecg = (ecg - 1024) / 200.0
|
| 184 |
+
return ecg
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@xp_capabilities(out_of_scope=True)
|
| 188 |
+
def face(gray=False):
|
| 189 |
+
"""
|
| 190 |
+
Get a 1024 x 768, color image of a raccoon face.
|
| 191 |
+
|
| 192 |
+
The image is derived from
|
| 193 |
+
https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
|
| 194 |
+
|
| 195 |
+
Parameters
|
| 196 |
+
----------
|
| 197 |
+
gray : bool, optional
|
| 198 |
+
If True return 8-bit grey-scale image, otherwise return a color image
|
| 199 |
+
|
| 200 |
+
Returns
|
| 201 |
+
-------
|
| 202 |
+
face : ndarray
|
| 203 |
+
image of a raccoon face
|
| 204 |
+
|
| 205 |
+
Examples
|
| 206 |
+
--------
|
| 207 |
+
>>> import scipy.datasets
|
| 208 |
+
>>> face = scipy.datasets.face()
|
| 209 |
+
>>> face.shape
|
| 210 |
+
(768, 1024, 3)
|
| 211 |
+
>>> face.max()
|
| 212 |
+
np.uint8(255)
|
| 213 |
+
|
| 214 |
+
>>> import matplotlib.pyplot as plt
|
| 215 |
+
>>> plt.gray()
|
| 216 |
+
>>> plt.imshow(face)
|
| 217 |
+
>>> plt.show()
|
| 218 |
+
|
| 219 |
+
"""
|
| 220 |
+
import bz2
|
| 221 |
+
fname = fetch_data("face.dat")
|
| 222 |
+
with open(fname, 'rb') as f:
|
| 223 |
+
rawdata = f.read()
|
| 224 |
+
face_data = bz2.decompress(rawdata)
|
| 225 |
+
face = frombuffer(face_data, dtype='uint8').reshape((768, 1024, 3))
|
| 226 |
+
if gray is True:
|
| 227 |
+
face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
|
| 228 |
+
0.07 * face[:, :, 2]).astype('uint8')
|
| 229 |
+
return face
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_registry.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
##########################################################################
|
| 2 |
+
# This file serves as the dataset registry for SciPy Datasets SubModule.
|
| 3 |
+
##########################################################################
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# To generate the SHA256 hash, use the command
|
| 7 |
+
# openssl sha256 <filename>
|
| 8 |
+
registry = {
|
| 9 |
+
"ascent.dat": "03ce124c1afc880f87b55f6b061110e2e1e939679184f5614e38dacc6c1957e2",
|
| 10 |
+
"ecg.dat": "f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf",
|
| 11 |
+
"face.dat": "9d8b0b4d081313e2b485748c770472e5a95ed1738146883d84c7030493e82886"
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
registry_urls = {
|
| 15 |
+
"ascent.dat": "https://raw.githubusercontent.com/scipy/dataset-ascent/main/ascent.dat",
|
| 16 |
+
"ecg.dat": "https://raw.githubusercontent.com/scipy/dataset-ecg/main/ecg.dat",
|
| 17 |
+
"face.dat": "https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat"
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
# dataset method mapping with their associated filenames
|
| 21 |
+
# <method_name> : ["filename1", "filename2", ...]
|
| 22 |
+
method_files_map = {
|
| 23 |
+
"ascent": ["ascent.dat"],
|
| 24 |
+
"electrocardiogram": ["ecg.dat"],
|
| 25 |
+
"face": ["face.dat"]
|
| 26 |
+
}
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/datasets/_utils.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
from ._registry import method_files_map
|
| 4 |
+
|
| 5 |
+
from scipy._lib._array_api import xp_capabilities
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
import platformdirs
|
| 9 |
+
except ImportError:
|
| 10 |
+
platformdirs = None # type: ignore[assignment]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _clear_cache(datasets, cache_dir=None, method_map=None):
|
| 14 |
+
if method_map is None:
|
| 15 |
+
# Use SciPy Datasets method map
|
| 16 |
+
method_map = method_files_map
|
| 17 |
+
if cache_dir is None:
|
| 18 |
+
# Use default cache_dir path
|
| 19 |
+
if platformdirs is None:
|
| 20 |
+
# platformdirs is pooch dependency
|
| 21 |
+
raise ImportError("Missing optional dependency 'pooch' required "
|
| 22 |
+
"for scipy.datasets module. Please use pip or "
|
| 23 |
+
"conda to install 'pooch'.")
|
| 24 |
+
cache_dir = platformdirs.user_cache_dir("scipy-data")
|
| 25 |
+
|
| 26 |
+
if not os.path.exists(cache_dir):
|
| 27 |
+
print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
|
| 28 |
+
return
|
| 29 |
+
|
| 30 |
+
if datasets is None:
|
| 31 |
+
print(f"Cleaning the cache directory {cache_dir}!")
|
| 32 |
+
shutil.rmtree(cache_dir)
|
| 33 |
+
else:
|
| 34 |
+
if not isinstance(datasets, list | tuple):
|
| 35 |
+
# single dataset method passed should be converted to list
|
| 36 |
+
datasets = [datasets, ]
|
| 37 |
+
for dataset in datasets:
|
| 38 |
+
assert callable(dataset)
|
| 39 |
+
dataset_name = dataset.__name__ # Name of the dataset method
|
| 40 |
+
if dataset_name not in method_map:
|
| 41 |
+
raise ValueError(f"Dataset method {dataset_name} doesn't "
|
| 42 |
+
"exist. Please check if the passed dataset "
|
| 43 |
+
"is a subset of the following dataset "
|
| 44 |
+
f"methods: {list(method_map.keys())}")
|
| 45 |
+
|
| 46 |
+
data_files = method_map[dataset_name]
|
| 47 |
+
data_filepaths = [os.path.join(cache_dir, file)
|
| 48 |
+
for file in data_files]
|
| 49 |
+
for data_filepath in data_filepaths:
|
| 50 |
+
if os.path.exists(data_filepath):
|
| 51 |
+
print("Cleaning the file "
|
| 52 |
+
f"{os.path.split(data_filepath)[1]} "
|
| 53 |
+
f"for dataset {dataset_name}")
|
| 54 |
+
os.remove(data_filepath)
|
| 55 |
+
else:
|
| 56 |
+
print(f"Path {data_filepath} doesn't exist. "
|
| 57 |
+
"Nothing to clear.")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@xp_capabilities(out_of_scope=True)
|
| 61 |
+
def clear_cache(datasets=None):
|
| 62 |
+
"""
|
| 63 |
+
Cleans the scipy datasets cache directory.
|
| 64 |
+
|
| 65 |
+
If a scipy.datasets method or a list/tuple of the same is
|
| 66 |
+
provided, then clear_cache removes all the data files
|
| 67 |
+
associated to the passed dataset method callable(s).
|
| 68 |
+
|
| 69 |
+
By default, it removes all the cached data files.
|
| 70 |
+
|
| 71 |
+
Parameters
|
| 72 |
+
----------
|
| 73 |
+
datasets : callable or list/tuple of callable or None
|
| 74 |
+
|
| 75 |
+
Examples
|
| 76 |
+
--------
|
| 77 |
+
>>> from scipy import datasets
|
| 78 |
+
>>> ascent_array = datasets.ascent()
|
| 79 |
+
>>> ascent_array.shape
|
| 80 |
+
(512, 512)
|
| 81 |
+
>>> datasets.clear_cache([datasets.ascent])
|
| 82 |
+
Cleaning the file ascent.dat for dataset ascent
|
| 83 |
+
"""
|
| 84 |
+
_clear_cache(datasets)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/differentiate/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
==============================================================
|
| 3 |
+
Finite Difference Differentiation (:mod:`scipy.differentiate`)
|
| 4 |
+
==============================================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.differentiate
|
| 7 |
+
|
| 8 |
+
SciPy ``differentiate`` provides functions for performing finite difference
|
| 9 |
+
numerical differentiation of black-box functions.
|
| 10 |
+
|
| 11 |
+
.. autosummary::
|
| 12 |
+
:toctree: generated/
|
| 13 |
+
|
| 14 |
+
derivative
|
| 15 |
+
jacobian
|
| 16 |
+
hessian
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
from ._differentiate import *
|
| 22 |
+
|
| 23 |
+
__all__ = ['derivative', 'jacobian', 'hessian']
|
| 24 |
+
|
| 25 |
+
from scipy._lib._testutils import PytestTester
|
| 26 |
+
test = PytestTester(__name__)
|
| 27 |
+
del PytestTester
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/differentiate/_differentiate.py
ADDED
|
@@ -0,0 +1,1140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code="attr-defined"
|
| 2 |
+
import warnings
|
| 3 |
+
import numpy as np
|
| 4 |
+
import scipy._lib._elementwise_iterative_method as eim
|
| 5 |
+
from scipy._lib._util import _RichResult
|
| 6 |
+
from scipy._lib._array_api import array_namespace, xp_copy, xp_promote, xp_capabilities
|
| 7 |
+
import scipy._lib.array_api_extra as xpx
|
| 8 |
+
|
| 9 |
+
_EERRORINCREASE = -1 # used in derivative
|
| 10 |
+
|
| 11 |
+
def _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
|
| 12 |
+
step_factor, step_direction, preserve_shape, callback):
|
| 13 |
+
# Input validation for `derivative`
|
| 14 |
+
xp = array_namespace(x)
|
| 15 |
+
|
| 16 |
+
if not callable(f):
|
| 17 |
+
raise ValueError('`f` must be callable.')
|
| 18 |
+
|
| 19 |
+
if not np.iterable(args):
|
| 20 |
+
args = (args,)
|
| 21 |
+
|
| 22 |
+
tolerances = {} if tolerances is None else tolerances
|
| 23 |
+
atol = tolerances.get('atol', None)
|
| 24 |
+
rtol = tolerances.get('rtol', None)
|
| 25 |
+
|
| 26 |
+
# tolerances are floats, not arrays; OK to use NumPy
|
| 27 |
+
message = 'Tolerances and step parameters must be non-negative scalars.'
|
| 28 |
+
tols = np.asarray([atol if atol is not None else 1,
|
| 29 |
+
rtol if rtol is not None else 1,
|
| 30 |
+
step_factor])
|
| 31 |
+
if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
|
| 32 |
+
or np.any(np.isnan(tols)) or tols.shape != (3,)):
|
| 33 |
+
raise ValueError(message)
|
| 34 |
+
step_factor = float(tols[2])
|
| 35 |
+
|
| 36 |
+
maxiter_int = int(maxiter)
|
| 37 |
+
if maxiter != maxiter_int or maxiter <= 0:
|
| 38 |
+
raise ValueError('`maxiter` must be a positive integer.')
|
| 39 |
+
|
| 40 |
+
order_int = int(order)
|
| 41 |
+
if order_int != order or order <= 0:
|
| 42 |
+
raise ValueError('`order` must be a positive integer.')
|
| 43 |
+
|
| 44 |
+
step_direction = xp.asarray(step_direction)
|
| 45 |
+
initial_step = xp.asarray(initial_step)
|
| 46 |
+
temp = xp.broadcast_arrays(x, step_direction, initial_step)
|
| 47 |
+
x, step_direction, initial_step = temp
|
| 48 |
+
|
| 49 |
+
message = '`preserve_shape` must be True or False.'
|
| 50 |
+
if preserve_shape not in {True, False}:
|
| 51 |
+
raise ValueError(message)
|
| 52 |
+
|
| 53 |
+
if callback is not None and not callable(callback):
|
| 54 |
+
raise ValueError('`callback` must be callable.')
|
| 55 |
+
|
| 56 |
+
return (f, x, args, atol, rtol, maxiter_int, order_int, initial_step,
|
| 57 |
+
step_factor, step_direction, preserve_shape, callback)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
_array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
|
| 62 |
+
_dask_reason = 'boolean indexing assignment'
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
|
| 66 |
+
('dask.array', _dask_reason)], jax_jit=False)
|
| 67 |
+
def derivative(f, x, *, args=(), tolerances=None, maxiter=10,
|
| 68 |
+
order=8, initial_step=0.5, step_factor=2.0,
|
| 69 |
+
step_direction=0, preserve_shape=False, callback=None):
|
| 70 |
+
"""Evaluate the derivative of an elementwise, real scalar function numerically.
|
| 71 |
+
|
| 72 |
+
For each element of the output of `f`, `derivative` approximates the first
|
| 73 |
+
derivative of `f` at the corresponding element of `x` using finite difference
|
| 74 |
+
differentiation.
|
| 75 |
+
|
| 76 |
+
This function works elementwise when `x`, `step_direction`, and `args` contain
|
| 77 |
+
(broadcastable) arrays.
|
| 78 |
+
|
| 79 |
+
Parameters
|
| 80 |
+
----------
|
| 81 |
+
f : callable
|
| 82 |
+
The function whose derivative is desired. The signature must be::
|
| 83 |
+
|
| 84 |
+
f(xi: ndarray, *argsi) -> ndarray
|
| 85 |
+
|
| 86 |
+
where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
|
| 87 |
+
which may contain an arbitrary number of arrays that are broadcastable with
|
| 88 |
+
``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
|
| 89 |
+
must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
|
| 90 |
+
``xi`` or the arrays in ``argsi``.
|
| 91 |
+
x : float array_like
|
| 92 |
+
Abscissae at which to evaluate the derivative. Must be broadcastable with
|
| 93 |
+
`args` and `step_direction`.
|
| 94 |
+
args : tuple of array_like, optional
|
| 95 |
+
Additional positional array arguments to be passed to `f`. Arrays
|
| 96 |
+
must be broadcastable with one another and the arrays of `init`.
|
| 97 |
+
If the callable for which the root is desired requires arguments that are
|
| 98 |
+
not broadcastable with `x`, wrap that callable with `f` such that `f`
|
| 99 |
+
accepts only `x` and broadcastable ``*args``.
|
| 100 |
+
tolerances : dictionary of floats, optional
|
| 101 |
+
Absolute and relative tolerances. Valid keys of the dictionary are:
|
| 102 |
+
|
| 103 |
+
- ``atol`` - absolute tolerance on the derivative
|
| 104 |
+
- ``rtol`` - relative tolerance on the derivative
|
| 105 |
+
|
| 106 |
+
Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
|
| 107 |
+
`atol` is the smallest normal number of the appropriate dtype, and
|
| 108 |
+
the default `rtol` is the square root of the precision of the
|
| 109 |
+
appropriate dtype.
|
| 110 |
+
order : int, default: 8
|
| 111 |
+
The (positive integer) order of the finite difference formula to be
|
| 112 |
+
used. Odd integers will be rounded up to the next even integer.
|
| 113 |
+
initial_step : float array_like, default: 0.5
|
| 114 |
+
The (absolute) initial step size for the finite difference derivative
|
| 115 |
+
approximation.
|
| 116 |
+
step_factor : float, default: 2.0
|
| 117 |
+
The factor by which the step size is *reduced* in each iteration; i.e.
|
| 118 |
+
the step size in iteration 1 is ``initial_step/step_factor``. If
|
| 119 |
+
``step_factor < 1``, subsequent steps will be greater than the initial
|
| 120 |
+
step; this may be useful if steps smaller than some threshold are
|
| 121 |
+
undesirable (e.g. due to subtractive cancellation error).
|
| 122 |
+
maxiter : int, default: 10
|
| 123 |
+
The maximum number of iterations of the algorithm to perform. See
|
| 124 |
+
Notes.
|
| 125 |
+
step_direction : integer array_like
|
| 126 |
+
An array representing the direction of the finite difference steps (for
|
| 127 |
+
use when `x` lies near to the boundary of the domain of the function.)
|
| 128 |
+
Must be broadcastable with `x` and all `args`.
|
| 129 |
+
Where 0 (default), central differences are used; where negative (e.g.
|
| 130 |
+
-1), steps are non-positive; and where positive (e.g. 1), all steps are
|
| 131 |
+
non-negative.
|
| 132 |
+
preserve_shape : bool, default: False
|
| 133 |
+
In the following, "arguments of `f`" refers to the array ``xi`` and
|
| 134 |
+
any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
|
| 135 |
+
of `x` and all elements of `args` (which is conceptually
|
| 136 |
+
distinct from ``xi` and ``argsi`` passed into `f`).
|
| 137 |
+
|
| 138 |
+
- When ``preserve_shape=False`` (default), `f` must accept arguments
|
| 139 |
+
of *any* broadcastable shapes.
|
| 140 |
+
|
| 141 |
+
- When ``preserve_shape=True``, `f` must accept arguments of shape
|
| 142 |
+
``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
|
| 143 |
+
abscissae at which the function is being evaluated.
|
| 144 |
+
|
| 145 |
+
In either case, for each scalar element ``xi[j]`` within ``xi``, the array
|
| 146 |
+
returned by `f` must include the scalar ``f(xi[j])`` at the same index.
|
| 147 |
+
Consequently, the shape of the output is always the shape of the input
|
| 148 |
+
``xi``.
|
| 149 |
+
|
| 150 |
+
See Examples.
|
| 151 |
+
callback : callable, optional
|
| 152 |
+
An optional user-supplied function to be called before the first
|
| 153 |
+
iteration and after each iteration.
|
| 154 |
+
Called as ``callback(res)``, where ``res`` is a ``_RichResult``
|
| 155 |
+
similar to that returned by `derivative` (but containing the current
|
| 156 |
+
iterate's values of all variables). If `callback` raises a
|
| 157 |
+
``StopIteration``, the algorithm will terminate immediately and
|
| 158 |
+
`derivative` will return a result. `callback` must not mutate
|
| 159 |
+
`res` or its attributes.
|
| 160 |
+
|
| 161 |
+
Returns
|
| 162 |
+
-------
|
| 163 |
+
res : _RichResult
|
| 164 |
+
An object similar to an instance of `scipy.optimize.OptimizeResult` with the
|
| 165 |
+
following attributes. The descriptions are written as though the values will
|
| 166 |
+
be scalars; however, if `f` returns an array, the outputs will be
|
| 167 |
+
arrays of the same shape.
|
| 168 |
+
|
| 169 |
+
success : bool array
|
| 170 |
+
``True`` where the algorithm terminated successfully (status ``0``);
|
| 171 |
+
``False`` otherwise.
|
| 172 |
+
status : int array
|
| 173 |
+
An integer representing the exit status of the algorithm.
|
| 174 |
+
|
| 175 |
+
- ``0`` : The algorithm converged to the specified tolerances.
|
| 176 |
+
- ``-1`` : The error estimate increased, so iteration was terminated.
|
| 177 |
+
- ``-2`` : The maximum number of iterations was reached.
|
| 178 |
+
- ``-3`` : A non-finite value was encountered.
|
| 179 |
+
- ``-4`` : Iteration was terminated by `callback`.
|
| 180 |
+
- ``1`` : The algorithm is proceeding normally (in `callback` only).
|
| 181 |
+
|
| 182 |
+
df : float array
|
| 183 |
+
The derivative of `f` at `x`, if the algorithm terminated
|
| 184 |
+
successfully.
|
| 185 |
+
error : float array
|
| 186 |
+
An estimate of the error: the magnitude of the difference between
|
| 187 |
+
the current estimate of the derivative and the estimate in the
|
| 188 |
+
previous iteration.
|
| 189 |
+
nit : int array
|
| 190 |
+
The number of iterations of the algorithm that were performed.
|
| 191 |
+
nfev : int array
|
| 192 |
+
The number of points at which `f` was evaluated.
|
| 193 |
+
x : float array
|
| 194 |
+
The value at which the derivative of `f` was evaluated
|
| 195 |
+
(after broadcasting with `args` and `step_direction`).
|
| 196 |
+
|
| 197 |
+
See Also
|
| 198 |
+
--------
|
| 199 |
+
jacobian, hessian
|
| 200 |
+
|
| 201 |
+
Notes
|
| 202 |
+
-----
|
| 203 |
+
The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
|
| 204 |
+
DERIVEST [3]_, but the implementation follows the theory of Taylor series
|
| 205 |
+
more straightforwardly (and arguably naively so).
|
| 206 |
+
In the first iteration, the derivative is estimated using a finite
|
| 207 |
+
difference formula of order `order` with maximum step size `initial_step`.
|
| 208 |
+
Each subsequent iteration, the maximum step size is reduced by
|
| 209 |
+
`step_factor`, and the derivative is estimated again until a termination
|
| 210 |
+
condition is reached. The error estimate is the magnitude of the difference
|
| 211 |
+
between the current derivative approximation and that of the previous
|
| 212 |
+
iteration.
|
| 213 |
+
|
| 214 |
+
The stencils of the finite difference formulae are designed such that
|
| 215 |
+
abscissae are "nested": after `f` is evaluated at ``order + 1``
|
| 216 |
+
points in the first iteration, `f` is evaluated at only two new points
|
| 217 |
+
in each subsequent iteration; ``order - 1`` previously evaluated function
|
| 218 |
+
values required by the finite difference formula are reused, and two
|
| 219 |
+
function values (evaluations at the points furthest from `x`) are unused.
|
| 220 |
+
|
| 221 |
+
Step sizes are absolute. When the step size is small relative to the
|
| 222 |
+
magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
|
| 223 |
+
default initial step size of ``0.5`` cannot be resolved. Accordingly,
|
| 224 |
+
consider using larger initial step sizes for large magnitudes of `x`.
|
| 225 |
+
|
| 226 |
+
The default tolerances are challenging to satisfy at points where the
|
| 227 |
+
true derivative is exactly zero. If the derivative may be exactly zero,
|
| 228 |
+
consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
|
| 229 |
+
improve convergence.
|
| 230 |
+
|
| 231 |
+
References
|
| 232 |
+
----------
|
| 233 |
+
.. [1] Hans Dembinski (@HDembinski). jacobi.
|
| 234 |
+
https://github.com/HDembinski/jacobi
|
| 235 |
+
.. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
|
| 236 |
+
https://numdifftools.readthedocs.io/en/latest/
|
| 237 |
+
.. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
|
| 238 |
+
https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
|
| 239 |
+
.. [4] Numerical Differentition. Wikipedia.
|
| 240 |
+
https://en.wikipedia.org/wiki/Numerical_differentiation
|
| 241 |
+
|
| 242 |
+
Examples
|
| 243 |
+
--------
|
| 244 |
+
Evaluate the derivative of ``np.exp`` at several points ``x``.
|
| 245 |
+
|
| 246 |
+
>>> import numpy as np
|
| 247 |
+
>>> from scipy.differentiate import derivative
|
| 248 |
+
>>> f = np.exp
|
| 249 |
+
>>> df = np.exp # true derivative
|
| 250 |
+
>>> x = np.linspace(1, 2, 5)
|
| 251 |
+
>>> res = derivative(f, x)
|
| 252 |
+
>>> res.df # approximation of the derivative
|
| 253 |
+
array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
|
| 254 |
+
>>> res.error # estimate of the error
|
| 255 |
+
array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
|
| 256 |
+
1.94262384e-11])
|
| 257 |
+
>>> abs(res.df - df(x)) # true error
|
| 258 |
+
array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
|
| 259 |
+
6.92779167e-14])
|
| 260 |
+
|
| 261 |
+
Show the convergence of the approximation as the step size is reduced.
|
| 262 |
+
Each iteration, the step size is reduced by `step_factor`, so for
|
| 263 |
+
sufficiently small initial step, each iteration reduces the error by a
|
| 264 |
+
factor of ``1/step_factor**order`` until finite precision arithmetic
|
| 265 |
+
inhibits further improvement.
|
| 266 |
+
|
| 267 |
+
>>> import matplotlib.pyplot as plt
|
| 268 |
+
>>> iter = list(range(1, 12)) # maximum iterations
|
| 269 |
+
>>> hfac = 2 # step size reduction per iteration
|
| 270 |
+
>>> hdir = [-1, 0, 1] # compare left-, central-, and right- steps
|
| 271 |
+
>>> order = 4 # order of differentiation formula
|
| 272 |
+
>>> x = 1
|
| 273 |
+
>>> ref = df(x)
|
| 274 |
+
>>> errors = [] # true error
|
| 275 |
+
>>> for i in iter:
|
| 276 |
+
... res = derivative(f, x, maxiter=i, step_factor=hfac,
|
| 277 |
+
... step_direction=hdir, order=order,
|
| 278 |
+
... # prevent early termination
|
| 279 |
+
... tolerances=dict(atol=0, rtol=0))
|
| 280 |
+
... errors.append(abs(res.df - ref))
|
| 281 |
+
>>> errors = np.array(errors)
|
| 282 |
+
>>> plt.semilogy(iter, errors[:, 0], label='left differences')
|
| 283 |
+
>>> plt.semilogy(iter, errors[:, 1], label='central differences')
|
| 284 |
+
>>> plt.semilogy(iter, errors[:, 2], label='right differences')
|
| 285 |
+
>>> plt.xlabel('iteration')
|
| 286 |
+
>>> plt.ylabel('error')
|
| 287 |
+
>>> plt.legend()
|
| 288 |
+
>>> plt.show()
|
| 289 |
+
>>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
|
| 290 |
+
(0.06215223140159822, 0.0625)
|
| 291 |
+
|
| 292 |
+
The implementation is vectorized over `x`, `step_direction`, and `args`.
|
| 293 |
+
The function is evaluated once before the first iteration to perform input
|
| 294 |
+
validation and standardization, and once per iteration thereafter.
|
| 295 |
+
|
| 296 |
+
>>> def f(x, p):
|
| 297 |
+
... f.nit += 1
|
| 298 |
+
... return x**p
|
| 299 |
+
>>> f.nit = 0
|
| 300 |
+
>>> def df(x, p):
|
| 301 |
+
... return p*x**(p-1)
|
| 302 |
+
>>> x = np.arange(1, 5)
|
| 303 |
+
>>> p = np.arange(1, 6).reshape((-1, 1))
|
| 304 |
+
>>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
|
| 305 |
+
>>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
|
| 306 |
+
>>> np.allclose(res.df, df(x, p))
|
| 307 |
+
True
|
| 308 |
+
>>> res.df.shape
|
| 309 |
+
(3, 5, 4)
|
| 310 |
+
>>> f.nit
|
| 311 |
+
2
|
| 312 |
+
|
| 313 |
+
By default, `preserve_shape` is False, and therefore the callable
|
| 314 |
+
`f` may be called with arrays of any broadcastable shapes.
|
| 315 |
+
For example:
|
| 316 |
+
|
| 317 |
+
>>> shapes = []
|
| 318 |
+
>>> def f(x, c):
|
| 319 |
+
... shape = np.broadcast_shapes(x.shape, c.shape)
|
| 320 |
+
... shapes.append(shape)
|
| 321 |
+
... return np.sin(c*x)
|
| 322 |
+
>>>
|
| 323 |
+
>>> c = [1, 5, 10, 20]
|
| 324 |
+
>>> res = derivative(f, 0, args=(c,))
|
| 325 |
+
>>> shapes
|
| 326 |
+
[(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]
|
| 327 |
+
|
| 328 |
+
To understand where these shapes are coming from - and to better
|
| 329 |
+
understand how `derivative` computes accurate results - note that
|
| 330 |
+
higher values of ``c`` correspond with higher frequency sinusoids.
|
| 331 |
+
The higher frequency sinusoids make the function's derivative change
|
| 332 |
+
faster, so more function evaluations are required to achieve the target
|
| 333 |
+
accuracy:
|
| 334 |
+
|
| 335 |
+
>>> res.nfev
|
| 336 |
+
array([11, 13, 15, 17], dtype=int32)
|
| 337 |
+
|
| 338 |
+
The initial ``shape``, ``(4,)``, corresponds with evaluating the
|
| 339 |
+
function at a single abscissa and all four frequencies; this is used
|
| 340 |
+
for input validation and to determine the size and dtype of the arrays
|
| 341 |
+
that store results. The next shape corresponds with evaluating the
|
| 342 |
+
function at an initial grid of abscissae and all four frequencies.
|
| 343 |
+
Successive calls to the function evaluate the function at two more
|
| 344 |
+
abscissae, increasing the effective order of the approximation by two.
|
| 345 |
+
However, in later function evaluations, the function is evaluated at
|
| 346 |
+
fewer frequencies because the corresponding derivative has already
|
| 347 |
+
converged to the required tolerance. This saves function evaluations to
|
| 348 |
+
improve performance, but it requires the function to accept arguments of
|
| 349 |
+
any shape.
|
| 350 |
+
|
| 351 |
+
"Vector-valued" functions are unlikely to satisfy this requirement.
|
| 352 |
+
For example, consider
|
| 353 |
+
|
| 354 |
+
>>> def f(x):
|
| 355 |
+
... return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
|
| 356 |
+
|
| 357 |
+
This integrand is not compatible with `derivative` as written; for instance,
|
| 358 |
+
the shape of the output will not be the same as the shape of ``x``. Such a
|
| 359 |
+
function *could* be converted to a compatible form with the introduction of
|
| 360 |
+
additional parameters, but this would be inconvenient. In such cases,
|
| 361 |
+
a simpler solution would be to use `preserve_shape`.
|
| 362 |
+
|
| 363 |
+
>>> shapes = []
|
| 364 |
+
>>> def f(x):
|
| 365 |
+
... shapes.append(x.shape)
|
| 366 |
+
... x0, x1, x2, x3 = x
|
| 367 |
+
... return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
|
| 368 |
+
>>>
|
| 369 |
+
>>> x = np.zeros(4)
|
| 370 |
+
>>> res = derivative(f, x, preserve_shape=True)
|
| 371 |
+
>>> shapes
|
| 372 |
+
[(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
|
| 373 |
+
|
| 374 |
+
Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
|
| 375 |
+
function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
|
| 376 |
+
and this is what we observe.
|
| 377 |
+
|
| 378 |
+
"""
|
| 379 |
+
# TODO (followup):
|
| 380 |
+
# - investigate behavior at saddle points
|
| 381 |
+
# - multivariate functions?
|
| 382 |
+
# - relative steps?
|
| 383 |
+
# - show example of `np.vectorize`
|
| 384 |
+
|
| 385 |
+
res = _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
|
| 386 |
+
step_factor, step_direction, preserve_shape, callback)
|
| 387 |
+
(func, x, args, atol, rtol, maxiter, order,
|
| 388 |
+
h0, fac, hdir, preserve_shape, callback) = res
|
| 389 |
+
|
| 390 |
+
# Initialization
|
| 391 |
+
# Since f(x) (no step) is not needed for central differences, it may be
|
| 392 |
+
# possible to eliminate this function evaluation. However, it's useful for
|
| 393 |
+
# input validation and standardization, and everything else is designed to
|
| 394 |
+
# reduce function calls, so let's keep it simple.
|
| 395 |
+
temp = eim._initialize(func, (x,), args, preserve_shape=preserve_shape)
|
| 396 |
+
func, xs, fs, args, shape, dtype, xp = temp
|
| 397 |
+
|
| 398 |
+
finfo = xp.finfo(dtype)
|
| 399 |
+
atol = finfo.smallest_normal if atol is None else atol
|
| 400 |
+
rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `hessian`
|
| 401 |
+
|
| 402 |
+
x, f = xs[0], fs[0]
|
| 403 |
+
df = xp.full_like(f, xp.nan)
|
| 404 |
+
|
| 405 |
+
# Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but
|
| 406 |
+
# it's simpler to do it here than to generalize `_elementwise_algo_init` further.
|
| 407 |
+
# `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know
|
| 408 |
+
# that `hdir` can be broadcasted to the final shape. Same with `h0`.
|
| 409 |
+
hdir = xp.broadcast_to(hdir, shape)
|
| 410 |
+
hdir = xp.reshape(hdir, (-1,))
|
| 411 |
+
hdir = xp.astype(xp.sign(hdir), dtype)
|
| 412 |
+
h0 = xp.broadcast_to(h0, shape)
|
| 413 |
+
h0 = xp.reshape(h0, (-1,))
|
| 414 |
+
h0 = xp.astype(h0, dtype)
|
| 415 |
+
h0 = xpx.at(h0)[h0 <= 0].set(xp.nan)
|
| 416 |
+
|
| 417 |
+
status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32) # in progress
|
| 418 |
+
nit, nfev = 0, 1 # one function evaluations performed above
|
| 419 |
+
# Boolean indices of left, central, right, and (all) one-sided steps
|
| 420 |
+
il = hdir < 0
|
| 421 |
+
ic = hdir == 0
|
| 422 |
+
ir = hdir > 0
|
| 423 |
+
io = il | ir
|
| 424 |
+
|
| 425 |
+
# Most of these attributes are reasonably obvious, but:
|
| 426 |
+
# - `fs` holds all the function values of all active `x`. The zeroth
|
| 427 |
+
# axis corresponds with active points `x`, the first axis corresponds
|
| 428 |
+
# with the different steps (in the order described in
|
| 429 |
+
# `_derivative_weights`).
|
| 430 |
+
# - `terms` (which could probably use a better name) is half the `order`,
|
| 431 |
+
# which is always even.
|
| 432 |
+
work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
|
| 433 |
+
df_last=xp.nan, error_last=xp.nan, fac=fac,
|
| 434 |
+
atol=atol, rtol=rtol, nit=nit, nfev=nfev,
|
| 435 |
+
status=status, dtype=dtype, terms=(order+1)//2,
|
| 436 |
+
hdir=hdir, il=il, ic=ic, ir=ir, io=io,
|
| 437 |
+
# Store the weights in an object so they can't get compressed
|
| 438 |
+
# Using RichResult to allow dot notation, but a dict would work
|
| 439 |
+
diff_state=_RichResult(central=[], right=[], fac=None))
|
| 440 |
+
|
| 441 |
+
# This is the correspondence between terms in the `work` object and the
|
| 442 |
+
# final result. In this case, the mapping is trivial. Note that `success`
|
| 443 |
+
# is prepended automatically.
|
| 444 |
+
res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
|
| 445 |
+
('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
|
| 446 |
+
|
| 447 |
+
def pre_func_eval(work):
|
| 448 |
+
"""Determine the abscissae at which the function needs to be evaluated.
|
| 449 |
+
|
| 450 |
+
See `_derivative_weights` for a description of the stencil (pattern
|
| 451 |
+
of the abscissae).
|
| 452 |
+
|
| 453 |
+
In the first iteration, there is only one stored function value in
|
| 454 |
+
`work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
|
| 455 |
+
subsequent iterations, we evaluate at two new points. Note that
|
| 456 |
+
`work.x` is always flattened into a 1D array after broadcasting with
|
| 457 |
+
all `args`, so we add a new axis at the end and evaluate all point
|
| 458 |
+
in one call to the function.
|
| 459 |
+
|
| 460 |
+
For improvement:
|
| 461 |
+
- Consider measuring the step size actually taken, since ``(x + h) - x``
|
| 462 |
+
is not identically equal to `h` with floating point arithmetic.
|
| 463 |
+
- Adjust the step size automatically if `x` is too big to resolve the
|
| 464 |
+
step.
|
| 465 |
+
- We could probably save some work if there are no central difference
|
| 466 |
+
steps or no one-sided steps.
|
| 467 |
+
"""
|
| 468 |
+
n = work.terms # half the order
|
| 469 |
+
h = work.h[:, xp.newaxis] # step size
|
| 470 |
+
c = work.fac # step reduction factor
|
| 471 |
+
d = c**0.5 # square root of step reduction factor (one-sided stencil)
|
| 472 |
+
# Note - no need to be careful about dtypes until we allocate `x_eval`
|
| 473 |
+
|
| 474 |
+
if work.nit == 0:
|
| 475 |
+
hc = h / c**xp.arange(n, dtype=work.dtype)
|
| 476 |
+
hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
|
| 477 |
+
else:
|
| 478 |
+
hc = xp.concat((-h, h), axis=-1) / c**(n-1)
|
| 479 |
+
|
| 480 |
+
if work.nit == 0:
|
| 481 |
+
hr = h / d**xp.arange(2*n, dtype=work.dtype)
|
| 482 |
+
else:
|
| 483 |
+
hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
|
| 484 |
+
|
| 485 |
+
n_new = 2*n if work.nit == 0 else 2 # number of new abscissae
|
| 486 |
+
x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
|
| 487 |
+
il, ic, ir = work.il, work.ic, work.ir
|
| 488 |
+
x_eval = xpx.at(x_eval)[ir].set(work.x[ir][:, xp.newaxis] + hr[ir])
|
| 489 |
+
x_eval = xpx.at(x_eval)[ic].set(work.x[ic][:, xp.newaxis] + hc[ic])
|
| 490 |
+
x_eval = xpx.at(x_eval)[il].set(work.x[il][:, xp.newaxis] - hr[il])
|
| 491 |
+
return x_eval
|
| 492 |
+
|
| 493 |
+
def post_func_eval(x, f, work):
|
| 494 |
+
""" Estimate the derivative and error from the function evaluations
|
| 495 |
+
|
| 496 |
+
As in `pre_func_eval`: in the first iteration, there is only one stored
|
| 497 |
+
function value in `work.fs`, `f(x)`, so we need to add the `order` new
|
| 498 |
+
points. In subsequent iterations, we add two new points. The tricky
|
| 499 |
+
part is getting the order to match that of the weights, which is
|
| 500 |
+
described in `_derivative_weights`.
|
| 501 |
+
|
| 502 |
+
For improvement:
|
| 503 |
+
- Change the order of the weights (and steps in `pre_func_eval`) to
|
| 504 |
+
simplify `work_fc` concatenation and eliminate `fc` concatenation.
|
| 505 |
+
- It would be simple to do one-step Richardson extrapolation with `df`
|
| 506 |
+
and `df_last` to increase the order of the estimate and/or improve
|
| 507 |
+
the error estimate.
|
| 508 |
+
- Process the function evaluations in a more numerically favorable
|
| 509 |
+
way. For instance, combining the pairs of central difference evals
|
| 510 |
+
into a second-order approximation and using Richardson extrapolation
|
| 511 |
+
to produce a higher order approximation seemed to retain accuracy up
|
| 512 |
+
to very high order.
|
| 513 |
+
- Alternatively, we could use `polyfit` like Jacobi. An advantage of
|
| 514 |
+
fitting polynomial to more points than necessary is improved noise
|
| 515 |
+
tolerance.
|
| 516 |
+
"""
|
| 517 |
+
n = work.terms
|
| 518 |
+
n_new = n if work.nit == 0 else 1
|
| 519 |
+
il, ic, io = work.il, work.ic, work.io
|
| 520 |
+
|
| 521 |
+
# Central difference
|
| 522 |
+
# `work_fc` is *all* the points at which the function has been evaluated
|
| 523 |
+
# `fc` is the points we're using *this iteration* to produce the estimate
|
| 524 |
+
work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
|
| 525 |
+
work_fc = xp.concat(work_fc, axis=-1)
|
| 526 |
+
if work.nit == 0:
|
| 527 |
+
fc = work_fc
|
| 528 |
+
else:
|
| 529 |
+
fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
|
| 530 |
+
fc = xp.concat(fc, axis=-1)
|
| 531 |
+
|
| 532 |
+
# One-sided difference
|
| 533 |
+
work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
|
| 534 |
+
if work.nit == 0:
|
| 535 |
+
fo = work_fo
|
| 536 |
+
else:
|
| 537 |
+
fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
|
| 538 |
+
|
| 539 |
+
work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
|
| 540 |
+
work.fs = xpx.at(work.fs)[ic].set(work_fc)
|
| 541 |
+
work.fs = xpx.at(work.fs)[io].set(work_fo)
|
| 542 |
+
|
| 543 |
+
wc, wo = _derivative_weights(work, n, xp)
|
| 544 |
+
work.df_last = xp.asarray(work.df, copy=True)
|
| 545 |
+
work.df = xpx.at(work.df)[ic].set(fc @ wc / work.h[ic])
|
| 546 |
+
work.df = xpx.at(work.df)[io].set(fo @ wo / work.h[io])
|
| 547 |
+
work.df = xpx.at(work.df)[il].multiply(-1)
|
| 548 |
+
|
| 549 |
+
work.h /= work.fac
|
| 550 |
+
work.error_last = work.error
|
| 551 |
+
# Simple error estimate - the difference in derivative estimates between
|
| 552 |
+
# this iteration and the last. This is typically conservative because if
|
| 553 |
+
# convergence has begin, the true error is much closer to the difference
|
| 554 |
+
# between the current estimate and the *next* error estimate. However,
|
| 555 |
+
# we could use Richarson extrapolation to produce an error estimate that
|
| 556 |
+
# is one order higher, and take the difference between that and
|
| 557 |
+
# `work.df` (which would just be constant factor that depends on `fac`.)
|
| 558 |
+
work.error = xp.abs(work.df - work.df_last)
|
| 559 |
+
|
| 560 |
+
def check_termination(work):
|
| 561 |
+
"""Terminate due to convergence, non-finite values, or error increase"""
|
| 562 |
+
stop = xp.astype(xp.zeros_like(work.df), xp.bool)
|
| 563 |
+
|
| 564 |
+
i = work.error < work.atol + work.rtol*abs(work.df)
|
| 565 |
+
work.status = xpx.at(work.status)[i].set(eim._ECONVERGED)
|
| 566 |
+
stop = xpx.at(stop)[i].set(True)
|
| 567 |
+
|
| 568 |
+
if work.nit > 0:
|
| 569 |
+
i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
|
| 570 |
+
work.df = xpx.at(work.df)[i].set(xp.nan)
|
| 571 |
+
work.status = xpx.at(work.status)[i].set(eim._EVALUEERR)
|
| 572 |
+
stop = xpx.at(stop)[i].set(True)
|
| 573 |
+
|
| 574 |
+
# With infinite precision, there is a step size below which
|
| 575 |
+
# all smaller step sizes will reduce the error. But in floating point
|
| 576 |
+
# arithmetic, catastrophic cancellation will begin to cause the error
|
| 577 |
+
# to increase again. This heuristic tries to avoid step sizes that are
|
| 578 |
+
# too small. There may be more theoretically sound approaches for
|
| 579 |
+
# detecting a step size that minimizes the total error, but this
|
| 580 |
+
# heuristic seems simple and effective.
|
| 581 |
+
i = (work.error > work.error_last*10) & ~stop
|
| 582 |
+
work.status = xpx.at(work.status)[i].set(_EERRORINCREASE)
|
| 583 |
+
stop = xpx.at(stop)[i].set(True)
|
| 584 |
+
|
| 585 |
+
return stop
|
| 586 |
+
|
| 587 |
+
def post_termination_check(work):
|
| 588 |
+
return
|
| 589 |
+
|
| 590 |
+
def customize_result(res, shape):
|
| 591 |
+
return shape
|
| 592 |
+
|
| 593 |
+
return eim._loop(work, callback, shape, maxiter, func, args, dtype,
|
| 594 |
+
pre_func_eval, post_func_eval, check_termination,
|
| 595 |
+
post_termination_check, customize_result, res_work_pairs,
|
| 596 |
+
xp, preserve_shape)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def _derivative_weights(work, n, xp):
|
| 600 |
+
# This produces the weights of the finite difference formula for a given
|
| 601 |
+
# stencil. In experiments, use of a second-order central difference formula
|
| 602 |
+
# with Richardson extrapolation was more accurate numerically, but it was
|
| 603 |
+
# more complicated, and it would have become even more complicated when
|
| 604 |
+
# adding support for one-sided differences. However, now that all the
|
| 605 |
+
# function evaluation values are stored, they can be processed in whatever
|
| 606 |
+
# way is desired to produce the derivative estimate. We leave alternative
|
| 607 |
+
# approaches to future work. To be more self-contained, here is the theory
|
| 608 |
+
# for deriving the weights below.
|
| 609 |
+
#
|
| 610 |
+
# Recall that the Taylor expansion of a univariate, scalar-values function
|
| 611 |
+
# about a point `x` may be expressed as:
|
| 612 |
+
# f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3)
|
| 613 |
+
# Suppose we evaluate f(x), f(x+h), and f(x-h). We have:
|
| 614 |
+
# f(x) = f(x)
|
| 615 |
+
# f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3)
|
| 616 |
+
# f(x - h) = f(x) - f'(x)*h + f''(x)/2!*h**2 + O(h**3)
|
| 617 |
+
# We can solve for weights `wi` such that:
|
| 618 |
+
# w1*f(x) = w1*(f(x))
|
| 619 |
+
# + w2*f(x + h) = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
|
| 620 |
+
# + w3*f(x - h) = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
|
| 621 |
+
# = 0 + f'(x)*h + 0 + O(h**3)
|
| 622 |
+
# Then
|
| 623 |
+
# f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
|
| 624 |
+
# is a finite difference derivative approximation with error O(h**2),
|
| 625 |
+
# and so it is said to be a "second-order" approximation. Under certain
|
| 626 |
+
# conditions (e.g. well-behaved function, `h` sufficiently small), the
|
| 627 |
+
# error in the approximation will decrease with h**2; that is, if `h` is
|
| 628 |
+
# reduced by a factor of 2, the error is reduced by a factor of 4.
|
| 629 |
+
#
|
| 630 |
+
# By default, we use eighth-order formulae. Our central-difference formula
|
| 631 |
+
# uses abscissae:
|
| 632 |
+
# x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
|
| 633 |
+
# where `c` is the step factor. (Typically, the step factor is greater than
|
| 634 |
+
# one, so the outermost points - as written above - are actually closest to
|
| 635 |
+
# `x`.) This "stencil" is chosen so that each iteration, the step can be
|
| 636 |
+
# reduced by the factor `c`, and most of the function evaluations can be
|
| 637 |
+
# reused with the new step size. For example, in the next iteration, we
|
| 638 |
+
# will have:
|
| 639 |
+
# x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
|
| 640 |
+
# We do not reuse `x-h` and `x+h` for the new derivative estimate.
|
| 641 |
+
# While this would increase the order of the formula and thus the
|
| 642 |
+
# theoretical convergence rate, it is also less stable numerically.
|
| 643 |
+
# (As noted above, there are other ways of processing the values that are
|
| 644 |
+
# more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
|
| 645 |
+
# to simplify future development of this sort of improvement.)
|
| 646 |
+
#
|
| 647 |
+
# The (right) one-sided formula is produced similarly using abscissae
|
| 648 |
+
# x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
|
| 649 |
+
# where `d` is the square root of `c`. (The left one-sided formula simply
|
| 650 |
+
# uses -h.) When the step size is reduced by factor `c = d**2`, we have
|
| 651 |
+
# abscissae:
|
| 652 |
+
# x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
|
| 653 |
+
# `d` is chosen as the square root of `c` so that the rate of the step-size
|
| 654 |
+
# reduction is the same per iteration as in the central difference case.
|
| 655 |
+
# Note that because the central difference formulas are inherently of even
|
| 656 |
+
# order, for simplicity, we use only even-order formulas for one-sided
|
| 657 |
+
# differences, too.
|
| 658 |
+
|
| 659 |
+
# It's possible for the user to specify `fac` in, say, double precision but
|
| 660 |
+
# `x` and `args` in single precision. `fac` gets converted to single
|
| 661 |
+
# precision, but we should always use double precision for the intermediate
|
| 662 |
+
# calculations here to avoid additional error in the weights.
|
| 663 |
+
fac = float(work.fac)
|
| 664 |
+
|
| 665 |
+
# Note that if the user switches back to floating point precision with
|
| 666 |
+
# `x` and `args`, then `fac` will not necessarily equal the (lower
|
| 667 |
+
# precision) cached `_derivative_weights.fac`, and the weights will
|
| 668 |
+
# need to be recalculated. This could be fixed, but it's late, and of
|
| 669 |
+
# low consequence.
|
| 670 |
+
|
| 671 |
+
diff_state = work.diff_state
|
| 672 |
+
if fac != diff_state.fac:
|
| 673 |
+
diff_state.central = []
|
| 674 |
+
diff_state.right = []
|
| 675 |
+
diff_state.fac = fac
|
| 676 |
+
|
| 677 |
+
if len(diff_state.central) != 2*n + 1:
|
| 678 |
+
# Central difference weights. Consider refactoring this; it could
|
| 679 |
+
# probably be more compact.
|
| 680 |
+
# Note: Using NumPy here is OK; we convert to xp-type at the end
|
| 681 |
+
i = np.arange(-n, n + 1)
|
| 682 |
+
p = np.abs(i) - 1. # center point has power `p` -1, but sign `s` is 0
|
| 683 |
+
s = np.sign(i)
|
| 684 |
+
|
| 685 |
+
h = s / fac ** p
|
| 686 |
+
A = np.vander(h, increasing=True).T
|
| 687 |
+
b = np.zeros(2*n + 1)
|
| 688 |
+
b[1] = 1
|
| 689 |
+
weights = np.linalg.solve(A, b)
|
| 690 |
+
|
| 691 |
+
# Enforce identities to improve accuracy
|
| 692 |
+
weights[n] = 0
|
| 693 |
+
for i in range(n):
|
| 694 |
+
weights[-i-1] = -weights[i]
|
| 695 |
+
|
| 696 |
+
# Cache the weights. We only need to calculate them once unless
|
| 697 |
+
# the step factor changes.
|
| 698 |
+
diff_state.central = weights
|
| 699 |
+
|
| 700 |
+
# One-sided difference weights. The left one-sided weights (with
|
| 701 |
+
# negative steps) are simply the negative of the right one-sided
|
| 702 |
+
# weights, so no need to compute them separately.
|
| 703 |
+
i = np.arange(2*n + 1)
|
| 704 |
+
p = i - 1.
|
| 705 |
+
s = np.sign(i)
|
| 706 |
+
|
| 707 |
+
h = s / np.sqrt(fac) ** p
|
| 708 |
+
A = np.vander(h, increasing=True).T
|
| 709 |
+
b = np.zeros(2 * n + 1)
|
| 710 |
+
b[1] = 1
|
| 711 |
+
weights = np.linalg.solve(A, b)
|
| 712 |
+
|
| 713 |
+
diff_state.right = weights
|
| 714 |
+
|
| 715 |
+
return (xp.asarray(diff_state.central, dtype=work.dtype),
|
| 716 |
+
xp.asarray(diff_state.right, dtype=work.dtype))
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
|
| 720 |
+
('dask.array', _dask_reason)], jax_jit=False)
|
| 721 |
+
def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
|
| 722 |
+
step_factor=2.0, step_direction=0):
|
| 723 |
+
r"""Evaluate the Jacobian of a function numerically.
|
| 724 |
+
|
| 725 |
+
Parameters
|
| 726 |
+
----------
|
| 727 |
+
f : callable
|
| 728 |
+
The function whose Jacobian is desired. The signature must be::
|
| 729 |
+
|
| 730 |
+
f(xi: ndarray) -> ndarray
|
| 731 |
+
|
| 732 |
+
where each element of ``xi`` is a finite real. If the function to be
|
| 733 |
+
differentiated accepts additional arguments, wrap it (e.g. using
|
| 734 |
+
`functools.partial` or ``lambda``) and pass the wrapped callable
|
| 735 |
+
into `jacobian`. `f` must not mutate the array ``xi``. See Notes
|
| 736 |
+
regarding vectorization and the dimensionality of the input and output.
|
| 737 |
+
x : float array_like
|
| 738 |
+
Points at which to evaluate the Jacobian. Must have at least one dimension.
|
| 739 |
+
See Notes regarding the dimensionality and vectorization.
|
| 740 |
+
tolerances : dictionary of floats, optional
|
| 741 |
+
Absolute and relative tolerances. Valid keys of the dictionary are:
|
| 742 |
+
|
| 743 |
+
- ``atol`` - absolute tolerance on the derivative
|
| 744 |
+
- ``rtol`` - relative tolerance on the derivative
|
| 745 |
+
|
| 746 |
+
Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
|
| 747 |
+
`atol` is the smallest normal number of the appropriate dtype, and
|
| 748 |
+
the default `rtol` is the square root of the precision of the
|
| 749 |
+
appropriate dtype.
|
| 750 |
+
maxiter : int, default: 10
|
| 751 |
+
The maximum number of iterations of the algorithm to perform. See
|
| 752 |
+
Notes.
|
| 753 |
+
order : int, default: 8
|
| 754 |
+
The (positive integer) order of the finite difference formula to be
|
| 755 |
+
used. Odd integers will be rounded up to the next even integer.
|
| 756 |
+
initial_step : float array_like, default: 0.5
|
| 757 |
+
The (absolute) initial step size for the finite difference derivative
|
| 758 |
+
approximation. Must be broadcastable with `x` and `step_direction`.
|
| 759 |
+
step_factor : float, default: 2.0
|
| 760 |
+
The factor by which the step size is *reduced* in each iteration; i.e.
|
| 761 |
+
the step size in iteration 1 is ``initial_step/step_factor``. If
|
| 762 |
+
``step_factor < 1``, subsequent steps will be greater than the initial
|
| 763 |
+
step; this may be useful if steps smaller than some threshold are
|
| 764 |
+
undesirable (e.g. due to subtractive cancellation error).
|
| 765 |
+
step_direction : integer array_like
|
| 766 |
+
An array representing the direction of the finite difference steps (e.g.
|
| 767 |
+
for use when `x` lies near to the boundary of the domain of the function.)
|
| 768 |
+
Must be broadcastable with `x` and `initial_step`.
|
| 769 |
+
Where 0 (default), central differences are used; where negative (e.g.
|
| 770 |
+
-1), steps are non-positive; and where positive (e.g. 1), all steps are
|
| 771 |
+
non-negative.
|
| 772 |
+
|
| 773 |
+
Returns
|
| 774 |
+
-------
|
| 775 |
+
res : _RichResult
|
| 776 |
+
An object similar to an instance of `scipy.optimize.OptimizeResult` with the
|
| 777 |
+
following attributes. The descriptions are written as though the values will
|
| 778 |
+
be scalars; however, if `f` returns an array, the outputs will be
|
| 779 |
+
arrays of the same shape.
|
| 780 |
+
|
| 781 |
+
success : bool array
|
| 782 |
+
``True`` where the algorithm terminated successfully (status ``0``);
|
| 783 |
+
``False`` otherwise.
|
| 784 |
+
status : int array
|
| 785 |
+
An integer representing the exit status of the algorithm.
|
| 786 |
+
|
| 787 |
+
- ``0`` : The algorithm converged to the specified tolerances.
|
| 788 |
+
- ``-1`` : The error estimate increased, so iteration was terminated.
|
| 789 |
+
- ``-2`` : The maximum number of iterations was reached.
|
| 790 |
+
- ``-3`` : A non-finite value was encountered.
|
| 791 |
+
|
| 792 |
+
df : float array
|
| 793 |
+
The Jacobian of `f` at `x`, if the algorithm terminated
|
| 794 |
+
successfully.
|
| 795 |
+
error : float array
|
| 796 |
+
An estimate of the error: the magnitude of the difference between
|
| 797 |
+
the current estimate of the Jacobian and the estimate in the
|
| 798 |
+
previous iteration.
|
| 799 |
+
nit : int array
|
| 800 |
+
The number of iterations of the algorithm that were performed.
|
| 801 |
+
nfev : int array
|
| 802 |
+
The number of points at which `f` was evaluated.
|
| 803 |
+
|
| 804 |
+
Each element of an attribute is associated with the corresponding
|
| 805 |
+
element of `df`. For instance, element ``i`` of `nfev` is the
|
| 806 |
+
number of points at which `f` was evaluated for the sake of
|
| 807 |
+
computing element ``i`` of `df`.
|
| 808 |
+
|
| 809 |
+
See Also
|
| 810 |
+
--------
|
| 811 |
+
derivative, hessian
|
| 812 |
+
|
| 813 |
+
Notes
|
| 814 |
+
-----
|
| 815 |
+
Suppose we wish to evaluate the Jacobian of a function
|
| 816 |
+
:math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
|
| 817 |
+
``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
|
| 818 |
+
respectively, and let ``...`` represent an arbitrary tuple of integers.
|
| 819 |
+
If we wish to evaluate the Jacobian at a single point, then:
|
| 820 |
+
|
| 821 |
+
- argument `x` must be an array of shape ``(m,)``
|
| 822 |
+
- argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
|
| 823 |
+
The first axis represents the :math:`m` inputs of :math:`f`; the remainder
|
| 824 |
+
are for evaluating the function at multiple points in a single call.
|
| 825 |
+
- argument `f` must return an array of shape ``(n, ...)``. The first
|
| 826 |
+
axis represents the :math:`n` outputs of :math:`f`; the remainder
|
| 827 |
+
are for the result of evaluating the function at multiple points.
|
| 828 |
+
- attribute ``df`` of the result object will be an array of shape ``(n, m)``,
|
| 829 |
+
the Jacobian.
|
| 830 |
+
|
| 831 |
+
This function is also vectorized in the sense that the Jacobian can be
|
| 832 |
+
evaluated at ``k`` points in a single call. In this case, `x` would be an
|
| 833 |
+
array of shape ``(m, k)``, `f` would accept an array of shape
|
| 834 |
+
``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
|
| 835 |
+
attribute of the result would have shape ``(n, m, k)``.
|
| 836 |
+
|
| 837 |
+
Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
|
| 838 |
+
only accept an array of shape ``(m,)``. A simple solution to satisfy the required
|
| 839 |
+
interface is to wrap ``f_not_vectorized`` as follows::
|
| 840 |
+
|
| 841 |
+
def f(x):
|
| 842 |
+
return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)
|
| 843 |
+
|
| 844 |
+
Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
|
| 845 |
+
only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
|
| 846 |
+
consider::
|
| 847 |
+
|
| 848 |
+
def f(x):
|
| 849 |
+
m, batch = x.shape[0], x.shape[1:] # x.shape is (m, ...)
|
| 850 |
+
x = np.reshape(x, (m, -1)) # `-1` is short for q = prod(batch)
|
| 851 |
+
res = f_vec_q(x) # pass shape (m, q) to function
|
| 852 |
+
n = res.shape[0]
|
| 853 |
+
return np.reshape(res, (n,) + batch) # return shape (n, ...)
|
| 854 |
+
|
| 855 |
+
Then pass the wrapped callable ``f`` as the first argument of `jacobian`.
|
| 856 |
+
|
| 857 |
+
References
|
| 858 |
+
----------
|
| 859 |
+
.. [1] Jacobian matrix and determinant, *Wikipedia*,
|
| 860 |
+
https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
|
| 861 |
+
|
| 862 |
+
Examples
|
| 863 |
+
--------
|
| 864 |
+
The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
|
| 865 |
+
the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
|
| 866 |
+
array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
|
| 867 |
+
to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
|
| 868 |
+
at ``[0.5, 0.5, 0.5]``.
|
| 869 |
+
|
| 870 |
+
>>> import numpy as np
|
| 871 |
+
>>> from scipy.differentiate import jacobian
|
| 872 |
+
>>> from scipy.optimize import rosen, rosen_der
|
| 873 |
+
>>> m = 3
|
| 874 |
+
>>> x = np.full(m, 0.5)
|
| 875 |
+
>>> res = jacobian(rosen, x)
|
| 876 |
+
>>> ref = rosen_der(x) # reference value of the gradient
|
| 877 |
+
>>> res.df, ref
|
| 878 |
+
(array([-51., -1., 50.]), array([-51., -1., 50.]))
|
| 879 |
+
|
| 880 |
+
As an example of a function with multiple outputs, consider Example 4
|
| 881 |
+
from [1]_.
|
| 882 |
+
|
| 883 |
+
>>> def f(x):
|
| 884 |
+
... x1, x2, x3 = x
|
| 885 |
+
... return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]
|
| 886 |
+
|
| 887 |
+
The true Jacobian is given by:
|
| 888 |
+
|
| 889 |
+
>>> def df(x):
|
| 890 |
+
... x1, x2, x3 = x
|
| 891 |
+
... one = np.ones_like(x1)
|
| 892 |
+
... return [[one, 0*one, 0*one],
|
| 893 |
+
... [0*one, 0*one, 5*one],
|
| 894 |
+
... [0*one, 8*x2, -2*one],
|
| 895 |
+
... [x3*np.cos(x1), 0*one, np.sin(x1)]]
|
| 896 |
+
|
| 897 |
+
Evaluate the Jacobian at an arbitrary point.
|
| 898 |
+
|
| 899 |
+
>>> rng = np.random.default_rng(389252938452)
|
| 900 |
+
>>> x = rng.random(size=3)
|
| 901 |
+
>>> res = jacobian(f, x)
|
| 902 |
+
>>> ref = df(x)
|
| 903 |
+
>>> res.df.shape == (4, 3)
|
| 904 |
+
True
|
| 905 |
+
>>> np.allclose(res.df, ref)
|
| 906 |
+
True
|
| 907 |
+
|
| 908 |
+
Evaluate the Jacobian at 10 arbitrary points in a single call.
|
| 909 |
+
|
| 910 |
+
>>> x = rng.random(size=(3, 10))
|
| 911 |
+
>>> res = jacobian(f, x)
|
| 912 |
+
>>> ref = df(x)
|
| 913 |
+
>>> res.df.shape == (4, 3, 10)
|
| 914 |
+
True
|
| 915 |
+
>>> np.allclose(res.df, ref)
|
| 916 |
+
True
|
| 917 |
+
|
| 918 |
+
"""
|
| 919 |
+
xp = array_namespace(x)
|
| 920 |
+
x0 = xp_promote(x, force_floating=True, xp=xp)
|
| 921 |
+
|
| 922 |
+
if x0.ndim < 1:
|
| 923 |
+
message = "Argument `x` must be at least 1-D."
|
| 924 |
+
raise ValueError(message)
|
| 925 |
+
|
| 926 |
+
m = x0.shape[0]
|
| 927 |
+
i = xp.arange(m)
|
| 928 |
+
|
| 929 |
+
def wrapped(x):
|
| 930 |
+
p = () if x.ndim == x0.ndim else (x.shape[-1],) # number of abscissae
|
| 931 |
+
|
| 932 |
+
new_shape = (m, m) + x0.shape[1:] + p
|
| 933 |
+
xph = xp.expand_dims(x0, axis=1)
|
| 934 |
+
if x.ndim != x0.ndim:
|
| 935 |
+
xph = xp.expand_dims(xph, axis=-1)
|
| 936 |
+
xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
|
| 937 |
+
xph = xpx.at(xph)[i, i].set(x)
|
| 938 |
+
return f(xph)
|
| 939 |
+
|
| 940 |
+
res = derivative(wrapped, x, tolerances=tolerances,
|
| 941 |
+
maxiter=maxiter, order=order, initial_step=initial_step,
|
| 942 |
+
step_factor=step_factor, preserve_shape=True,
|
| 943 |
+
step_direction=step_direction)
|
| 944 |
+
|
| 945 |
+
del res.x # the user knows `x`, and the way it gets broadcasted is meaningless here
|
| 946 |
+
return res
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
|
| 950 |
+
('dask.array', _dask_reason)], jax_jit=False)
|
| 951 |
+
def hessian(f, x, *, tolerances=None, maxiter=10,
|
| 952 |
+
order=8, initial_step=0.5, step_factor=2.0):
|
| 953 |
+
r"""Evaluate the Hessian of a function numerically.
|
| 954 |
+
|
| 955 |
+
Parameters
|
| 956 |
+
----------
|
| 957 |
+
f : callable
|
| 958 |
+
The function whose Hessian is desired. The signature must be::
|
| 959 |
+
|
| 960 |
+
f(xi: ndarray) -> ndarray
|
| 961 |
+
|
| 962 |
+
where each element of ``xi`` is a finite real. If the function to be
|
| 963 |
+
differentiated accepts additional arguments, wrap it (e.g. using
|
| 964 |
+
`functools.partial` or ``lambda``) and pass the wrapped callable
|
| 965 |
+
into `hessian`. `f` must not mutate the array ``xi``. See Notes
|
| 966 |
+
regarding vectorization and the dimensionality of the input and output.
|
| 967 |
+
x : float array_like
|
| 968 |
+
Points at which to evaluate the Hessian. Must have at least one dimension.
|
| 969 |
+
See Notes regarding the dimensionality and vectorization.
|
| 970 |
+
tolerances : dictionary of floats, optional
|
| 971 |
+
Absolute and relative tolerances. Valid keys of the dictionary are:
|
| 972 |
+
|
| 973 |
+
- ``atol`` - absolute tolerance on the derivative
|
| 974 |
+
- ``rtol`` - relative tolerance on the derivative
|
| 975 |
+
|
| 976 |
+
Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
|
| 977 |
+
`atol` is the smallest normal number of the appropriate dtype, and
|
| 978 |
+
the default `rtol` is the square root of the precision of the
|
| 979 |
+
appropriate dtype.
|
| 980 |
+
order : int, default: 8
|
| 981 |
+
The (positive integer) order of the finite difference formula to be
|
| 982 |
+
used. Odd integers will be rounded up to the next even integer.
|
| 983 |
+
initial_step : float, default: 0.5
|
| 984 |
+
The (absolute) initial step size for the finite difference derivative
|
| 985 |
+
approximation.
|
| 986 |
+
step_factor : float, default: 2.0
|
| 987 |
+
The factor by which the step size is *reduced* in each iteration; i.e.
|
| 988 |
+
the step size in iteration 1 is ``initial_step/step_factor``. If
|
| 989 |
+
``step_factor < 1``, subsequent steps will be greater than the initial
|
| 990 |
+
step; this may be useful if steps smaller than some threshold are
|
| 991 |
+
undesirable (e.g. due to subtractive cancellation error).
|
| 992 |
+
maxiter : int, default: 10
|
| 993 |
+
The maximum number of iterations of the algorithm to perform. See
|
| 994 |
+
Notes.
|
| 995 |
+
|
| 996 |
+
Returns
|
| 997 |
+
-------
|
| 998 |
+
res : _RichResult
|
| 999 |
+
An object similar to an instance of `scipy.optimize.OptimizeResult` with the
|
| 1000 |
+
following attributes. The descriptions are written as though the values will
|
| 1001 |
+
be scalars; however, if `f` returns an array, the outputs will be
|
| 1002 |
+
arrays of the same shape.
|
| 1003 |
+
|
| 1004 |
+
success : bool array
|
| 1005 |
+
``True`` where the algorithm terminated successfully (status ``0``);
|
| 1006 |
+
``False`` otherwise.
|
| 1007 |
+
status : int array
|
| 1008 |
+
An integer representing the exit status of the algorithm.
|
| 1009 |
+
|
| 1010 |
+
- ``0`` : The algorithm converged to the specified tolerances.
|
| 1011 |
+
- ``-1`` : The error estimate increased, so iteration was terminated.
|
| 1012 |
+
- ``-2`` : The maximum number of iterations was reached.
|
| 1013 |
+
- ``-3`` : A non-finite value was encountered.
|
| 1014 |
+
|
| 1015 |
+
ddf : float array
|
| 1016 |
+
The Hessian of `f` at `x`, if the algorithm terminated
|
| 1017 |
+
successfully.
|
| 1018 |
+
error : float array
|
| 1019 |
+
An estimate of the error: the magnitude of the difference between
|
| 1020 |
+
the current estimate of the Hessian and the estimate in the
|
| 1021 |
+
previous iteration.
|
| 1022 |
+
nfev : int array
|
| 1023 |
+
The number of points at which `f` was evaluated.
|
| 1024 |
+
|
| 1025 |
+
Each element of an attribute is associated with the corresponding
|
| 1026 |
+
element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
|
| 1027 |
+
number of points at which `f` was evaluated for the sake of
|
| 1028 |
+
computing element ``[i, j]`` of `ddf`.
|
| 1029 |
+
|
| 1030 |
+
See Also
|
| 1031 |
+
--------
|
| 1032 |
+
derivative, jacobian
|
| 1033 |
+
|
| 1034 |
+
Notes
|
| 1035 |
+
-----
|
| 1036 |
+
Suppose we wish to evaluate the Hessian of a function
|
| 1037 |
+
:math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
|
| 1038 |
+
``m`` the positive integer value of :math:`m`. If we wish to evaluate
|
| 1039 |
+
the Hessian at a single point, then:
|
| 1040 |
+
|
| 1041 |
+
- argument `x` must be an array of shape ``(m,)``
|
| 1042 |
+
- argument `f` must be vectorized to accept an array of shape
|
| 1043 |
+
``(m, ...)``. The first axis represents the :math:`m` inputs of
|
| 1044 |
+
:math:`f`; the remaining axes indicated by ellipses are for evaluating
|
| 1045 |
+
the function at several abscissae in a single call.
|
| 1046 |
+
- argument `f` must return an array of shape ``(...)``.
|
| 1047 |
+
- attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
|
| 1048 |
+
the Hessian.
|
| 1049 |
+
|
| 1050 |
+
This function is also vectorized in the sense that the Hessian can be
|
| 1051 |
+
evaluated at ``k`` points in a single call. In this case, `x` would be an
|
| 1052 |
+
array of shape ``(m, k)``, `f` would accept an array of shape
|
| 1053 |
+
``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
|
| 1054 |
+
attribute of the result would have shape ``(m, m, k)``. Note that the
|
| 1055 |
+
axis associated with the ``k`` points is included within the axes
|
| 1056 |
+
denoted by ``(...)``.
|
| 1057 |
+
|
| 1058 |
+
Currently, `hessian` is implemented by nesting calls to `jacobian`.
|
| 1059 |
+
All options passed to `hessian` are used for both the inner and outer
|
| 1060 |
+
calls with one exception: the `rtol` used in the inner `jacobian` call
|
| 1061 |
+
is tightened by a factor of 100 with the expectation that the inner
|
| 1062 |
+
error can be ignored. A consequence is that `rtol` should not be set
|
| 1063 |
+
less than 100 times the precision of the dtype of `x`; a warning is
|
| 1064 |
+
emitted otherwise.
|
| 1065 |
+
|
| 1066 |
+
References
|
| 1067 |
+
----------
|
| 1068 |
+
.. [1] Hessian matrix, *Wikipedia*,
|
| 1069 |
+
https://en.wikipedia.org/wiki/Hessian_matrix
|
| 1070 |
+
|
| 1071 |
+
Examples
|
| 1072 |
+
--------
|
| 1073 |
+
The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
|
| 1074 |
+
the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
|
| 1075 |
+
array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
|
| 1076 |
+
wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.
|
| 1077 |
+
|
| 1078 |
+
>>> import numpy as np
|
| 1079 |
+
>>> from scipy.differentiate import hessian
|
| 1080 |
+
>>> from scipy.optimize import rosen, rosen_hess
|
| 1081 |
+
>>> m = 3
|
| 1082 |
+
>>> x = np.full(m, 0.5)
|
| 1083 |
+
>>> res = hessian(rosen, x)
|
| 1084 |
+
>>> ref = rosen_hess(x) # reference value of the Hessian
|
| 1085 |
+
>>> np.allclose(res.ddf, ref)
|
| 1086 |
+
True
|
| 1087 |
+
|
| 1088 |
+
`hessian` is vectorized to evaluate the Hessian at multiple points
|
| 1089 |
+
in a single call.
|
| 1090 |
+
|
| 1091 |
+
>>> rng = np.random.default_rng(4589245925010)
|
| 1092 |
+
>>> x = rng.random((m, 10))
|
| 1093 |
+
>>> res = hessian(rosen, x)
|
| 1094 |
+
>>> ref = [rosen_hess(xi) for xi in x.T]
|
| 1095 |
+
>>> ref = np.moveaxis(ref, 0, -1)
|
| 1096 |
+
>>> np.allclose(res.ddf, ref)
|
| 1097 |
+
True
|
| 1098 |
+
|
| 1099 |
+
"""
|
| 1100 |
+
# todo:
|
| 1101 |
+
# - add ability to vectorize over additional parameters (*args?)
|
| 1102 |
+
# - error estimate stack with inner jacobian (or use legit 2D stencil)
|
| 1103 |
+
|
| 1104 |
+
kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step,
|
| 1105 |
+
step_factor=step_factor)
|
| 1106 |
+
tolerances = {} if tolerances is None else tolerances
|
| 1107 |
+
atol = tolerances.get('atol', None)
|
| 1108 |
+
rtol = tolerances.get('rtol', None)
|
| 1109 |
+
|
| 1110 |
+
xp = array_namespace(x)
|
| 1111 |
+
x0 = xp_promote(x, force_floating=True, xp=xp)
|
| 1112 |
+
|
| 1113 |
+
finfo = xp.finfo(x0.dtype)
|
| 1114 |
+
rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `derivative`
|
| 1115 |
+
|
| 1116 |
+
# tighten the inner tolerance to make the inner error negligible
|
| 1117 |
+
rtol_min = finfo.eps * 100
|
| 1118 |
+
message = (f"The specified `{rtol=}`, but error estimates are likely to be "
|
| 1119 |
+
f"unreliable when `rtol < {rtol_min}`.")
|
| 1120 |
+
if 0 < rtol < rtol_min: # rtol <= 0 is an error
|
| 1121 |
+
warnings.warn(message, RuntimeWarning, stacklevel=2)
|
| 1122 |
+
rtol = rtol_min
|
| 1123 |
+
|
| 1124 |
+
def df(x):
|
| 1125 |
+
tolerances = dict(rtol=rtol/100, atol=atol)
|
| 1126 |
+
temp = jacobian(f, x, tolerances=tolerances, **kwargs)
|
| 1127 |
+
nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
|
| 1128 |
+
return temp.df
|
| 1129 |
+
|
| 1130 |
+
nfev = [] # track inner function evaluations
|
| 1131 |
+
res = jacobian(df, x, tolerances=tolerances, **kwargs) # jacobian of jacobian
|
| 1132 |
+
|
| 1133 |
+
nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
|
| 1134 |
+
res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64) # appease torch
|
| 1135 |
+
res.nfev = xp.take_along_axis(nfev, res_nit, axis=0)[0]
|
| 1136 |
+
res.ddf = res.df
|
| 1137 |
+
del res.df # this is renamed to ddf
|
| 1138 |
+
del res.nit # this is only the outer-jacobian nit
|
| 1139 |
+
|
| 1140 |
+
return res
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/__init__.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
=========================================================
|
| 3 |
+
Legacy discrete Fourier transforms (:mod:`scipy.fftpack`)
|
| 4 |
+
=========================================================
|
| 5 |
+
|
| 6 |
+
.. legacy::
|
| 7 |
+
|
| 8 |
+
New code should use :mod:`scipy.fft`.
|
| 9 |
+
|
| 10 |
+
Fast Fourier Transforms (FFTs)
|
| 11 |
+
==============================
|
| 12 |
+
|
| 13 |
+
.. autosummary::
|
| 14 |
+
:toctree: generated/
|
| 15 |
+
|
| 16 |
+
fft - Fast (discrete) Fourier Transform (FFT)
|
| 17 |
+
ifft - Inverse FFT
|
| 18 |
+
fft2 - 2-D FFT
|
| 19 |
+
ifft2 - 2-D inverse FFT
|
| 20 |
+
fftn - N-D FFT
|
| 21 |
+
ifftn - N-D inverse FFT
|
| 22 |
+
rfft - FFT of strictly real-valued sequence
|
| 23 |
+
irfft - Inverse of rfft
|
| 24 |
+
dct - Discrete cosine transform
|
| 25 |
+
idct - Inverse discrete cosine transform
|
| 26 |
+
dctn - N-D Discrete cosine transform
|
| 27 |
+
idctn - N-D Inverse discrete cosine transform
|
| 28 |
+
dst - Discrete sine transform
|
| 29 |
+
idst - Inverse discrete sine transform
|
| 30 |
+
dstn - N-D Discrete sine transform
|
| 31 |
+
idstn - N-D Inverse discrete sine transform
|
| 32 |
+
|
| 33 |
+
Differential and pseudo-differential operators
|
| 34 |
+
==============================================
|
| 35 |
+
|
| 36 |
+
.. autosummary::
|
| 37 |
+
:toctree: generated/
|
| 38 |
+
|
| 39 |
+
diff - Differentiation and integration of periodic sequences
|
| 40 |
+
tilbert - Tilbert transform: cs_diff(x,h,h)
|
| 41 |
+
itilbert - Inverse Tilbert transform: sc_diff(x,h,h)
|
| 42 |
+
hilbert - Hilbert transform: cs_diff(x,inf,inf)
|
| 43 |
+
ihilbert - Inverse Hilbert transform: sc_diff(x,inf,inf)
|
| 44 |
+
cs_diff - cosh/sinh pseudo-derivative of periodic sequences
|
| 45 |
+
sc_diff - sinh/cosh pseudo-derivative of periodic sequences
|
| 46 |
+
ss_diff - sinh/sinh pseudo-derivative of periodic sequences
|
| 47 |
+
cc_diff - cosh/cosh pseudo-derivative of periodic sequences
|
| 48 |
+
shift - Shift periodic sequences
|
| 49 |
+
|
| 50 |
+
Helper functions
|
| 51 |
+
================
|
| 52 |
+
|
| 53 |
+
.. autosummary::
|
| 54 |
+
:toctree: generated/
|
| 55 |
+
|
| 56 |
+
fftshift - Shift the zero-frequency component to the center of the spectrum
|
| 57 |
+
ifftshift - The inverse of `fftshift`
|
| 58 |
+
fftfreq - Return the Discrete Fourier Transform sample frequencies
|
| 59 |
+
rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
|
| 60 |
+
next_fast_len - Find the optimal length to zero-pad an FFT for speed
|
| 61 |
+
|
| 62 |
+
Note that ``fftshift``, ``ifftshift`` and ``fftfreq`` are numpy functions
|
| 63 |
+
exposed by ``fftpack``; importing them from ``numpy`` should be preferred.
|
| 64 |
+
|
| 65 |
+
Convolutions (:mod:`scipy.fftpack.convolve`)
|
| 66 |
+
============================================
|
| 67 |
+
|
| 68 |
+
.. module:: scipy.fftpack.convolve
|
| 69 |
+
|
| 70 |
+
.. autosummary::
|
| 71 |
+
:toctree: generated/
|
| 72 |
+
|
| 73 |
+
convolve
|
| 74 |
+
convolve_z
|
| 75 |
+
init_convolution_kernel
|
| 76 |
+
destroy_convolve_cache
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
|
| 82 |
+
'fft2','ifft2',
|
| 83 |
+
'diff',
|
| 84 |
+
'tilbert','itilbert','hilbert','ihilbert',
|
| 85 |
+
'sc_diff','cs_diff','cc_diff','ss_diff',
|
| 86 |
+
'shift',
|
| 87 |
+
'fftfreq', 'rfftfreq',
|
| 88 |
+
'fftshift', 'ifftshift',
|
| 89 |
+
'next_fast_len',
|
| 90 |
+
'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
from ._basic import *
|
| 94 |
+
from ._pseudo_diffs import *
|
| 95 |
+
from ._helper import *
|
| 96 |
+
from ._realtransforms import *
|
| 97 |
+
|
| 98 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
| 99 |
+
from . import basic, helper, pseudo_diffs, realtransforms
|
| 100 |
+
|
| 101 |
+
from scipy._lib._testutils import PytestTester
|
| 102 |
+
test = PytestTester(__name__)
|
| 103 |
+
del PytestTester
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_basic.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Discrete Fourier Transforms - _basic.py
|
| 3 |
+
"""
|
| 4 |
+
# Created by Pearu Peterson, August,September 2002
|
| 5 |
+
__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
|
| 6 |
+
'fft2','ifft2']
|
| 7 |
+
|
| 8 |
+
from scipy.fft import _pocketfft
|
| 9 |
+
from ._helper import _good_shape
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def fft(x, n=None, axis=-1, overwrite_x=False):
|
| 13 |
+
"""
|
| 14 |
+
Return discrete Fourier transform of real or complex sequence.
|
| 15 |
+
|
| 16 |
+
The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
|
| 17 |
+
|
| 18 |
+
``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
x : array_like
|
| 23 |
+
Array to Fourier transform.
|
| 24 |
+
n : int, optional
|
| 25 |
+
Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
|
| 26 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
| 27 |
+
default results in ``n = x.shape[axis]``.
|
| 28 |
+
axis : int, optional
|
| 29 |
+
Axis along which the fft's are computed; the default is over the
|
| 30 |
+
last axis (i.e., ``axis=-1``).
|
| 31 |
+
overwrite_x : bool, optional
|
| 32 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 33 |
+
|
| 34 |
+
Returns
|
| 35 |
+
-------
|
| 36 |
+
z : complex ndarray
|
| 37 |
+
with the elements::
|
| 38 |
+
|
| 39 |
+
[y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)] if n is even
|
| 40 |
+
[y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)] if n is odd
|
| 41 |
+
|
| 42 |
+
where::
|
| 43 |
+
|
| 44 |
+
y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
|
| 45 |
+
|
| 46 |
+
See Also
|
| 47 |
+
--------
|
| 48 |
+
ifft : Inverse FFT
|
| 49 |
+
rfft : FFT of a real sequence
|
| 50 |
+
|
| 51 |
+
Notes
|
| 52 |
+
-----
|
| 53 |
+
The packing of the result is "standard": If ``A = fft(a, n)``, then
|
| 54 |
+
``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
|
| 55 |
+
positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
|
| 56 |
+
terms, in order of decreasingly negative frequency. So ,for an 8-point
|
| 57 |
+
transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
|
| 58 |
+
To rearrange the fft output so that the zero-frequency component is
|
| 59 |
+
centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use `fftshift`.
|
| 60 |
+
|
| 61 |
+
Both single and double precision routines are implemented. Half precision
|
| 62 |
+
inputs will be converted to single precision. Non-floating-point inputs
|
| 63 |
+
will be converted to double precision. Long-double precision inputs are
|
| 64 |
+
not supported.
|
| 65 |
+
|
| 66 |
+
This function is most efficient when `n` is a power of two, and least
|
| 67 |
+
efficient when `n` is prime.
|
| 68 |
+
|
| 69 |
+
Note that if ``x`` is real-valued, then ``A[j] == A[n-j].conjugate()``.
|
| 70 |
+
If ``x`` is real-valued and ``n`` is even, then ``A[n/2]`` is real.
|
| 71 |
+
|
| 72 |
+
If the data type of `x` is real, a "real FFT" algorithm is automatically
|
| 73 |
+
used, which roughly halves the computation time. To increase efficiency
|
| 74 |
+
a little further, use `rfft`, which does the same calculation, but only
|
| 75 |
+
outputs half of the symmetrical spectrum. If the data is both real and
|
| 76 |
+
symmetrical, the `dct` can again double the efficiency by generating
|
| 77 |
+
half of the spectrum from half of the signal.
|
| 78 |
+
|
| 79 |
+
Examples
|
| 80 |
+
--------
|
| 81 |
+
>>> import numpy as np
|
| 82 |
+
>>> from scipy.fftpack import fft, ifft
|
| 83 |
+
>>> x = np.arange(5)
|
| 84 |
+
>>> np.allclose(fft(ifft(x)), x, atol=1e-15) # within numerical accuracy.
|
| 85 |
+
True
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
return _pocketfft.fft(x, n, axis, None, overwrite_x)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def ifft(x, n=None, axis=-1, overwrite_x=False):
|
| 92 |
+
"""
|
| 93 |
+
Return discrete inverse Fourier transform of real or complex sequence.
|
| 94 |
+
|
| 95 |
+
The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
|
| 96 |
+
|
| 97 |
+
``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.
|
| 98 |
+
|
| 99 |
+
Parameters
|
| 100 |
+
----------
|
| 101 |
+
x : array_like
|
| 102 |
+
Transformed data to invert.
|
| 103 |
+
n : int, optional
|
| 104 |
+
Length of the inverse Fourier transform. If ``n < x.shape[axis]``,
|
| 105 |
+
`x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded.
|
| 106 |
+
The default results in ``n = x.shape[axis]``.
|
| 107 |
+
axis : int, optional
|
| 108 |
+
Axis along which the ifft's are computed; the default is over the
|
| 109 |
+
last axis (i.e., ``axis=-1``).
|
| 110 |
+
overwrite_x : bool, optional
|
| 111 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 112 |
+
|
| 113 |
+
Returns
|
| 114 |
+
-------
|
| 115 |
+
ifft : ndarray of floats
|
| 116 |
+
The inverse discrete Fourier transform.
|
| 117 |
+
|
| 118 |
+
See Also
|
| 119 |
+
--------
|
| 120 |
+
fft : Forward FFT
|
| 121 |
+
|
| 122 |
+
Notes
|
| 123 |
+
-----
|
| 124 |
+
Both single and double precision routines are implemented. Half precision
|
| 125 |
+
inputs will be converted to single precision. Non-floating-point inputs
|
| 126 |
+
will be converted to double precision. Long-double precision inputs are
|
| 127 |
+
not supported.
|
| 128 |
+
|
| 129 |
+
This function is most efficient when `n` is a power of two, and least
|
| 130 |
+
efficient when `n` is prime.
|
| 131 |
+
|
| 132 |
+
If the data type of `x` is real, a "real IFFT" algorithm is automatically
|
| 133 |
+
used, which roughly halves the computation time.
|
| 134 |
+
|
| 135 |
+
Examples
|
| 136 |
+
--------
|
| 137 |
+
>>> from scipy.fftpack import fft, ifft
|
| 138 |
+
>>> import numpy as np
|
| 139 |
+
>>> x = np.arange(5)
|
| 140 |
+
>>> np.allclose(ifft(fft(x)), x, atol=1e-15) # within numerical accuracy.
|
| 141 |
+
True
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
return _pocketfft.ifft(x, n, axis, None, overwrite_x)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def rfft(x, n=None, axis=-1, overwrite_x=False):
|
| 148 |
+
"""
|
| 149 |
+
Discrete Fourier transform of a real sequence.
|
| 150 |
+
|
| 151 |
+
Parameters
|
| 152 |
+
----------
|
| 153 |
+
x : array_like, real-valued
|
| 154 |
+
The data to transform.
|
| 155 |
+
n : int, optional
|
| 156 |
+
Defines the length of the Fourier transform. If `n` is not specified
|
| 157 |
+
(the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``,
|
| 158 |
+
`x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded.
|
| 159 |
+
axis : int, optional
|
| 160 |
+
The axis along which the transform is applied. The default is the
|
| 161 |
+
last axis.
|
| 162 |
+
overwrite_x : bool, optional
|
| 163 |
+
If set to true, the contents of `x` can be overwritten. Default is
|
| 164 |
+
False.
|
| 165 |
+
|
| 166 |
+
Returns
|
| 167 |
+
-------
|
| 168 |
+
z : real ndarray
|
| 169 |
+
The returned real array contains::
|
| 170 |
+
|
| 171 |
+
[y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even
|
| 172 |
+
[y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd
|
| 173 |
+
|
| 174 |
+
where::
|
| 175 |
+
|
| 176 |
+
y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n)
|
| 177 |
+
j = 0..n-1
|
| 178 |
+
|
| 179 |
+
See Also
|
| 180 |
+
--------
|
| 181 |
+
fft, irfft, scipy.fft.rfft
|
| 182 |
+
|
| 183 |
+
Notes
|
| 184 |
+
-----
|
| 185 |
+
Within numerical accuracy, ``y == rfft(irfft(y))``.
|
| 186 |
+
|
| 187 |
+
Both single and double precision routines are implemented. Half precision
|
| 188 |
+
inputs will be converted to single precision. Non-floating-point inputs
|
| 189 |
+
will be converted to double precision. Long-double precision inputs are
|
| 190 |
+
not supported.
|
| 191 |
+
|
| 192 |
+
To get an output with a complex datatype, consider using the newer
|
| 193 |
+
function `scipy.fft.rfft`.
|
| 194 |
+
|
| 195 |
+
Examples
|
| 196 |
+
--------
|
| 197 |
+
>>> from scipy.fftpack import fft, rfft
|
| 198 |
+
>>> a = [9, -9, 1, 3]
|
| 199 |
+
>>> fft(a)
|
| 200 |
+
array([ 4. +0.j, 8.+12.j, 16. +0.j, 8.-12.j])
|
| 201 |
+
>>> rfft(a)
|
| 202 |
+
array([ 4., 8., 12., 16.])
|
| 203 |
+
|
| 204 |
+
"""
|
| 205 |
+
return _pocketfft.rfft_fftpack(x, n, axis, None, overwrite_x)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def irfft(x, n=None, axis=-1, overwrite_x=False):
|
| 209 |
+
"""
|
| 210 |
+
Return inverse discrete Fourier transform of real sequence x.
|
| 211 |
+
|
| 212 |
+
The contents of `x` are interpreted as the output of the `rfft`
|
| 213 |
+
function.
|
| 214 |
+
|
| 215 |
+
Parameters
|
| 216 |
+
----------
|
| 217 |
+
x : array_like
|
| 218 |
+
Transformed data to invert.
|
| 219 |
+
n : int, optional
|
| 220 |
+
Length of the inverse Fourier transform.
|
| 221 |
+
If n < x.shape[axis], x is truncated.
|
| 222 |
+
If n > x.shape[axis], x is zero-padded.
|
| 223 |
+
The default results in n = x.shape[axis].
|
| 224 |
+
axis : int, optional
|
| 225 |
+
Axis along which the ifft's are computed; the default is over
|
| 226 |
+
the last axis (i.e., axis=-1).
|
| 227 |
+
overwrite_x : bool, optional
|
| 228 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 229 |
+
|
| 230 |
+
Returns
|
| 231 |
+
-------
|
| 232 |
+
irfft : ndarray of floats
|
| 233 |
+
The inverse discrete Fourier transform.
|
| 234 |
+
|
| 235 |
+
See Also
|
| 236 |
+
--------
|
| 237 |
+
rfft, ifft, scipy.fft.irfft
|
| 238 |
+
|
| 239 |
+
Notes
|
| 240 |
+
-----
|
| 241 |
+
The returned real array contains::
|
| 242 |
+
|
| 243 |
+
[y(0),y(1),...,y(n-1)]
|
| 244 |
+
|
| 245 |
+
where for n is even::
|
| 246 |
+
|
| 247 |
+
y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
|
| 248 |
+
* exp(sqrt(-1)*j*k* 2*pi/n)
|
| 249 |
+
+ c.c. + x[0] + (-1)**(j) x[n-1])
|
| 250 |
+
|
| 251 |
+
and for n is odd::
|
| 252 |
+
|
| 253 |
+
y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
|
| 254 |
+
* exp(sqrt(-1)*j*k* 2*pi/n)
|
| 255 |
+
+ c.c. + x[0])
|
| 256 |
+
|
| 257 |
+
c.c. denotes complex conjugate of preceding expression.
|
| 258 |
+
|
| 259 |
+
For details on input parameters, see `rfft`.
|
| 260 |
+
|
| 261 |
+
To process (conjugate-symmetric) frequency-domain data with a complex
|
| 262 |
+
datatype, consider using the newer function `scipy.fft.irfft`.
|
| 263 |
+
|
| 264 |
+
Examples
|
| 265 |
+
--------
|
| 266 |
+
>>> from scipy.fftpack import rfft, irfft
|
| 267 |
+
>>> a = [1.0, 2.0, 3.0, 4.0, 5.0]
|
| 268 |
+
>>> irfft(a)
|
| 269 |
+
array([ 2.6 , -3.16405192, 1.24398433, -1.14955713, 1.46962473])
|
| 270 |
+
>>> irfft(rfft(a))
|
| 271 |
+
array([1., 2., 3., 4., 5.])
|
| 272 |
+
|
| 273 |
+
"""
|
| 274 |
+
return _pocketfft.irfft_fftpack(x, n, axis, None, overwrite_x)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def fftn(x, shape=None, axes=None, overwrite_x=False):
|
| 278 |
+
"""
|
| 279 |
+
Return multidimensional discrete Fourier transform.
|
| 280 |
+
|
| 281 |
+
The returned array contains::
|
| 282 |
+
|
| 283 |
+
y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
|
| 284 |
+
x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i)
|
| 285 |
+
|
| 286 |
+
where d = len(x.shape) and n = x.shape.
|
| 287 |
+
|
| 288 |
+
Parameters
|
| 289 |
+
----------
|
| 290 |
+
x : array_like
|
| 291 |
+
The (N-D) array to transform.
|
| 292 |
+
shape : int or array_like of ints or None, optional
|
| 293 |
+
The shape of the result. If both `shape` and `axes` (see below) are
|
| 294 |
+
None, `shape` is ``x.shape``; if `shape` is None but `axes` is
|
| 295 |
+
not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
|
| 296 |
+
If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
|
| 297 |
+
If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
|
| 298 |
+
length ``shape[i]``.
|
| 299 |
+
If any element of `shape` is -1, the size of the corresponding
|
| 300 |
+
dimension of `x` is used.
|
| 301 |
+
axes : int or array_like of ints or None, optional
|
| 302 |
+
The axes of `x` (`y` if `shape` is not None) along which the
|
| 303 |
+
transform is applied.
|
| 304 |
+
The default is over all axes.
|
| 305 |
+
overwrite_x : bool, optional
|
| 306 |
+
If True, the contents of `x` can be destroyed. Default is False.
|
| 307 |
+
|
| 308 |
+
Returns
|
| 309 |
+
-------
|
| 310 |
+
y : complex-valued N-D NumPy array
|
| 311 |
+
The (N-D) DFT of the input array.
|
| 312 |
+
|
| 313 |
+
See Also
|
| 314 |
+
--------
|
| 315 |
+
ifftn
|
| 316 |
+
|
| 317 |
+
Notes
|
| 318 |
+
-----
|
| 319 |
+
If ``x`` is real-valued, then
|
| 320 |
+
``y[..., j_i, ...] == y[..., n_i-j_i, ...].conjugate()``.
|
| 321 |
+
|
| 322 |
+
Both single and double precision routines are implemented. Half precision
|
| 323 |
+
inputs will be converted to single precision. Non-floating-point inputs
|
| 324 |
+
will be converted to double precision. Long-double precision inputs are
|
| 325 |
+
not supported.
|
| 326 |
+
|
| 327 |
+
Examples
|
| 328 |
+
--------
|
| 329 |
+
>>> import numpy as np
|
| 330 |
+
>>> from scipy.fftpack import fftn, ifftn
|
| 331 |
+
>>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
|
| 332 |
+
>>> np.allclose(y, fftn(ifftn(y)))
|
| 333 |
+
True
|
| 334 |
+
|
| 335 |
+
"""
|
| 336 |
+
shape = _good_shape(x, shape, axes)
|
| 337 |
+
return _pocketfft.fftn(x, shape, axes, None, overwrite_x)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def ifftn(x, shape=None, axes=None, overwrite_x=False):
|
| 341 |
+
"""
|
| 342 |
+
Return inverse multidimensional discrete Fourier transform.
|
| 343 |
+
|
| 344 |
+
The sequence can be of an arbitrary type.
|
| 345 |
+
|
| 346 |
+
The returned array contains::
|
| 347 |
+
|
| 348 |
+
y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
|
| 349 |
+
x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i)
|
| 350 |
+
|
| 351 |
+
where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``.
|
| 352 |
+
|
| 353 |
+
For description of parameters see `fftn`.
|
| 354 |
+
|
| 355 |
+
See Also
|
| 356 |
+
--------
|
| 357 |
+
fftn : for detailed information.
|
| 358 |
+
|
| 359 |
+
Examples
|
| 360 |
+
--------
|
| 361 |
+
>>> from scipy.fftpack import fftn, ifftn
|
| 362 |
+
>>> import numpy as np
|
| 363 |
+
>>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
|
| 364 |
+
>>> np.allclose(y, ifftn(fftn(y)))
|
| 365 |
+
True
|
| 366 |
+
|
| 367 |
+
"""
|
| 368 |
+
shape = _good_shape(x, shape, axes)
|
| 369 |
+
return _pocketfft.ifftn(x, shape, axes, None, overwrite_x)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
|
| 373 |
+
"""
|
| 374 |
+
2-D discrete Fourier transform.
|
| 375 |
+
|
| 376 |
+
Return the 2-D discrete Fourier transform of the 2-D argument
|
| 377 |
+
`x`.
|
| 378 |
+
|
| 379 |
+
See Also
|
| 380 |
+
--------
|
| 381 |
+
fftn : for detailed information.
|
| 382 |
+
|
| 383 |
+
Examples
|
| 384 |
+
--------
|
| 385 |
+
>>> import numpy as np
|
| 386 |
+
>>> from scipy.fftpack import fft2, ifft2
|
| 387 |
+
>>> y = np.mgrid[:5, :5][0]
|
| 388 |
+
>>> y
|
| 389 |
+
array([[0, 0, 0, 0, 0],
|
| 390 |
+
[1, 1, 1, 1, 1],
|
| 391 |
+
[2, 2, 2, 2, 2],
|
| 392 |
+
[3, 3, 3, 3, 3],
|
| 393 |
+
[4, 4, 4, 4, 4]])
|
| 394 |
+
>>> np.allclose(y, ifft2(fft2(y)))
|
| 395 |
+
True
|
| 396 |
+
"""
|
| 397 |
+
return fftn(x,shape,axes,overwrite_x)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
|
| 401 |
+
"""
|
| 402 |
+
2-D discrete inverse Fourier transform of real or complex sequence.
|
| 403 |
+
|
| 404 |
+
Return inverse 2-D discrete Fourier transform of
|
| 405 |
+
arbitrary type sequence x.
|
| 406 |
+
|
| 407 |
+
See `ifft` for more information.
|
| 408 |
+
|
| 409 |
+
See Also
|
| 410 |
+
--------
|
| 411 |
+
fft2, ifft
|
| 412 |
+
|
| 413 |
+
Examples
|
| 414 |
+
--------
|
| 415 |
+
>>> import numpy as np
|
| 416 |
+
>>> from scipy.fftpack import fft2, ifft2
|
| 417 |
+
>>> y = np.mgrid[:5, :5][0]
|
| 418 |
+
>>> y
|
| 419 |
+
array([[0, 0, 0, 0, 0],
|
| 420 |
+
[1, 1, 1, 1, 1],
|
| 421 |
+
[2, 2, 2, 2, 2],
|
| 422 |
+
[3, 3, 3, 3, 3],
|
| 423 |
+
[4, 4, 4, 4, 4]])
|
| 424 |
+
>>> np.allclose(y, fft2(ifft2(y)))
|
| 425 |
+
True
|
| 426 |
+
|
| 427 |
+
"""
|
| 428 |
+
return ifftn(x,shape,axes,overwrite_x)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_helper.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numpy.fft import fftshift, ifftshift, fftfreq
|
| 5 |
+
|
| 6 |
+
import scipy.fft._pocketfft.helper as _helper
|
| 7 |
+
|
| 8 |
+
__all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len']
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def rfftfreq(n, d=1.0):
|
| 12 |
+
"""DFT sample frequencies (for usage with rfft, irfft).
|
| 13 |
+
|
| 14 |
+
The returned float array contains the frequency bins in
|
| 15 |
+
cycles/unit (with zero at the start) given a window length `n` and a
|
| 16 |
+
sample spacing `d`::
|
| 17 |
+
|
| 18 |
+
f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2]/(d*n) if n is even
|
| 19 |
+
f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2,n/2]/(d*n) if n is odd
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
n : int
|
| 24 |
+
Window length.
|
| 25 |
+
d : scalar, optional
|
| 26 |
+
Sample spacing. Default is 1.
|
| 27 |
+
|
| 28 |
+
Returns
|
| 29 |
+
-------
|
| 30 |
+
out : ndarray
|
| 31 |
+
The array of length `n`, containing the sample frequencies.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
--------
|
| 35 |
+
>>> import numpy as np
|
| 36 |
+
>>> from scipy import fftpack
|
| 37 |
+
>>> sig = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
|
| 38 |
+
>>> sig_fft = fftpack.rfft(sig)
|
| 39 |
+
>>> n = sig_fft.size
|
| 40 |
+
>>> timestep = 0.1
|
| 41 |
+
>>> freq = fftpack.rfftfreq(n, d=timestep)
|
| 42 |
+
>>> freq
|
| 43 |
+
array([ 0. , 1.25, 1.25, 2.5 , 2.5 , 3.75, 3.75, 5. ])
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
n = operator.index(n)
|
| 47 |
+
if n < 0:
|
| 48 |
+
raise ValueError(f"n = {n} is not valid. "
|
| 49 |
+
"n must be a nonnegative integer.")
|
| 50 |
+
|
| 51 |
+
return (np.arange(1, n + 1, dtype=int) // 2) / float(n * d)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def next_fast_len(target):
|
| 55 |
+
"""
|
| 56 |
+
Find the next fast size of input data to `fft`, for zero-padding, etc.
|
| 57 |
+
|
| 58 |
+
SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
|
| 59 |
+
returns the next composite of the prime factors 2, 3, and 5 which is
|
| 60 |
+
greater than or equal to `target`. (These are also known as 5-smooth
|
| 61 |
+
numbers, regular numbers, or Hamming numbers.)
|
| 62 |
+
|
| 63 |
+
Parameters
|
| 64 |
+
----------
|
| 65 |
+
target : int
|
| 66 |
+
Length to start searching from. Must be a positive integer.
|
| 67 |
+
|
| 68 |
+
Returns
|
| 69 |
+
-------
|
| 70 |
+
out : int
|
| 71 |
+
The first 5-smooth number greater than or equal to `target`.
|
| 72 |
+
|
| 73 |
+
Notes
|
| 74 |
+
-----
|
| 75 |
+
.. versionadded:: 0.18.0
|
| 76 |
+
|
| 77 |
+
Examples
|
| 78 |
+
--------
|
| 79 |
+
On a particular machine, an FFT of prime length takes 133 ms:
|
| 80 |
+
|
| 81 |
+
>>> from scipy import fftpack
|
| 82 |
+
>>> import numpy as np
|
| 83 |
+
>>> rng = np.random.default_rng()
|
| 84 |
+
>>> min_len = 10007 # prime length is worst case for speed
|
| 85 |
+
>>> a = rng.standard_normal(min_len)
|
| 86 |
+
>>> b = fftpack.fft(a)
|
| 87 |
+
|
| 88 |
+
Zero-padding to the next 5-smooth length reduces computation time to
|
| 89 |
+
211 us, a speedup of 630 times:
|
| 90 |
+
|
| 91 |
+
>>> fftpack.next_fast_len(min_len)
|
| 92 |
+
10125
|
| 93 |
+
>>> b = fftpack.fft(a, 10125)
|
| 94 |
+
|
| 95 |
+
Rounding up to the next power of 2 is not optimal, taking 367 us to
|
| 96 |
+
compute, 1.7 times as long as the 5-smooth size:
|
| 97 |
+
|
| 98 |
+
>>> b = fftpack.fft(a, 16384)
|
| 99 |
+
|
| 100 |
+
"""
|
| 101 |
+
# Real transforms use regular sizes so this is backwards compatible
|
| 102 |
+
return _helper.good_size(target, True)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _good_shape(x, shape, axes):
|
| 106 |
+
"""Ensure that shape argument is valid for scipy.fftpack
|
| 107 |
+
|
| 108 |
+
scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
|
| 109 |
+
"""
|
| 110 |
+
if shape is not None and axes is None:
|
| 111 |
+
shape = _helper._iterable_of_int(shape, 'shape')
|
| 112 |
+
if len(shape) != np.ndim(x):
|
| 113 |
+
raise ValueError("when given, axes and shape arguments"
|
| 114 |
+
" have to be of the same length")
|
| 115 |
+
return shape
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_pseudo_diffs.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Differential and pseudo-differential operators.
|
| 3 |
+
"""
|
| 4 |
+
# Created by Pearu Peterson, September 2002
|
| 5 |
+
|
| 6 |
+
__all__ = ['diff',
|
| 7 |
+
'tilbert','itilbert','hilbert','ihilbert',
|
| 8 |
+
'cs_diff','cc_diff','sc_diff','ss_diff',
|
| 9 |
+
'shift']
|
| 10 |
+
|
| 11 |
+
import threading
|
| 12 |
+
|
| 13 |
+
from numpy import pi, asarray, sin, cos, sinh, cosh, tanh, iscomplexobj
|
| 14 |
+
from . import convolve
|
| 15 |
+
|
| 16 |
+
from scipy.fft._pocketfft.helper import _datacopied
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_cache = threading.local()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def diff(x,order=1,period=None, _cache=_cache):
|
| 23 |
+
"""
|
| 24 |
+
Return kth derivative (or integral) of a periodic sequence x.
|
| 25 |
+
|
| 26 |
+
If x_j and y_j are Fourier coefficients of periodic functions x
|
| 27 |
+
and y, respectively, then::
|
| 28 |
+
|
| 29 |
+
y_j = pow(sqrt(-1)*j*2*pi/period, order) * x_j
|
| 30 |
+
y_0 = 0 if order is not 0.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
x : array_like
|
| 35 |
+
Input array.
|
| 36 |
+
order : int, optional
|
| 37 |
+
The order of differentiation. Default order is 1. If order is
|
| 38 |
+
negative, then integration is carried out under the assumption
|
| 39 |
+
that ``x_0 == 0``.
|
| 40 |
+
period : float, optional
|
| 41 |
+
The assumed period of the sequence. Default is ``2*pi``.
|
| 42 |
+
|
| 43 |
+
Notes
|
| 44 |
+
-----
|
| 45 |
+
If ``sum(x, axis=0) = 0`` then ``diff(diff(x, k), -k) == x`` (within
|
| 46 |
+
numerical accuracy).
|
| 47 |
+
|
| 48 |
+
For odd order and even ``len(x)``, the Nyquist mode is taken zero.
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
if isinstance(_cache, threading.local):
|
| 52 |
+
if not hasattr(_cache, 'diff_cache'):
|
| 53 |
+
_cache.diff_cache = {}
|
| 54 |
+
_cache = _cache.diff_cache
|
| 55 |
+
|
| 56 |
+
tmp = asarray(x)
|
| 57 |
+
if order == 0:
|
| 58 |
+
return tmp
|
| 59 |
+
if iscomplexobj(tmp):
|
| 60 |
+
return diff(tmp.real, order, period, _cache)+1j*diff(
|
| 61 |
+
tmp.imag, order, period, _cache)
|
| 62 |
+
if period is not None:
|
| 63 |
+
c = 2*pi/period
|
| 64 |
+
else:
|
| 65 |
+
c = 1.0
|
| 66 |
+
n = len(x)
|
| 67 |
+
omega = _cache.get((n,order,c))
|
| 68 |
+
if omega is None:
|
| 69 |
+
if len(_cache) > 20:
|
| 70 |
+
while _cache:
|
| 71 |
+
_cache.popitem()
|
| 72 |
+
|
| 73 |
+
def kernel(k,order=order,c=c):
|
| 74 |
+
if k:
|
| 75 |
+
return pow(c*k,order)
|
| 76 |
+
return 0
|
| 77 |
+
omega = convolve.init_convolution_kernel(n,kernel,d=order,
|
| 78 |
+
zero_nyquist=1)
|
| 79 |
+
_cache[(n,order,c)] = omega
|
| 80 |
+
overwrite_x = _datacopied(tmp, x)
|
| 81 |
+
return convolve.convolve(tmp,omega,swap_real_imag=order % 2,
|
| 82 |
+
overwrite_x=overwrite_x)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def tilbert(x, h, period=None, _cache=_cache):
|
| 86 |
+
"""
|
| 87 |
+
Return h-Tilbert transform of a periodic sequence x.
|
| 88 |
+
|
| 89 |
+
If x_j and y_j are Fourier coefficients of periodic functions x
|
| 90 |
+
and y, respectively, then::
|
| 91 |
+
|
| 92 |
+
y_j = sqrt(-1)*coth(j*h*2*pi/period) * x_j
|
| 93 |
+
y_0 = 0
|
| 94 |
+
|
| 95 |
+
Parameters
|
| 96 |
+
----------
|
| 97 |
+
x : array_like
|
| 98 |
+
The input array to transform.
|
| 99 |
+
h : float
|
| 100 |
+
Defines the parameter of the Tilbert transform.
|
| 101 |
+
period : float, optional
|
| 102 |
+
The assumed period of the sequence. Default period is ``2*pi``.
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
tilbert : ndarray
|
| 107 |
+
The result of the transform.
|
| 108 |
+
|
| 109 |
+
Notes
|
| 110 |
+
-----
|
| 111 |
+
If ``sum(x, axis=0) == 0`` and ``n = len(x)`` is odd, then
|
| 112 |
+
``tilbert(itilbert(x)) == x``.
|
| 113 |
+
|
| 114 |
+
If ``2 * pi * h / period`` is approximately 10 or larger, then
|
| 115 |
+
numerically ``tilbert == hilbert``
|
| 116 |
+
(theoretically oo-Tilbert == Hilbert).
|
| 117 |
+
|
| 118 |
+
For even ``len(x)``, the Nyquist mode of ``x`` is taken zero.
|
| 119 |
+
|
| 120 |
+
"""
|
| 121 |
+
if isinstance(_cache, threading.local):
|
| 122 |
+
if not hasattr(_cache, 'tilbert_cache'):
|
| 123 |
+
_cache.tilbert_cache = {}
|
| 124 |
+
_cache = _cache.tilbert_cache
|
| 125 |
+
|
| 126 |
+
tmp = asarray(x)
|
| 127 |
+
if iscomplexobj(tmp):
|
| 128 |
+
return tilbert(tmp.real, h, period, _cache) + \
|
| 129 |
+
1j * tilbert(tmp.imag, h, period, _cache)
|
| 130 |
+
|
| 131 |
+
if period is not None:
|
| 132 |
+
h = h * 2 * pi / period
|
| 133 |
+
|
| 134 |
+
n = len(x)
|
| 135 |
+
omega = _cache.get((n, h))
|
| 136 |
+
if omega is None:
|
| 137 |
+
if len(_cache) > 20:
|
| 138 |
+
while _cache:
|
| 139 |
+
_cache.popitem()
|
| 140 |
+
|
| 141 |
+
def kernel(k, h=h):
|
| 142 |
+
if k:
|
| 143 |
+
return 1.0/tanh(h*k)
|
| 144 |
+
|
| 145 |
+
return 0
|
| 146 |
+
|
| 147 |
+
omega = convolve.init_convolution_kernel(n, kernel, d=1)
|
| 148 |
+
_cache[(n,h)] = omega
|
| 149 |
+
|
| 150 |
+
overwrite_x = _datacopied(tmp, x)
|
| 151 |
+
return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def itilbert(x,h,period=None, _cache=_cache):
|
| 155 |
+
"""
|
| 156 |
+
Return inverse h-Tilbert transform of a periodic sequence x.
|
| 157 |
+
|
| 158 |
+
If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
|
| 159 |
+
and y, respectively, then::
|
| 160 |
+
|
| 161 |
+
y_j = -sqrt(-1)*tanh(j*h*2*pi/period) * x_j
|
| 162 |
+
y_0 = 0
|
| 163 |
+
|
| 164 |
+
For more details, see `tilbert`.
|
| 165 |
+
|
| 166 |
+
"""
|
| 167 |
+
if isinstance(_cache, threading.local):
|
| 168 |
+
if not hasattr(_cache, 'itilbert_cache'):
|
| 169 |
+
_cache.itilbert_cache = {}
|
| 170 |
+
_cache = _cache.itilbert_cache
|
| 171 |
+
|
| 172 |
+
tmp = asarray(x)
|
| 173 |
+
if iscomplexobj(tmp):
|
| 174 |
+
return itilbert(tmp.real, h, period, _cache) + \
|
| 175 |
+
1j*itilbert(tmp.imag, h, period, _cache)
|
| 176 |
+
if period is not None:
|
| 177 |
+
h = h*2*pi/period
|
| 178 |
+
n = len(x)
|
| 179 |
+
omega = _cache.get((n,h))
|
| 180 |
+
if omega is None:
|
| 181 |
+
if len(_cache) > 20:
|
| 182 |
+
while _cache:
|
| 183 |
+
_cache.popitem()
|
| 184 |
+
|
| 185 |
+
def kernel(k,h=h):
|
| 186 |
+
if k:
|
| 187 |
+
return -tanh(h*k)
|
| 188 |
+
return 0
|
| 189 |
+
omega = convolve.init_convolution_kernel(n,kernel,d=1)
|
| 190 |
+
_cache[(n,h)] = omega
|
| 191 |
+
overwrite_x = _datacopied(tmp, x)
|
| 192 |
+
return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def hilbert(x, _cache=_cache):
|
| 196 |
+
"""
|
| 197 |
+
Return Hilbert transform of a periodic sequence x.
|
| 198 |
+
|
| 199 |
+
If x_j and y_j are Fourier coefficients of periodic functions x
|
| 200 |
+
and y, respectively, then::
|
| 201 |
+
|
| 202 |
+
y_j = sqrt(-1)*sign(j) * x_j
|
| 203 |
+
y_0 = 0
|
| 204 |
+
|
| 205 |
+
Parameters
|
| 206 |
+
----------
|
| 207 |
+
x : array_like
|
| 208 |
+
The input array, should be periodic.
|
| 209 |
+
_cache : dict, optional
|
| 210 |
+
Dictionary that contains the kernel used to do a convolution with.
|
| 211 |
+
|
| 212 |
+
Returns
|
| 213 |
+
-------
|
| 214 |
+
y : ndarray
|
| 215 |
+
The transformed input.
|
| 216 |
+
|
| 217 |
+
See Also
|
| 218 |
+
--------
|
| 219 |
+
scipy.signal.hilbert : Compute the analytic signal, using the Hilbert
|
| 220 |
+
transform.
|
| 221 |
+
|
| 222 |
+
Notes
|
| 223 |
+
-----
|
| 224 |
+
If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``.
|
| 225 |
+
|
| 226 |
+
For even len(x), the Nyquist mode of x is taken zero.
|
| 227 |
+
|
| 228 |
+
The sign of the returned transform does not have a factor -1 that is more
|
| 229 |
+
often than not found in the definition of the Hilbert transform. Note also
|
| 230 |
+
that `scipy.signal.hilbert` does have an extra -1 factor compared to this
|
| 231 |
+
function.
|
| 232 |
+
|
| 233 |
+
"""
|
| 234 |
+
if isinstance(_cache, threading.local):
|
| 235 |
+
if not hasattr(_cache, 'hilbert_cache'):
|
| 236 |
+
_cache.hilbert_cache = {}
|
| 237 |
+
_cache = _cache.hilbert_cache
|
| 238 |
+
|
| 239 |
+
tmp = asarray(x)
|
| 240 |
+
if iscomplexobj(tmp):
|
| 241 |
+
return hilbert(tmp.real, _cache) + 1j * hilbert(tmp.imag, _cache)
|
| 242 |
+
n = len(x)
|
| 243 |
+
omega = _cache.get(n)
|
| 244 |
+
if omega is None:
|
| 245 |
+
if len(_cache) > 20:
|
| 246 |
+
while _cache:
|
| 247 |
+
_cache.popitem()
|
| 248 |
+
|
| 249 |
+
def kernel(k):
|
| 250 |
+
if k > 0:
|
| 251 |
+
return 1.0
|
| 252 |
+
elif k < 0:
|
| 253 |
+
return -1.0
|
| 254 |
+
return 0.0
|
| 255 |
+
omega = convolve.init_convolution_kernel(n,kernel,d=1)
|
| 256 |
+
_cache[n] = omega
|
| 257 |
+
overwrite_x = _datacopied(tmp, x)
|
| 258 |
+
return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def ihilbert(x, _cache=_cache):
|
| 262 |
+
"""
|
| 263 |
+
Return inverse Hilbert transform of a periodic sequence x.
|
| 264 |
+
|
| 265 |
+
If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
|
| 266 |
+
and y, respectively, then::
|
| 267 |
+
|
| 268 |
+
y_j = -sqrt(-1)*sign(j) * x_j
|
| 269 |
+
y_0 = 0
|
| 270 |
+
|
| 271 |
+
"""
|
| 272 |
+
if isinstance(_cache, threading.local):
|
| 273 |
+
if not hasattr(_cache, 'ihilbert_cache'):
|
| 274 |
+
_cache.ihilbert_cache = {}
|
| 275 |
+
_cache = _cache.ihilbert_cache
|
| 276 |
+
return -hilbert(x, _cache)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def cs_diff(x, a, b, period=None, _cache=_cache):
|
| 280 |
+
"""
|
| 281 |
+
Return (a,b)-cosh/sinh pseudo-derivative of a periodic sequence.
|
| 282 |
+
|
| 283 |
+
If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
|
| 284 |
+
and y, respectively, then::
|
| 285 |
+
|
| 286 |
+
y_j = -sqrt(-1)*cosh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
|
| 287 |
+
y_0 = 0
|
| 288 |
+
|
| 289 |
+
Parameters
|
| 290 |
+
----------
|
| 291 |
+
x : array_like
|
| 292 |
+
The array to take the pseudo-derivative from.
|
| 293 |
+
a, b : float
|
| 294 |
+
Defines the parameters of the cosh/sinh pseudo-differential
|
| 295 |
+
operator.
|
| 296 |
+
period : float, optional
|
| 297 |
+
The period of the sequence. Default period is ``2*pi``.
|
| 298 |
+
|
| 299 |
+
Returns
|
| 300 |
+
-------
|
| 301 |
+
cs_diff : ndarray
|
| 302 |
+
Pseudo-derivative of periodic sequence `x`.
|
| 303 |
+
|
| 304 |
+
Notes
|
| 305 |
+
-----
|
| 306 |
+
For even len(`x`), the Nyquist mode of `x` is taken as zero.
|
| 307 |
+
|
| 308 |
+
"""
|
| 309 |
+
if isinstance(_cache, threading.local):
|
| 310 |
+
if not hasattr(_cache, 'cs_diff_cache'):
|
| 311 |
+
_cache.cs_diff_cache = {}
|
| 312 |
+
_cache = _cache.cs_diff_cache
|
| 313 |
+
|
| 314 |
+
tmp = asarray(x)
|
| 315 |
+
if iscomplexobj(tmp):
|
| 316 |
+
return cs_diff(tmp.real, a, b, period, _cache) + \
|
| 317 |
+
1j*cs_diff(tmp.imag, a, b, period, _cache)
|
| 318 |
+
if period is not None:
|
| 319 |
+
a = a*2*pi/period
|
| 320 |
+
b = b*2*pi/period
|
| 321 |
+
n = len(x)
|
| 322 |
+
omega = _cache.get((n,a,b))
|
| 323 |
+
if omega is None:
|
| 324 |
+
if len(_cache) > 20:
|
| 325 |
+
while _cache:
|
| 326 |
+
_cache.popitem()
|
| 327 |
+
|
| 328 |
+
def kernel(k,a=a,b=b):
|
| 329 |
+
if k:
|
| 330 |
+
return -cosh(a*k)/sinh(b*k)
|
| 331 |
+
return 0
|
| 332 |
+
omega = convolve.init_convolution_kernel(n,kernel,d=1)
|
| 333 |
+
_cache[(n,a,b)] = omega
|
| 334 |
+
overwrite_x = _datacopied(tmp, x)
|
| 335 |
+
return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def sc_diff(x, a, b, period=None, _cache=_cache):
|
| 339 |
+
"""
|
| 340 |
+
Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x.
|
| 341 |
+
|
| 342 |
+
If x_j and y_j are Fourier coefficients of periodic functions x
|
| 343 |
+
and y, respectively, then::
|
| 344 |
+
|
| 345 |
+
y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
|
| 346 |
+
y_0 = 0
|
| 347 |
+
|
| 348 |
+
Parameters
|
| 349 |
+
----------
|
| 350 |
+
x : array_like
|
| 351 |
+
Input array.
|
| 352 |
+
a,b : float
|
| 353 |
+
Defines the parameters of the sinh/cosh pseudo-differential
|
| 354 |
+
operator.
|
| 355 |
+
period : float, optional
|
| 356 |
+
The period of the sequence x. Default is 2*pi.
|
| 357 |
+
|
| 358 |
+
Notes
|
| 359 |
+
-----
|
| 360 |
+
``sc_diff(cs_diff(x,a,b),b,a) == x``
|
| 361 |
+
For even ``len(x)``, the Nyquist mode of x is taken as zero.
|
| 362 |
+
|
| 363 |
+
"""
|
| 364 |
+
if isinstance(_cache, threading.local):
|
| 365 |
+
if not hasattr(_cache, 'sc_diff_cache'):
|
| 366 |
+
_cache.sc_diff_cache = {}
|
| 367 |
+
_cache = _cache.sc_diff_cache
|
| 368 |
+
|
| 369 |
+
tmp = asarray(x)
|
| 370 |
+
if iscomplexobj(tmp):
|
| 371 |
+
return sc_diff(tmp.real, a, b, period, _cache) + \
|
| 372 |
+
1j * sc_diff(tmp.imag, a, b, period, _cache)
|
| 373 |
+
if period is not None:
|
| 374 |
+
a = a*2*pi/period
|
| 375 |
+
b = b*2*pi/period
|
| 376 |
+
n = len(x)
|
| 377 |
+
omega = _cache.get((n,a,b))
|
| 378 |
+
if omega is None:
|
| 379 |
+
if len(_cache) > 20:
|
| 380 |
+
while _cache:
|
| 381 |
+
_cache.popitem()
|
| 382 |
+
|
| 383 |
+
def kernel(k,a=a,b=b):
|
| 384 |
+
if k:
|
| 385 |
+
return sinh(a*k)/cosh(b*k)
|
| 386 |
+
return 0
|
| 387 |
+
omega = convolve.init_convolution_kernel(n,kernel,d=1)
|
| 388 |
+
_cache[(n,a,b)] = omega
|
| 389 |
+
overwrite_x = _datacopied(tmp, x)
|
| 390 |
+
return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def ss_diff(x, a, b, period=None, _cache=_cache):
|
| 394 |
+
"""
|
| 395 |
+
Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x.
|
| 396 |
+
|
| 397 |
+
If x_j and y_j are Fourier coefficients of periodic functions x
|
| 398 |
+
and y, respectively, then::
|
| 399 |
+
|
| 400 |
+
y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
|
| 401 |
+
y_0 = a/b * x_0
|
| 402 |
+
|
| 403 |
+
Parameters
|
| 404 |
+
----------
|
| 405 |
+
x : array_like
|
| 406 |
+
The array to take the pseudo-derivative from.
|
| 407 |
+
a,b
|
| 408 |
+
Defines the parameters of the sinh/sinh pseudo-differential
|
| 409 |
+
operator.
|
| 410 |
+
period : float, optional
|
| 411 |
+
The period of the sequence x. Default is ``2*pi``.
|
| 412 |
+
|
| 413 |
+
Notes
|
| 414 |
+
-----
|
| 415 |
+
``ss_diff(ss_diff(x,a,b),b,a) == x``
|
| 416 |
+
|
| 417 |
+
"""
|
| 418 |
+
if isinstance(_cache, threading.local):
|
| 419 |
+
if not hasattr(_cache, 'ss_diff_cache'):
|
| 420 |
+
_cache.ss_diff_cache = {}
|
| 421 |
+
_cache = _cache.ss_diff_cache
|
| 422 |
+
|
| 423 |
+
tmp = asarray(x)
|
| 424 |
+
if iscomplexobj(tmp):
|
| 425 |
+
return ss_diff(tmp.real, a, b, period, _cache) + \
|
| 426 |
+
1j*ss_diff(tmp.imag, a, b, period, _cache)
|
| 427 |
+
if period is not None:
|
| 428 |
+
a = a*2*pi/period
|
| 429 |
+
b = b*2*pi/period
|
| 430 |
+
n = len(x)
|
| 431 |
+
omega = _cache.get((n,a,b))
|
| 432 |
+
if omega is None:
|
| 433 |
+
if len(_cache) > 20:
|
| 434 |
+
while _cache:
|
| 435 |
+
_cache.popitem()
|
| 436 |
+
|
| 437 |
+
def kernel(k,a=a,b=b):
|
| 438 |
+
if k:
|
| 439 |
+
return sinh(a*k)/sinh(b*k)
|
| 440 |
+
return float(a)/b
|
| 441 |
+
omega = convolve.init_convolution_kernel(n,kernel)
|
| 442 |
+
_cache[(n,a,b)] = omega
|
| 443 |
+
overwrite_x = _datacopied(tmp, x)
|
| 444 |
+
return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def cc_diff(x, a, b, period=None, _cache=_cache):
|
| 448 |
+
"""
|
| 449 |
+
Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence.
|
| 450 |
+
|
| 451 |
+
If x_j and y_j are Fourier coefficients of periodic functions x
|
| 452 |
+
and y, respectively, then::
|
| 453 |
+
|
| 454 |
+
y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
|
| 455 |
+
|
| 456 |
+
Parameters
|
| 457 |
+
----------
|
| 458 |
+
x : array_like
|
| 459 |
+
The array to take the pseudo-derivative from.
|
| 460 |
+
a,b : float
|
| 461 |
+
Defines the parameters of the sinh/sinh pseudo-differential
|
| 462 |
+
operator.
|
| 463 |
+
period : float, optional
|
| 464 |
+
The period of the sequence x. Default is ``2*pi``.
|
| 465 |
+
|
| 466 |
+
Returns
|
| 467 |
+
-------
|
| 468 |
+
cc_diff : ndarray
|
| 469 |
+
Pseudo-derivative of periodic sequence `x`.
|
| 470 |
+
|
| 471 |
+
Notes
|
| 472 |
+
-----
|
| 473 |
+
``cc_diff(cc_diff(x,a,b),b,a) == x``
|
| 474 |
+
|
| 475 |
+
"""
|
| 476 |
+
if isinstance(_cache, threading.local):
|
| 477 |
+
if not hasattr(_cache, 'cc_diff_cache'):
|
| 478 |
+
_cache.cc_diff_cache = {}
|
| 479 |
+
_cache = _cache.cc_diff_cache
|
| 480 |
+
|
| 481 |
+
tmp = asarray(x)
|
| 482 |
+
if iscomplexobj(tmp):
|
| 483 |
+
return cc_diff(tmp.real, a, b, period, _cache) + \
|
| 484 |
+
1j * cc_diff(tmp.imag, a, b, period, _cache)
|
| 485 |
+
if period is not None:
|
| 486 |
+
a = a*2*pi/period
|
| 487 |
+
b = b*2*pi/period
|
| 488 |
+
n = len(x)
|
| 489 |
+
omega = _cache.get((n,a,b))
|
| 490 |
+
if omega is None:
|
| 491 |
+
if len(_cache) > 20:
|
| 492 |
+
while _cache:
|
| 493 |
+
_cache.popitem()
|
| 494 |
+
|
| 495 |
+
def kernel(k,a=a,b=b):
|
| 496 |
+
return cosh(a*k)/cosh(b*k)
|
| 497 |
+
omega = convolve.init_convolution_kernel(n,kernel)
|
| 498 |
+
_cache[(n,a,b)] = omega
|
| 499 |
+
overwrite_x = _datacopied(tmp, x)
|
| 500 |
+
return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def shift(x, a, period=None, _cache=_cache):
|
| 504 |
+
"""
|
| 505 |
+
Shift periodic sequence x by a: y(u) = x(u+a).
|
| 506 |
+
|
| 507 |
+
If x_j and y_j are Fourier coefficients of periodic functions x
|
| 508 |
+
and y, respectively, then::
|
| 509 |
+
|
| 510 |
+
y_j = exp(j*a*2*pi/period*sqrt(-1)) * x_f
|
| 511 |
+
|
| 512 |
+
Parameters
|
| 513 |
+
----------
|
| 514 |
+
x : array_like
|
| 515 |
+
The array to take the pseudo-derivative from.
|
| 516 |
+
a : float
|
| 517 |
+
Defines the parameters of the sinh/sinh pseudo-differential
|
| 518 |
+
period : float, optional
|
| 519 |
+
The period of the sequences x and y. Default period is ``2*pi``.
|
| 520 |
+
"""
|
| 521 |
+
if isinstance(_cache, threading.local):
|
| 522 |
+
if not hasattr(_cache, 'shift_cache'):
|
| 523 |
+
_cache.shift_cache = {}
|
| 524 |
+
_cache = _cache.shift_cache
|
| 525 |
+
|
| 526 |
+
tmp = asarray(x)
|
| 527 |
+
if iscomplexobj(tmp):
|
| 528 |
+
return shift(tmp.real, a, period, _cache) + 1j * shift(
|
| 529 |
+
tmp.imag, a, period, _cache)
|
| 530 |
+
if period is not None:
|
| 531 |
+
a = a*2*pi/period
|
| 532 |
+
n = len(x)
|
| 533 |
+
omega = _cache.get((n,a))
|
| 534 |
+
if omega is None:
|
| 535 |
+
if len(_cache) > 20:
|
| 536 |
+
while _cache:
|
| 537 |
+
_cache.popitem()
|
| 538 |
+
|
| 539 |
+
def kernel_real(k,a=a):
|
| 540 |
+
return cos(a*k)
|
| 541 |
+
|
| 542 |
+
def kernel_imag(k,a=a):
|
| 543 |
+
return sin(a*k)
|
| 544 |
+
omega_real = convolve.init_convolution_kernel(n,kernel_real,d=0,
|
| 545 |
+
zero_nyquist=0)
|
| 546 |
+
omega_imag = convolve.init_convolution_kernel(n,kernel_imag,d=1,
|
| 547 |
+
zero_nyquist=0)
|
| 548 |
+
_cache[(n,a)] = omega_real,omega_imag
|
| 549 |
+
else:
|
| 550 |
+
omega_real,omega_imag = omega
|
| 551 |
+
overwrite_x = _datacopied(tmp, x)
|
| 552 |
+
return convolve.convolve_z(tmp,omega_real,omega_imag,
|
| 553 |
+
overwrite_x=overwrite_x)
|
| 554 |
+
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/_realtransforms.py
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Real spectrum transforms (DCT, DST, MDCT)
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
|
| 6 |
+
|
| 7 |
+
from scipy.fft import _pocketfft
|
| 8 |
+
from ._helper import _good_shape
|
| 9 |
+
|
| 10 |
+
_inverse_typemap = {1: 1, 2: 3, 3: 2, 4: 4}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def dctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
|
| 14 |
+
"""
|
| 15 |
+
Return multidimensional Discrete Cosine Transform along the specified axes.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
x : array_like
|
| 20 |
+
The input array.
|
| 21 |
+
type : {1, 2, 3, 4}, optional
|
| 22 |
+
Type of the DCT (see Notes). Default type is 2.
|
| 23 |
+
shape : int or array_like of ints or None, optional
|
| 24 |
+
The shape of the result. If both `shape` and `axes` (see below) are
|
| 25 |
+
None, `shape` is ``x.shape``; if `shape` is None but `axes` is
|
| 26 |
+
not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
|
| 27 |
+
If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
|
| 28 |
+
If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
|
| 29 |
+
length ``shape[i]``.
|
| 30 |
+
If any element of `shape` is -1, the size of the corresponding
|
| 31 |
+
dimension of `x` is used.
|
| 32 |
+
axes : int or array_like of ints or None, optional
|
| 33 |
+
Axes along which the DCT is computed.
|
| 34 |
+
The default is over all axes.
|
| 35 |
+
norm : {None, 'ortho'}, optional
|
| 36 |
+
Normalization mode (see Notes). Default is None.
|
| 37 |
+
overwrite_x : bool, optional
|
| 38 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
-------
|
| 42 |
+
y : ndarray of real
|
| 43 |
+
The transformed input array.
|
| 44 |
+
|
| 45 |
+
See Also
|
| 46 |
+
--------
|
| 47 |
+
idctn : Inverse multidimensional DCT
|
| 48 |
+
|
| 49 |
+
Notes
|
| 50 |
+
-----
|
| 51 |
+
For full details of the DCT types and normalization modes, as well as
|
| 52 |
+
references, see `dct`.
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
--------
|
| 56 |
+
>>> import numpy as np
|
| 57 |
+
>>> from scipy.fftpack import dctn, idctn
|
| 58 |
+
>>> rng = np.random.default_rng()
|
| 59 |
+
>>> y = rng.standard_normal((16, 16))
|
| 60 |
+
>>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
|
| 61 |
+
True
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
shape = _good_shape(x, shape, axes)
|
| 65 |
+
return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def idctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
|
| 69 |
+
"""
|
| 70 |
+
Return multidimensional Discrete Cosine Transform along the specified axes.
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
x : array_like
|
| 75 |
+
The input array.
|
| 76 |
+
type : {1, 2, 3, 4}, optional
|
| 77 |
+
Type of the DCT (see Notes). Default type is 2.
|
| 78 |
+
shape : int or array_like of ints or None, optional
|
| 79 |
+
The shape of the result. If both `shape` and `axes` (see below) are
|
| 80 |
+
None, `shape` is ``x.shape``; if `shape` is None but `axes` is
|
| 81 |
+
not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
|
| 82 |
+
If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
|
| 83 |
+
If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
|
| 84 |
+
length ``shape[i]``.
|
| 85 |
+
If any element of `shape` is -1, the size of the corresponding
|
| 86 |
+
dimension of `x` is used.
|
| 87 |
+
axes : int or array_like of ints or None, optional
|
| 88 |
+
Axes along which the IDCT is computed.
|
| 89 |
+
The default is over all axes.
|
| 90 |
+
norm : {None, 'ortho'}, optional
|
| 91 |
+
Normalization mode (see Notes). Default is None.
|
| 92 |
+
overwrite_x : bool, optional
|
| 93 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 94 |
+
|
| 95 |
+
Returns
|
| 96 |
+
-------
|
| 97 |
+
y : ndarray of real
|
| 98 |
+
The transformed input array.
|
| 99 |
+
|
| 100 |
+
See Also
|
| 101 |
+
--------
|
| 102 |
+
dctn : multidimensional DCT
|
| 103 |
+
|
| 104 |
+
Notes
|
| 105 |
+
-----
|
| 106 |
+
For full details of the IDCT types and normalization modes, as well as
|
| 107 |
+
references, see `idct`.
|
| 108 |
+
|
| 109 |
+
Examples
|
| 110 |
+
--------
|
| 111 |
+
>>> import numpy as np
|
| 112 |
+
>>> from scipy.fftpack import dctn, idctn
|
| 113 |
+
>>> rng = np.random.default_rng()
|
| 114 |
+
>>> y = rng.standard_normal((16, 16))
|
| 115 |
+
>>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
|
| 116 |
+
True
|
| 117 |
+
|
| 118 |
+
"""
|
| 119 |
+
type = _inverse_typemap[type]
|
| 120 |
+
shape = _good_shape(x, shape, axes)
|
| 121 |
+
return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def dstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
|
| 125 |
+
"""
|
| 126 |
+
Return multidimensional Discrete Sine Transform along the specified axes.
|
| 127 |
+
|
| 128 |
+
Parameters
|
| 129 |
+
----------
|
| 130 |
+
x : array_like
|
| 131 |
+
The input array.
|
| 132 |
+
type : {1, 2, 3, 4}, optional
|
| 133 |
+
Type of the DST (see Notes). Default type is 2.
|
| 134 |
+
shape : int or array_like of ints or None, optional
|
| 135 |
+
The shape of the result. If both `shape` and `axes` (see below) are
|
| 136 |
+
None, `shape` is ``x.shape``; if `shape` is None but `axes` is
|
| 137 |
+
not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
|
| 138 |
+
If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
|
| 139 |
+
If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
|
| 140 |
+
length ``shape[i]``.
|
| 141 |
+
If any element of `shape` is -1, the size of the corresponding
|
| 142 |
+
dimension of `x` is used.
|
| 143 |
+
axes : int or array_like of ints or None, optional
|
| 144 |
+
Axes along which the DCT is computed.
|
| 145 |
+
The default is over all axes.
|
| 146 |
+
norm : {None, 'ortho'}, optional
|
| 147 |
+
Normalization mode (see Notes). Default is None.
|
| 148 |
+
overwrite_x : bool, optional
|
| 149 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 150 |
+
|
| 151 |
+
Returns
|
| 152 |
+
-------
|
| 153 |
+
y : ndarray of real
|
| 154 |
+
The transformed input array.
|
| 155 |
+
|
| 156 |
+
See Also
|
| 157 |
+
--------
|
| 158 |
+
idstn : Inverse multidimensional DST
|
| 159 |
+
|
| 160 |
+
Notes
|
| 161 |
+
-----
|
| 162 |
+
For full details of the DST types and normalization modes, as well as
|
| 163 |
+
references, see `dst`.
|
| 164 |
+
|
| 165 |
+
Examples
|
| 166 |
+
--------
|
| 167 |
+
>>> import numpy as np
|
| 168 |
+
>>> from scipy.fftpack import dstn, idstn
|
| 169 |
+
>>> rng = np.random.default_rng()
|
| 170 |
+
>>> y = rng.standard_normal((16, 16))
|
| 171 |
+
>>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
|
| 172 |
+
True
|
| 173 |
+
|
| 174 |
+
"""
|
| 175 |
+
shape = _good_shape(x, shape, axes)
|
| 176 |
+
return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def idstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
|
| 180 |
+
"""
|
| 181 |
+
Return multidimensional Discrete Sine Transform along the specified axes.
|
| 182 |
+
|
| 183 |
+
Parameters
|
| 184 |
+
----------
|
| 185 |
+
x : array_like
|
| 186 |
+
The input array.
|
| 187 |
+
type : {1, 2, 3, 4}, optional
|
| 188 |
+
Type of the DST (see Notes). Default type is 2.
|
| 189 |
+
shape : int or array_like of ints or None, optional
|
| 190 |
+
The shape of the result. If both `shape` and `axes` (see below) are
|
| 191 |
+
None, `shape` is ``x.shape``; if `shape` is None but `axes` is
|
| 192 |
+
not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
|
| 193 |
+
If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
|
| 194 |
+
If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
|
| 195 |
+
length ``shape[i]``.
|
| 196 |
+
If any element of `shape` is -1, the size of the corresponding
|
| 197 |
+
dimension of `x` is used.
|
| 198 |
+
axes : int or array_like of ints or None, optional
|
| 199 |
+
Axes along which the IDST is computed.
|
| 200 |
+
The default is over all axes.
|
| 201 |
+
norm : {None, 'ortho'}, optional
|
| 202 |
+
Normalization mode (see Notes). Default is None.
|
| 203 |
+
overwrite_x : bool, optional
|
| 204 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 205 |
+
|
| 206 |
+
Returns
|
| 207 |
+
-------
|
| 208 |
+
y : ndarray of real
|
| 209 |
+
The transformed input array.
|
| 210 |
+
|
| 211 |
+
See Also
|
| 212 |
+
--------
|
| 213 |
+
dstn : multidimensional DST
|
| 214 |
+
|
| 215 |
+
Notes
|
| 216 |
+
-----
|
| 217 |
+
For full details of the IDST types and normalization modes, as well as
|
| 218 |
+
references, see `idst`.
|
| 219 |
+
|
| 220 |
+
Examples
|
| 221 |
+
--------
|
| 222 |
+
>>> import numpy as np
|
| 223 |
+
>>> from scipy.fftpack import dstn, idstn
|
| 224 |
+
>>> rng = np.random.default_rng()
|
| 225 |
+
>>> y = rng.standard_normal((16, 16))
|
| 226 |
+
>>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
|
| 227 |
+
True
|
| 228 |
+
|
| 229 |
+
"""
|
| 230 |
+
type = _inverse_typemap[type]
|
| 231 |
+
shape = _good_shape(x, shape, axes)
|
| 232 |
+
return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
|
| 236 |
+
r"""
|
| 237 |
+
Return the Discrete Cosine Transform of arbitrary type sequence x.
|
| 238 |
+
|
| 239 |
+
Parameters
|
| 240 |
+
----------
|
| 241 |
+
x : array_like
|
| 242 |
+
The input array.
|
| 243 |
+
type : {1, 2, 3, 4}, optional
|
| 244 |
+
Type of the DCT (see Notes). Default type is 2.
|
| 245 |
+
n : int, optional
|
| 246 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
| 247 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
| 248 |
+
default results in ``n = x.shape[axis]``.
|
| 249 |
+
axis : int, optional
|
| 250 |
+
Axis along which the dct is computed; the default is over the
|
| 251 |
+
last axis (i.e., ``axis=-1``).
|
| 252 |
+
norm : {None, 'ortho'}, optional
|
| 253 |
+
Normalization mode (see Notes). Default is None.
|
| 254 |
+
overwrite_x : bool, optional
|
| 255 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 256 |
+
|
| 257 |
+
Returns
|
| 258 |
+
-------
|
| 259 |
+
y : ndarray of real
|
| 260 |
+
The transformed input array.
|
| 261 |
+
|
| 262 |
+
See Also
|
| 263 |
+
--------
|
| 264 |
+
idct : Inverse DCT
|
| 265 |
+
|
| 266 |
+
Notes
|
| 267 |
+
-----
|
| 268 |
+
For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
|
| 269 |
+
MATLAB ``dct(x)``.
|
| 270 |
+
|
| 271 |
+
There are, theoretically, 8 types of the DCT, only the first 4 types are
|
| 272 |
+
implemented in scipy. 'The' DCT generally refers to DCT type 2, and 'the'
|
| 273 |
+
Inverse DCT generally refers to DCT type 3.
|
| 274 |
+
|
| 275 |
+
**Type I**
|
| 276 |
+
|
| 277 |
+
There are several definitions of the DCT-I; we use the following
|
| 278 |
+
(for ``norm=None``)
|
| 279 |
+
|
| 280 |
+
.. math::
|
| 281 |
+
|
| 282 |
+
y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
|
| 283 |
+
\frac{\pi k n}{N-1} \right)
|
| 284 |
+
|
| 285 |
+
If ``norm='ortho'``, ``x[0]`` and ``x[N-1]`` are multiplied by a scaling
|
| 286 |
+
factor of :math:`\sqrt{2}`, and ``y[k]`` is multiplied by a scaling factor
|
| 287 |
+
``f``
|
| 288 |
+
|
| 289 |
+
.. math::
|
| 290 |
+
|
| 291 |
+
f = \begin{cases}
|
| 292 |
+
\frac{1}{2}\sqrt{\frac{1}{N-1}} & \text{if }k=0\text{ or }N-1, \\
|
| 293 |
+
\frac{1}{2}\sqrt{\frac{2}{N-1}} & \text{otherwise} \end{cases}
|
| 294 |
+
|
| 295 |
+
.. versionadded:: 1.2.0
|
| 296 |
+
Orthonormalization in DCT-I.
|
| 297 |
+
|
| 298 |
+
.. note::
|
| 299 |
+
The DCT-I is only supported for input size > 1.
|
| 300 |
+
|
| 301 |
+
**Type II**
|
| 302 |
+
|
| 303 |
+
There are several definitions of the DCT-II; we use the following
|
| 304 |
+
(for ``norm=None``)
|
| 305 |
+
|
| 306 |
+
.. math::
|
| 307 |
+
|
| 308 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
|
| 309 |
+
|
| 310 |
+
If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
|
| 311 |
+
|
| 312 |
+
.. math::
|
| 313 |
+
f = \begin{cases}
|
| 314 |
+
\sqrt{\frac{1}{4N}} & \text{if }k=0, \\
|
| 315 |
+
\sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
|
| 316 |
+
|
| 317 |
+
which makes the corresponding matrix of coefficients orthonormal
|
| 318 |
+
(``O @ O.T = np.eye(N)``).
|
| 319 |
+
|
| 320 |
+
**Type III**
|
| 321 |
+
|
| 322 |
+
There are several definitions, we use the following (for ``norm=None``)
|
| 323 |
+
|
| 324 |
+
.. math::
|
| 325 |
+
|
| 326 |
+
y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
|
| 327 |
+
|
| 328 |
+
or, for ``norm='ortho'``
|
| 329 |
+
|
| 330 |
+
.. math::
|
| 331 |
+
|
| 332 |
+
y_k = \frac{x_0}{\sqrt{N}} + \sqrt{\frac{2}{N}} \sum_{n=1}^{N-1} x_n
|
| 333 |
+
\cos\left(\frac{\pi(2k+1)n}{2N}\right)
|
| 334 |
+
|
| 335 |
+
The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
|
| 336 |
+
to a factor ``2N``. The orthonormalized DCT-III is exactly the inverse of
|
| 337 |
+
the orthonormalized DCT-II.
|
| 338 |
+
|
| 339 |
+
**Type IV**
|
| 340 |
+
|
| 341 |
+
There are several definitions of the DCT-IV; we use the following
|
| 342 |
+
(for ``norm=None``)
|
| 343 |
+
|
| 344 |
+
.. math::
|
| 345 |
+
|
| 346 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
|
| 347 |
+
|
| 348 |
+
If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
|
| 349 |
+
|
| 350 |
+
.. math::
|
| 351 |
+
|
| 352 |
+
f = \frac{1}{\sqrt{2N}}
|
| 353 |
+
|
| 354 |
+
.. versionadded:: 1.2.0
|
| 355 |
+
Support for DCT-IV.
|
| 356 |
+
|
| 357 |
+
References
|
| 358 |
+
----------
|
| 359 |
+
.. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
|
| 360 |
+
Makhoul, `IEEE Transactions on acoustics, speech and signal
|
| 361 |
+
processing` vol. 28(1), pp. 27-34,
|
| 362 |
+
:doi:`10.1109/TASSP.1980.1163351` (1980).
|
| 363 |
+
.. [2] Wikipedia, "Discrete cosine transform",
|
| 364 |
+
https://en.wikipedia.org/wiki/Discrete_cosine_transform
|
| 365 |
+
|
| 366 |
+
Examples
|
| 367 |
+
--------
|
| 368 |
+
The Type 1 DCT is equivalent to the FFT (though faster) for real,
|
| 369 |
+
even-symmetrical inputs. The output is also real and even-symmetrical.
|
| 370 |
+
Half of the FFT input is used to generate half of the FFT output:
|
| 371 |
+
|
| 372 |
+
>>> from scipy.fftpack import fft, dct
|
| 373 |
+
>>> import numpy as np
|
| 374 |
+
>>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
|
| 375 |
+
array([ 30., -8., 6., -2., 6., -8.])
|
| 376 |
+
>>> dct(np.array([4., 3., 5., 10.]), 1)
|
| 377 |
+
array([ 30., -8., 6., -2.])
|
| 378 |
+
|
| 379 |
+
"""
|
| 380 |
+
return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
|
| 384 |
+
"""
|
| 385 |
+
Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
|
| 386 |
+
|
| 387 |
+
Parameters
|
| 388 |
+
----------
|
| 389 |
+
x : array_like
|
| 390 |
+
The input array.
|
| 391 |
+
type : {1, 2, 3, 4}, optional
|
| 392 |
+
Type of the DCT (see Notes). Default type is 2.
|
| 393 |
+
n : int, optional
|
| 394 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
| 395 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
| 396 |
+
default results in ``n = x.shape[axis]``.
|
| 397 |
+
axis : int, optional
|
| 398 |
+
Axis along which the idct is computed; the default is over the
|
| 399 |
+
last axis (i.e., ``axis=-1``).
|
| 400 |
+
norm : {None, 'ortho'}, optional
|
| 401 |
+
Normalization mode (see Notes). Default is None.
|
| 402 |
+
overwrite_x : bool, optional
|
| 403 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 404 |
+
|
| 405 |
+
Returns
|
| 406 |
+
-------
|
| 407 |
+
idct : ndarray of real
|
| 408 |
+
The transformed input array.
|
| 409 |
+
|
| 410 |
+
See Also
|
| 411 |
+
--------
|
| 412 |
+
dct : Forward DCT
|
| 413 |
+
|
| 414 |
+
Notes
|
| 415 |
+
-----
|
| 416 |
+
For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
|
| 417 |
+
MATLAB ``idct(x)``.
|
| 418 |
+
|
| 419 |
+
'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
|
| 420 |
+
|
| 421 |
+
IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
|
| 422 |
+
3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
|
| 423 |
+
of type 4. For the definition of these types, see `dct`.
|
| 424 |
+
|
| 425 |
+
Examples
|
| 426 |
+
--------
|
| 427 |
+
The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
|
| 428 |
+
inputs. The output is also real and even-symmetrical. Half of the IFFT
|
| 429 |
+
input is used to generate half of the IFFT output:
|
| 430 |
+
|
| 431 |
+
>>> from scipy.fftpack import ifft, idct
|
| 432 |
+
>>> import numpy as np
|
| 433 |
+
>>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real
|
| 434 |
+
array([ 4., 3., 5., 10., 5., 3.])
|
| 435 |
+
>>> idct(np.array([ 30., -8., 6., -2.]), 1) / 6
|
| 436 |
+
array([ 4., 3., 5., 10.])
|
| 437 |
+
|
| 438 |
+
"""
|
| 439 |
+
type = _inverse_typemap[type]
|
| 440 |
+
return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
|
| 444 |
+
r"""
|
| 445 |
+
Return the Discrete Sine Transform of arbitrary type sequence x.
|
| 446 |
+
|
| 447 |
+
Parameters
|
| 448 |
+
----------
|
| 449 |
+
x : array_like
|
| 450 |
+
The input array.
|
| 451 |
+
type : {1, 2, 3, 4}, optional
|
| 452 |
+
Type of the DST (see Notes). Default type is 2.
|
| 453 |
+
n : int, optional
|
| 454 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
| 455 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
| 456 |
+
default results in ``n = x.shape[axis]``.
|
| 457 |
+
axis : int, optional
|
| 458 |
+
Axis along which the dst is computed; the default is over the
|
| 459 |
+
last axis (i.e., ``axis=-1``).
|
| 460 |
+
norm : {None, 'ortho'}, optional
|
| 461 |
+
Normalization mode (see Notes). Default is None.
|
| 462 |
+
overwrite_x : bool, optional
|
| 463 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 464 |
+
|
| 465 |
+
Returns
|
| 466 |
+
-------
|
| 467 |
+
dst : ndarray of reals
|
| 468 |
+
The transformed input array.
|
| 469 |
+
|
| 470 |
+
See Also
|
| 471 |
+
--------
|
| 472 |
+
idst : Inverse DST
|
| 473 |
+
|
| 474 |
+
Notes
|
| 475 |
+
-----
|
| 476 |
+
For a single dimension array ``x``.
|
| 477 |
+
|
| 478 |
+
There are, theoretically, 8 types of the DST for different combinations of
|
| 479 |
+
even/odd boundary conditions and boundary off sets [1]_, only the first
|
| 480 |
+
4 types are implemented in scipy.
|
| 481 |
+
|
| 482 |
+
**Type I**
|
| 483 |
+
|
| 484 |
+
There are several definitions of the DST-I; we use the following
|
| 485 |
+
for ``norm=None``. DST-I assumes the input is odd around `n=-1` and `n=N`.
|
| 486 |
+
|
| 487 |
+
.. math::
|
| 488 |
+
|
| 489 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
|
| 490 |
+
|
| 491 |
+
Note that the DST-I is only supported for input size > 1.
|
| 492 |
+
The (unnormalized) DST-I is its own inverse, up to a factor ``2(N+1)``.
|
| 493 |
+
The orthonormalized DST-I is exactly its own inverse.
|
| 494 |
+
|
| 495 |
+
**Type II**
|
| 496 |
+
|
| 497 |
+
There are several definitions of the DST-II; we use the following for
|
| 498 |
+
``norm=None``. DST-II assumes the input is odd around `n=-1/2` and
|
| 499 |
+
`n=N-1/2`; the output is odd around :math:`k=-1` and even around `k=N-1`
|
| 500 |
+
|
| 501 |
+
.. math::
|
| 502 |
+
|
| 503 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
|
| 504 |
+
|
| 505 |
+
if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
|
| 506 |
+
|
| 507 |
+
.. math::
|
| 508 |
+
|
| 509 |
+
f = \begin{cases}
|
| 510 |
+
\sqrt{\frac{1}{4N}} & \text{if }k = 0, \\
|
| 511 |
+
\sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
|
| 512 |
+
|
| 513 |
+
**Type III**
|
| 514 |
+
|
| 515 |
+
There are several definitions of the DST-III, we use the following (for
|
| 516 |
+
``norm=None``). DST-III assumes the input is odd around `n=-1` and even
|
| 517 |
+
around `n=N-1`
|
| 518 |
+
|
| 519 |
+
.. math::
|
| 520 |
+
|
| 521 |
+
y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
|
| 522 |
+
\frac{\pi(2k+1)(n+1)}{2N}\right)
|
| 523 |
+
|
| 524 |
+
The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
|
| 525 |
+
to a factor ``2N``. The orthonormalized DST-III is exactly the inverse of the
|
| 526 |
+
orthonormalized DST-II.
|
| 527 |
+
|
| 528 |
+
.. versionadded:: 0.11.0
|
| 529 |
+
|
| 530 |
+
**Type IV**
|
| 531 |
+
|
| 532 |
+
There are several definitions of the DST-IV, we use the following (for
|
| 533 |
+
``norm=None``). DST-IV assumes the input is odd around `n=-0.5` and even
|
| 534 |
+
around `n=N-0.5`
|
| 535 |
+
|
| 536 |
+
.. math::
|
| 537 |
+
|
| 538 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
|
| 539 |
+
|
| 540 |
+
The (unnormalized) DST-IV is its own inverse, up to a factor ``2N``. The
|
| 541 |
+
orthonormalized DST-IV is exactly its own inverse.
|
| 542 |
+
|
| 543 |
+
.. versionadded:: 1.2.0
|
| 544 |
+
Support for DST-IV.
|
| 545 |
+
|
| 546 |
+
References
|
| 547 |
+
----------
|
| 548 |
+
.. [1] Wikipedia, "Discrete sine transform",
|
| 549 |
+
https://en.wikipedia.org/wiki/Discrete_sine_transform
|
| 550 |
+
|
| 551 |
+
"""
|
| 552 |
+
return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
|
| 556 |
+
"""
|
| 557 |
+
Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
|
| 558 |
+
|
| 559 |
+
Parameters
|
| 560 |
+
----------
|
| 561 |
+
x : array_like
|
| 562 |
+
The input array.
|
| 563 |
+
type : {1, 2, 3, 4}, optional
|
| 564 |
+
Type of the DST (see Notes). Default type is 2.
|
| 565 |
+
n : int, optional
|
| 566 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
| 567 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
| 568 |
+
default results in ``n = x.shape[axis]``.
|
| 569 |
+
axis : int, optional
|
| 570 |
+
Axis along which the idst is computed; the default is over the
|
| 571 |
+
last axis (i.e., ``axis=-1``).
|
| 572 |
+
norm : {None, 'ortho'}, optional
|
| 573 |
+
Normalization mode (see Notes). Default is None.
|
| 574 |
+
overwrite_x : bool, optional
|
| 575 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
| 576 |
+
|
| 577 |
+
Returns
|
| 578 |
+
-------
|
| 579 |
+
idst : ndarray of real
|
| 580 |
+
The transformed input array.
|
| 581 |
+
|
| 582 |
+
See Also
|
| 583 |
+
--------
|
| 584 |
+
dst : Forward DST
|
| 585 |
+
|
| 586 |
+
Notes
|
| 587 |
+
-----
|
| 588 |
+
'The' IDST is the IDST of type 2, which is the same as DST of type 3.
|
| 589 |
+
|
| 590 |
+
IDST of type 1 is the DST of type 1, IDST of type 2 is the DST of type
|
| 591 |
+
3, and IDST of type 3 is the DST of type 2. For the definition of these
|
| 592 |
+
types, see `dst`.
|
| 593 |
+
|
| 594 |
+
.. versionadded:: 0.11.0
|
| 595 |
+
|
| 596 |
+
"""
|
| 597 |
+
type = _inverse_typemap[type]
|
| 598 |
+
return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/basic.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.fftpack` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = [ # noqa: F822
|
| 8 |
+
'fft','ifft','fftn','ifftn','rfft','irfft',
|
| 9 |
+
'fft2','ifft2'
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def __dir__():
|
| 14 |
+
return __all__
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def __getattr__(name):
|
| 18 |
+
return _sub_module_deprecation(sub_package="fftpack", module="basic",
|
| 19 |
+
private_modules=["_basic"], all=__all__,
|
| 20 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/helper.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.fftpack` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = [ # noqa: F822
|
| 8 |
+
'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len'
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def __dir__():
|
| 13 |
+
return __all__
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def __getattr__(name):
|
| 17 |
+
return _sub_module_deprecation(sub_package="fftpack", module="helper",
|
| 18 |
+
private_modules=["_helper"], all=__all__,
|
| 19 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/pseudo_diffs.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.fftpack` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = [ # noqa: F822
|
| 8 |
+
'diff',
|
| 9 |
+
'tilbert', 'itilbert', 'hilbert', 'ihilbert',
|
| 10 |
+
'cs_diff', 'cc_diff', 'sc_diff', 'ss_diff',
|
| 11 |
+
'shift', 'convolve'
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def __dir__():
|
| 16 |
+
return __all__
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def __getattr__(name):
|
| 20 |
+
return _sub_module_deprecation(sub_package="fftpack", module="pseudo_diffs",
|
| 21 |
+
private_modules=["_pseudo_diffs"], all=__all__,
|
| 22 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/fftpack/realtransforms.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.fftpack` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = [ # noqa: F822
|
| 8 |
+
'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def __dir__():
|
| 13 |
+
return __all__
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def __getattr__(name):
|
| 17 |
+
return _sub_module_deprecation(sub_package="fftpack", module="realtransforms",
|
| 18 |
+
private_modules=["_realtransforms"], all=__all__,
|
| 19 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_bsplines.py
ADDED
|
@@ -0,0 +1,2614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
from math import prod
|
| 3 |
+
from types import GenericAlias
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from scipy._lib._util import normalize_axis_index
|
| 7 |
+
from scipy.linalg import (get_lapack_funcs, LinAlgError,
|
| 8 |
+
cholesky_banded, cho_solve_banded,
|
| 9 |
+
solve, solve_banded)
|
| 10 |
+
from scipy.optimize import minimize_scalar
|
| 11 |
+
from . import _dierckx
|
| 12 |
+
from . import _fitpack_impl
|
| 13 |
+
from scipy.sparse import csr_array
|
| 14 |
+
from scipy.special import poch
|
| 15 |
+
from itertools import combinations
|
| 16 |
+
|
| 17 |
+
from scipy._lib._array_api import array_namespace, concat_1d, xp_capabilities
|
| 18 |
+
|
| 19 |
+
__all__ = ["BSpline", "make_interp_spline", "make_lsq_spline",
|
| 20 |
+
"make_smoothing_spline"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _get_dtype(dtype):
|
| 24 |
+
"""Return np.complex128 for complex dtypes, np.float64 otherwise."""
|
| 25 |
+
if np.issubdtype(dtype, np.complexfloating):
|
| 26 |
+
return np.complex128
|
| 27 |
+
else:
|
| 28 |
+
return np.float64
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _as_float_array(x, check_finite=False):
|
| 32 |
+
"""Convert the input into a C contiguous float array.
|
| 33 |
+
|
| 34 |
+
NB: Upcasts half- and single-precision floats to double precision.
|
| 35 |
+
"""
|
| 36 |
+
x = np.ascontiguousarray(x)
|
| 37 |
+
dtyp = _get_dtype(x.dtype)
|
| 38 |
+
x = x.astype(dtyp, copy=False)
|
| 39 |
+
if check_finite and not np.isfinite(x).all():
|
| 40 |
+
raise ValueError("Array must not contain infs or nans.")
|
| 41 |
+
return x
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _dual_poly(j, k, t, y):
|
| 45 |
+
"""
|
| 46 |
+
Dual polynomial of the B-spline B_{j,k,t} -
|
| 47 |
+
polynomial which is associated with B_{j,k,t}:
|
| 48 |
+
$p_{j,k}(y) = (y - t_{j+1})(y - t_{j+2})...(y - t_{j+k})$
|
| 49 |
+
"""
|
| 50 |
+
if k == 0:
|
| 51 |
+
return 1
|
| 52 |
+
return np.prod([(y - t[j + i]) for i in range(1, k + 1)])
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _diff_dual_poly(j, k, y, d, t):
|
| 56 |
+
"""
|
| 57 |
+
d-th derivative of the dual polynomial $p_{j,k}(y)$
|
| 58 |
+
"""
|
| 59 |
+
if d == 0:
|
| 60 |
+
return _dual_poly(j, k, t, y)
|
| 61 |
+
if d == k:
|
| 62 |
+
return poch(1, k)
|
| 63 |
+
comb = list(combinations(range(j + 1, j + k + 1), d))
|
| 64 |
+
res = 0
|
| 65 |
+
for i in range(len(comb) * len(comb[0])):
|
| 66 |
+
res += np.prod([(y - t[j + p]) for p in range(1, k + 1)
|
| 67 |
+
if (j + p) not in comb[i//d]])
|
| 68 |
+
return res
|
| 69 |
+
|
| 70 |
+
@xp_capabilities(
|
| 71 |
+
cpu_only=True, jax_jit=False,
|
| 72 |
+
skip_backends=[
|
| 73 |
+
("dask.array",
|
| 74 |
+
"https://github.com/data-apis/array-api-extra/issues/488")
|
| 75 |
+
]
|
| 76 |
+
)
|
| 77 |
+
class BSpline:
|
| 78 |
+
r"""Univariate spline in the B-spline basis.
|
| 79 |
+
|
| 80 |
+
.. math::
|
| 81 |
+
|
| 82 |
+
S(x) = \sum_{j=0}^{n-1} c_j B_{j, k; t}(x)
|
| 83 |
+
|
| 84 |
+
where :math:`B_{j, k; t}` are B-spline basis functions of degree `k`
|
| 85 |
+
and knots `t`.
|
| 86 |
+
|
| 87 |
+
Parameters
|
| 88 |
+
----------
|
| 89 |
+
t : ndarray, shape (n+k+1,)
|
| 90 |
+
knots
|
| 91 |
+
c : ndarray, shape (>=n, ...)
|
| 92 |
+
spline coefficients
|
| 93 |
+
k : int
|
| 94 |
+
B-spline degree
|
| 95 |
+
extrapolate : bool or 'periodic', optional
|
| 96 |
+
whether to extrapolate beyond the base interval, ``t[k] .. t[n]``,
|
| 97 |
+
or to return nans.
|
| 98 |
+
If True, extrapolates the first and last polynomial pieces of b-spline
|
| 99 |
+
functions active on the base interval.
|
| 100 |
+
If 'periodic', periodic extrapolation is used.
|
| 101 |
+
Default is True.
|
| 102 |
+
axis : int, optional
|
| 103 |
+
Interpolation axis. Default is zero.
|
| 104 |
+
|
| 105 |
+
Attributes
|
| 106 |
+
----------
|
| 107 |
+
t : ndarray
|
| 108 |
+
knot vector
|
| 109 |
+
c : ndarray
|
| 110 |
+
spline coefficients
|
| 111 |
+
k : int
|
| 112 |
+
spline degree
|
| 113 |
+
extrapolate : bool
|
| 114 |
+
If True, extrapolates the first and last polynomial pieces of b-spline
|
| 115 |
+
functions active on the base interval.
|
| 116 |
+
axis : int
|
| 117 |
+
Interpolation axis.
|
| 118 |
+
tck : tuple
|
| 119 |
+
A read-only equivalent of ``(self.t, self.c, self.k)``
|
| 120 |
+
|
| 121 |
+
Methods
|
| 122 |
+
-------
|
| 123 |
+
__call__
|
| 124 |
+
basis_element
|
| 125 |
+
derivative
|
| 126 |
+
antiderivative
|
| 127 |
+
integrate
|
| 128 |
+
insert_knot
|
| 129 |
+
construct_fast
|
| 130 |
+
design_matrix
|
| 131 |
+
from_power_basis
|
| 132 |
+
|
| 133 |
+
Notes
|
| 134 |
+
-----
|
| 135 |
+
B-spline basis elements are defined via
|
| 136 |
+
|
| 137 |
+
.. math::
|
| 138 |
+
|
| 139 |
+
B_{i, 0}(x) = 1, \textrm{if $t_i \le x < t_{i+1}$, otherwise $0$,}
|
| 140 |
+
|
| 141 |
+
B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x)
|
| 142 |
+
+ \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x)
|
| 143 |
+
|
| 144 |
+
**Implementation details**
|
| 145 |
+
|
| 146 |
+
- At least ``k+1`` coefficients are required for a spline of degree `k`,
|
| 147 |
+
so that ``n >= k+1``. Additional coefficients, ``c[j]`` with
|
| 148 |
+
``j > n``, are ignored.
|
| 149 |
+
|
| 150 |
+
- B-spline basis elements of degree `k` form a partition of unity on the
|
| 151 |
+
*base interval*, ``t[k] <= x <= t[n]``.
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
Examples
|
| 155 |
+
--------
|
| 156 |
+
Translating the recursive definition of B-splines into Python code, we have:
|
| 157 |
+
|
| 158 |
+
>>> def B(x, k, i, t):
|
| 159 |
+
... if k == 0:
|
| 160 |
+
... return 1.0 if t[i] <= x < t[i+1] else 0.0
|
| 161 |
+
... if t[i+k] == t[i]:
|
| 162 |
+
... c1 = 0.0
|
| 163 |
+
... else:
|
| 164 |
+
... c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t)
|
| 165 |
+
... if t[i+k+1] == t[i+1]:
|
| 166 |
+
... c2 = 0.0
|
| 167 |
+
... else:
|
| 168 |
+
... c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
|
| 169 |
+
... return c1 + c2
|
| 170 |
+
|
| 171 |
+
>>> def bspline(x, t, c, k):
|
| 172 |
+
... n = len(t) - k - 1
|
| 173 |
+
... assert (n >= k+1) and (len(c) >= n)
|
| 174 |
+
... return sum(c[i] * B(x, k, i, t) for i in range(n))
|
| 175 |
+
|
| 176 |
+
Note that this is an inefficient (if straightforward) way to
|
| 177 |
+
evaluate B-splines --- this spline class does it in an equivalent,
|
| 178 |
+
but much more efficient way.
|
| 179 |
+
|
| 180 |
+
Here we construct a quadratic spline function on the base interval
|
| 181 |
+
``2 <= x <= 4`` and compare with the naive way of evaluating the spline:
|
| 182 |
+
|
| 183 |
+
>>> from scipy.interpolate import BSpline
|
| 184 |
+
>>> k = 2
|
| 185 |
+
>>> t = [0, 1, 2, 3, 4, 5, 6]
|
| 186 |
+
>>> c = [-1, 2, 0, -1]
|
| 187 |
+
>>> spl = BSpline(t, c, k)
|
| 188 |
+
>>> spl(2.5)
|
| 189 |
+
array(1.375)
|
| 190 |
+
>>> bspline(2.5, t, c, k)
|
| 191 |
+
1.375
|
| 192 |
+
|
| 193 |
+
Note that outside of the base interval results differ. This is because
|
| 194 |
+
`BSpline` extrapolates the first and last polynomial pieces of B-spline
|
| 195 |
+
functions active on the base interval.
|
| 196 |
+
|
| 197 |
+
>>> import matplotlib.pyplot as plt
|
| 198 |
+
>>> import numpy as np
|
| 199 |
+
>>> fig, ax = plt.subplots()
|
| 200 |
+
>>> xx = np.linspace(1.5, 4.5, 50)
|
| 201 |
+
>>> ax.plot(xx, [bspline(x, t, c ,k) for x in xx], 'r-', lw=3, label='naive')
|
| 202 |
+
>>> ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
|
| 203 |
+
>>> ax.grid(True)
|
| 204 |
+
>>> ax.legend(loc='best')
|
| 205 |
+
>>> plt.show()
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
References
|
| 209 |
+
----------
|
| 210 |
+
.. [1] Tom Lyche and Knut Morken, Spline methods,
|
| 211 |
+
http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
|
| 212 |
+
.. [2] Carl de Boor, A practical guide to splines, Springer, 2001.
|
| 213 |
+
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
# generic type compatibility with scipy-stubs
|
| 217 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def __init__(self, t, c, k, extrapolate=True, axis=0):
|
| 221 |
+
super().__init__()
|
| 222 |
+
|
| 223 |
+
self._asarray = array_namespace(c, t).asarray
|
| 224 |
+
|
| 225 |
+
self.k = operator.index(k)
|
| 226 |
+
self._c = np.asarray(c)
|
| 227 |
+
self._t = np.ascontiguousarray(t, dtype=np.float64)
|
| 228 |
+
|
| 229 |
+
if extrapolate == 'periodic':
|
| 230 |
+
self.extrapolate = extrapolate
|
| 231 |
+
else:
|
| 232 |
+
self.extrapolate = bool(extrapolate)
|
| 233 |
+
|
| 234 |
+
n = self._t.shape[0] - self.k - 1
|
| 235 |
+
|
| 236 |
+
axis = normalize_axis_index(axis, self._c.ndim)
|
| 237 |
+
|
| 238 |
+
# Note that the normalized axis is stored in the object.
|
| 239 |
+
self.axis = axis
|
| 240 |
+
if axis != 0:
|
| 241 |
+
# roll the interpolation axis to be the first one in self.c
|
| 242 |
+
# More specifically, the target shape for self.c is (n, ...),
|
| 243 |
+
# and axis !=0 means that we have c.shape (..., n, ...)
|
| 244 |
+
# ^
|
| 245 |
+
# axis
|
| 246 |
+
self._c = np.moveaxis(self._c, axis, 0)
|
| 247 |
+
|
| 248 |
+
if k < 0:
|
| 249 |
+
raise ValueError("Spline order cannot be negative.")
|
| 250 |
+
if self._t.ndim != 1:
|
| 251 |
+
raise ValueError("Knot vector must be one-dimensional.")
|
| 252 |
+
if n < self.k + 1:
|
| 253 |
+
raise ValueError(f"Need at least {2*k + 2} knots for degree {k}")
|
| 254 |
+
if (np.diff(self._t) < 0).any():
|
| 255 |
+
raise ValueError("Knots must be in a non-decreasing order.")
|
| 256 |
+
if len(np.unique(self._t[k:n+1])) < 2:
|
| 257 |
+
raise ValueError("Need at least two internal knots.")
|
| 258 |
+
if not np.isfinite(self._t).all():
|
| 259 |
+
raise ValueError("Knots should not have nans or infs.")
|
| 260 |
+
if self._c.ndim < 1:
|
| 261 |
+
raise ValueError("Coefficients must be at least 1-dimensional.")
|
| 262 |
+
if self._c.shape[0] < n:
|
| 263 |
+
raise ValueError("Knots, coefficients and degree are inconsistent.")
|
| 264 |
+
|
| 265 |
+
dt = _get_dtype(self._c.dtype)
|
| 266 |
+
|
| 267 |
+
self._c = np.ascontiguousarray(self._c, dtype=dt)
|
| 268 |
+
|
| 269 |
+
@classmethod
|
| 270 |
+
def construct_fast(cls, t, c, k, extrapolate=True, axis=0):
|
| 271 |
+
"""Construct a spline without making checks.
|
| 272 |
+
|
| 273 |
+
Accepts same parameters as the regular constructor. Input arrays
|
| 274 |
+
`t` and `c` must of correct shape and dtype.
|
| 275 |
+
"""
|
| 276 |
+
self = object.__new__(cls)
|
| 277 |
+
self._t, self._c, self.k = np.asarray(t), np.asarray(c), k
|
| 278 |
+
self.extrapolate = extrapolate
|
| 279 |
+
self.axis = axis
|
| 280 |
+
self._asarray = array_namespace(t, c).asarray
|
| 281 |
+
return self
|
| 282 |
+
|
| 283 |
+
@property
|
| 284 |
+
def tck(self):
|
| 285 |
+
"""Equivalent to ``(self.t, self.c, self.k)`` (read-only).
|
| 286 |
+
"""
|
| 287 |
+
return self.t, self.c, self.k
|
| 288 |
+
|
| 289 |
+
# Under the hood, self._c and self._t are always saved as numpy array
|
| 290 |
+
# because they are used in a C extension expecting numpy arrays.
|
| 291 |
+
@property
|
| 292 |
+
def t(self):
|
| 293 |
+
return self._asarray(self._t)
|
| 294 |
+
|
| 295 |
+
@t.setter
|
| 296 |
+
def t(self, t):
|
| 297 |
+
self._t = np.asarray(t)
|
| 298 |
+
|
| 299 |
+
@property
|
| 300 |
+
def c(self):
|
| 301 |
+
return self._asarray(self._c)
|
| 302 |
+
|
| 303 |
+
@c.setter
|
| 304 |
+
def c(self, c):
|
| 305 |
+
self._c = np.asarray(c)
|
| 306 |
+
|
| 307 |
+
@classmethod
|
| 308 |
+
def basis_element(cls, t, extrapolate=True):
|
| 309 |
+
"""Return a B-spline basis element ``B(x | t[0], ..., t[k+1])``.
|
| 310 |
+
|
| 311 |
+
Parameters
|
| 312 |
+
----------
|
| 313 |
+
t : ndarray, shape (k+2,)
|
| 314 |
+
internal knots
|
| 315 |
+
extrapolate : bool or 'periodic', optional
|
| 316 |
+
whether to extrapolate beyond the base interval, ``t[0] .. t[k+1]``,
|
| 317 |
+
or to return nans.
|
| 318 |
+
If 'periodic', periodic extrapolation is used.
|
| 319 |
+
Default is True.
|
| 320 |
+
|
| 321 |
+
Returns
|
| 322 |
+
-------
|
| 323 |
+
basis_element : callable
|
| 324 |
+
A callable representing a B-spline basis element for the knot
|
| 325 |
+
vector `t`.
|
| 326 |
+
|
| 327 |
+
Notes
|
| 328 |
+
-----
|
| 329 |
+
The degree of the B-spline, `k`, is inferred from the length of `t` as
|
| 330 |
+
``len(t)-2``. The knot vector is constructed by appending and prepending
|
| 331 |
+
``k+1`` elements to internal knots `t`.
|
| 332 |
+
|
| 333 |
+
Examples
|
| 334 |
+
--------
|
| 335 |
+
Construct a cubic B-spline:
|
| 336 |
+
|
| 337 |
+
>>> import numpy as np
|
| 338 |
+
>>> from scipy.interpolate import BSpline
|
| 339 |
+
>>> b = BSpline.basis_element([0, 1, 2, 3, 4])
|
| 340 |
+
>>> k = b.k
|
| 341 |
+
>>> b.t[k:-k]
|
| 342 |
+
array([ 0., 1., 2., 3., 4.])
|
| 343 |
+
>>> k
|
| 344 |
+
3
|
| 345 |
+
|
| 346 |
+
Construct a quadratic B-spline on ``[0, 1, 1, 2]``, and compare
|
| 347 |
+
to its explicit form:
|
| 348 |
+
|
| 349 |
+
>>> t = [0, 1, 1, 2]
|
| 350 |
+
>>> b = BSpline.basis_element(t)
|
| 351 |
+
>>> def f(x):
|
| 352 |
+
... return np.where(x < 1, x*x, (2. - x)**2)
|
| 353 |
+
|
| 354 |
+
>>> import matplotlib.pyplot as plt
|
| 355 |
+
>>> fig, ax = plt.subplots()
|
| 356 |
+
>>> x = np.linspace(0, 2, 51)
|
| 357 |
+
>>> ax.plot(x, b(x), 'g', lw=3)
|
| 358 |
+
>>> ax.plot(x, f(x), 'r', lw=8, alpha=0.4)
|
| 359 |
+
>>> ax.grid(True)
|
| 360 |
+
>>> plt.show()
|
| 361 |
+
|
| 362 |
+
"""
|
| 363 |
+
xp = array_namespace(t)
|
| 364 |
+
t = np.asarray(t)
|
| 365 |
+
k = t.shape[0] - 2
|
| 366 |
+
t = _as_float_array(t) # TODO: use concat_1d instead of np.r_
|
| 367 |
+
t = np.r_[(t[0]-1,) * k, t, (t[-1]+1,) * k]
|
| 368 |
+
c = np.zeros_like(t)
|
| 369 |
+
c[k] = 1.
|
| 370 |
+
|
| 371 |
+
t, c = xp.asarray(t), xp.asarray(c)
|
| 372 |
+
return cls.construct_fast(t, c, k, extrapolate)
|
| 373 |
+
|
| 374 |
+
@classmethod
|
| 375 |
+
def design_matrix(cls, x, t, k, extrapolate=False):
|
| 376 |
+
"""
|
| 377 |
+
Returns a design matrix as a CSR format sparse array.
|
| 378 |
+
|
| 379 |
+
Parameters
|
| 380 |
+
----------
|
| 381 |
+
x : array_like, shape (n,)
|
| 382 |
+
Points to evaluate the spline at.
|
| 383 |
+
t : array_like, shape (nt,)
|
| 384 |
+
Sorted 1D array of knots.
|
| 385 |
+
k : int
|
| 386 |
+
B-spline degree.
|
| 387 |
+
extrapolate : bool or 'periodic', optional
|
| 388 |
+
Whether to extrapolate based on the first and last intervals
|
| 389 |
+
or raise an error. If 'periodic', periodic extrapolation is used.
|
| 390 |
+
Default is False.
|
| 391 |
+
|
| 392 |
+
.. versionadded:: 1.10.0
|
| 393 |
+
|
| 394 |
+
Returns
|
| 395 |
+
-------
|
| 396 |
+
design_matrix : `csr_array` object
|
| 397 |
+
Sparse matrix in CSR format where each row contains all the basis
|
| 398 |
+
elements of the input row (first row = basis elements of x[0],
|
| 399 |
+
..., last row = basis elements x[-1]).
|
| 400 |
+
|
| 401 |
+
Examples
|
| 402 |
+
--------
|
| 403 |
+
Construct a design matrix for a B-spline
|
| 404 |
+
|
| 405 |
+
>>> from scipy.interpolate import make_interp_spline, BSpline
|
| 406 |
+
>>> import numpy as np
|
| 407 |
+
>>> x = np.linspace(0, np.pi * 2, 4)
|
| 408 |
+
>>> y = np.sin(x)
|
| 409 |
+
>>> k = 3
|
| 410 |
+
>>> bspl = make_interp_spline(x, y, k=k)
|
| 411 |
+
>>> design_matrix = bspl.design_matrix(x, bspl.t, k)
|
| 412 |
+
>>> design_matrix.toarray()
|
| 413 |
+
[[1. , 0. , 0. , 0. ],
|
| 414 |
+
[0.2962963 , 0.44444444, 0.22222222, 0.03703704],
|
| 415 |
+
[0.03703704, 0.22222222, 0.44444444, 0.2962963 ],
|
| 416 |
+
[0. , 0. , 0. , 1. ]]
|
| 417 |
+
|
| 418 |
+
Construct a design matrix for some vector of knots
|
| 419 |
+
|
| 420 |
+
>>> k = 2
|
| 421 |
+
>>> t = [-1, 0, 1, 2, 3, 4, 5, 6]
|
| 422 |
+
>>> x = [1, 2, 3, 4]
|
| 423 |
+
>>> design_matrix = BSpline.design_matrix(x, t, k).toarray()
|
| 424 |
+
>>> design_matrix
|
| 425 |
+
[[0.5, 0.5, 0. , 0. , 0. ],
|
| 426 |
+
[0. , 0.5, 0.5, 0. , 0. ],
|
| 427 |
+
[0. , 0. , 0.5, 0.5, 0. ],
|
| 428 |
+
[0. , 0. , 0. , 0.5, 0.5]]
|
| 429 |
+
|
| 430 |
+
This result is equivalent to the one created in the sparse format
|
| 431 |
+
|
| 432 |
+
>>> c = np.eye(len(t) - k - 1)
|
| 433 |
+
>>> design_matrix_gh = BSpline(t, c, k)(x)
|
| 434 |
+
>>> np.allclose(design_matrix, design_matrix_gh, atol=1e-14)
|
| 435 |
+
True
|
| 436 |
+
|
| 437 |
+
Notes
|
| 438 |
+
-----
|
| 439 |
+
.. versionadded:: 1.8.0
|
| 440 |
+
|
| 441 |
+
In each row of the design matrix all the basis elements are evaluated
|
| 442 |
+
at the certain point (first row - x[0], ..., last row - x[-1]).
|
| 443 |
+
|
| 444 |
+
`nt` is a length of the vector of knots: as far as there are
|
| 445 |
+
`nt - k - 1` basis elements, `nt` should be not less than `2 * k + 2`
|
| 446 |
+
to have at least `k + 1` basis element.
|
| 447 |
+
|
| 448 |
+
Out of bounds `x` raises a ValueError.
|
| 449 |
+
"""
|
| 450 |
+
x = _as_float_array(x, True)
|
| 451 |
+
t = _as_float_array(t, True)
|
| 452 |
+
|
| 453 |
+
if extrapolate != 'periodic':
|
| 454 |
+
extrapolate = bool(extrapolate)
|
| 455 |
+
|
| 456 |
+
if k < 0:
|
| 457 |
+
raise ValueError("Spline order cannot be negative.")
|
| 458 |
+
if t.ndim != 1 or np.any(t[1:] < t[:-1]):
|
| 459 |
+
raise ValueError(f"Expect t to be a 1-D sorted array_like, but "
|
| 460 |
+
f"got t={t}.")
|
| 461 |
+
# There are `nt - k - 1` basis elements in a BSpline built on the
|
| 462 |
+
# vector of knots with length `nt`, so to have at least `k + 1` basis
|
| 463 |
+
# elements we need to have at least `2 * k + 2` elements in the vector
|
| 464 |
+
# of knots.
|
| 465 |
+
if len(t) < 2 * k + 2:
|
| 466 |
+
raise ValueError(f"Length t is not enough for k={k}.")
|
| 467 |
+
|
| 468 |
+
if extrapolate == 'periodic':
|
| 469 |
+
# With periodic extrapolation we map x to the segment
|
| 470 |
+
# [t[k], t[n]].
|
| 471 |
+
n = t.size - k - 1
|
| 472 |
+
x = t[k] + (x - t[k]) % (t[n] - t[k])
|
| 473 |
+
extrapolate = False
|
| 474 |
+
elif not extrapolate and (
|
| 475 |
+
(min(x) < t[k]) or (max(x) > t[t.shape[0] - k - 1])
|
| 476 |
+
):
|
| 477 |
+
# Checks from `find_interval` function
|
| 478 |
+
raise ValueError(f'Out of bounds w/ x = {x}.')
|
| 479 |
+
|
| 480 |
+
# Compute number of non-zeros of final CSR array in order to determine
|
| 481 |
+
# the dtype of indices and indptr of the CSR array.
|
| 482 |
+
n = x.shape[0]
|
| 483 |
+
nnz = n * (k + 1)
|
| 484 |
+
if nnz < np.iinfo(np.int32).max:
|
| 485 |
+
int_dtype = np.int32
|
| 486 |
+
else:
|
| 487 |
+
int_dtype = np.int64
|
| 488 |
+
|
| 489 |
+
# Get the non-zero elements of the design matrix and per-row `offsets`:
|
| 490 |
+
# In row `i`, k+1 nonzero elements are consecutive, and start from `offset[i]`
|
| 491 |
+
data, offsets, _ = _dierckx.data_matrix(x, t, k, np.ones_like(x), extrapolate)
|
| 492 |
+
data = data.ravel()
|
| 493 |
+
|
| 494 |
+
if offsets.dtype != int_dtype:
|
| 495 |
+
offsets = offsets.astype(int_dtype)
|
| 496 |
+
|
| 497 |
+
# Convert from per-row offsets to the CSR indices/indptr format
|
| 498 |
+
indices = np.repeat(offsets, k+1).reshape(-1, k+1)
|
| 499 |
+
indices = indices + np.arange(k+1, dtype=int_dtype)
|
| 500 |
+
indices = indices.ravel()
|
| 501 |
+
|
| 502 |
+
indptr = np.arange(0, (n + 1) * (k + 1), k + 1, dtype=int_dtype)
|
| 503 |
+
|
| 504 |
+
return csr_array(
|
| 505 |
+
(data, indices, indptr),
|
| 506 |
+
shape=(x.shape[0], t.shape[0] - k - 1)
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
def __call__(self, x, nu=0, extrapolate=None):
|
| 510 |
+
"""
|
| 511 |
+
Evaluate a spline function.
|
| 512 |
+
|
| 513 |
+
Parameters
|
| 514 |
+
----------
|
| 515 |
+
x : array_like
|
| 516 |
+
points to evaluate the spline at.
|
| 517 |
+
nu : int, optional
|
| 518 |
+
derivative to evaluate (default is 0).
|
| 519 |
+
extrapolate : bool or 'periodic', optional
|
| 520 |
+
whether to extrapolate based on the first and last intervals
|
| 521 |
+
or return nans. If 'periodic', periodic extrapolation is used.
|
| 522 |
+
Default is `self.extrapolate`.
|
| 523 |
+
|
| 524 |
+
Returns
|
| 525 |
+
-------
|
| 526 |
+
y : array_like
|
| 527 |
+
Shape is determined by replacing the interpolation axis
|
| 528 |
+
in the coefficient array with the shape of `x`.
|
| 529 |
+
|
| 530 |
+
"""
|
| 531 |
+
if extrapolate is None:
|
| 532 |
+
extrapolate = self.extrapolate
|
| 533 |
+
x = np.asarray(x)
|
| 534 |
+
x_shape, x_ndim = x.shape, x.ndim
|
| 535 |
+
x = np.ascontiguousarray(x.ravel(), dtype=np.float64)
|
| 536 |
+
|
| 537 |
+
# With periodic extrapolation we map x to the segment
|
| 538 |
+
# [self.t[k], self.t[n]].
|
| 539 |
+
if extrapolate == 'periodic':
|
| 540 |
+
n = self._t.size - self.k - 1
|
| 541 |
+
x = self._t[self.k] + (x - self._t[self.k]) % (self._t[n] - self._t[self.k])
|
| 542 |
+
extrapolate = False
|
| 543 |
+
|
| 544 |
+
self._ensure_c_contiguous()
|
| 545 |
+
|
| 546 |
+
# if self.c is complex: the C code in _dierckxmodule.cc expects
|
| 547 |
+
# floats, so make a view---this expands the last axis, and
|
| 548 |
+
# the view is C contiguous if the original is.
|
| 549 |
+
# if c.dtype is complex of shape (n,), c.view(float).shape == (2*n,)
|
| 550 |
+
# if c.dtype is complex of shape (n, m), c.view(float).shape == (n, 2*m)
|
| 551 |
+
|
| 552 |
+
is_complex = self._c.dtype.kind == 'c'
|
| 553 |
+
if is_complex:
|
| 554 |
+
cc = self._c.view(float)
|
| 555 |
+
if self._c.ndim == 1:
|
| 556 |
+
cc = cc.reshape(self._c.shape[0], 2)
|
| 557 |
+
else:
|
| 558 |
+
cc = self._c
|
| 559 |
+
|
| 560 |
+
# flatten the trailing dims
|
| 561 |
+
cc = cc.reshape(cc.shape[0], -1)
|
| 562 |
+
|
| 563 |
+
# heavy lifting: actually perform the evaluations
|
| 564 |
+
out = _dierckx.evaluate_spline(self._t, cc, self.k, x, nu, extrapolate)
|
| 565 |
+
|
| 566 |
+
if is_complex:
|
| 567 |
+
out = out.view(complex)
|
| 568 |
+
|
| 569 |
+
out = out.reshape(x_shape + self._c.shape[1:])
|
| 570 |
+
if self.axis != 0:
|
| 571 |
+
# transpose to move the calculated values to the interpolation axis
|
| 572 |
+
l = list(range(out.ndim))
|
| 573 |
+
l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
|
| 574 |
+
out = out.transpose(l)
|
| 575 |
+
return self._asarray(out)
|
| 576 |
+
|
| 577 |
+
def _ensure_c_contiguous(self):
|
| 578 |
+
"""
|
| 579 |
+
c and t may be modified by the user. The Cython code expects
|
| 580 |
+
that they are C contiguous.
|
| 581 |
+
|
| 582 |
+
"""
|
| 583 |
+
if not self._t.flags.c_contiguous:
|
| 584 |
+
self._t = self._t.copy()
|
| 585 |
+
if not self._c.flags.c_contiguous:
|
| 586 |
+
self._c = self._c.copy()
|
| 587 |
+
|
| 588 |
+
def derivative(self, nu=1):
|
| 589 |
+
"""Return a B-spline representing the derivative.
|
| 590 |
+
|
| 591 |
+
Parameters
|
| 592 |
+
----------
|
| 593 |
+
nu : int, optional
|
| 594 |
+
Derivative order.
|
| 595 |
+
Default is 1.
|
| 596 |
+
|
| 597 |
+
Returns
|
| 598 |
+
-------
|
| 599 |
+
b : `BSpline` object
|
| 600 |
+
A new instance representing the derivative.
|
| 601 |
+
|
| 602 |
+
See Also
|
| 603 |
+
--------
|
| 604 |
+
splder, splantider
|
| 605 |
+
|
| 606 |
+
"""
|
| 607 |
+
c = self._asarray(self.c, copy=True)
|
| 608 |
+
t = self.t
|
| 609 |
+
xp = array_namespace(t, c)
|
| 610 |
+
|
| 611 |
+
# pad the c array if needed
|
| 612 |
+
ct = t.shape[0] - c.shape[0]
|
| 613 |
+
if ct > 0:
|
| 614 |
+
c = concat_1d(xp, c, xp.zeros((ct,) + c.shape[1:]))
|
| 615 |
+
tck = _fitpack_impl.splder((t, c, self.k), nu)
|
| 616 |
+
return self.construct_fast(*tck, extrapolate=self.extrapolate,
|
| 617 |
+
axis=self.axis)
|
| 618 |
+
|
| 619 |
+
def antiderivative(self, nu=1):
|
| 620 |
+
"""Return a B-spline representing the antiderivative.
|
| 621 |
+
|
| 622 |
+
Parameters
|
| 623 |
+
----------
|
| 624 |
+
nu : int, optional
|
| 625 |
+
Antiderivative order. Default is 1.
|
| 626 |
+
|
| 627 |
+
Returns
|
| 628 |
+
-------
|
| 629 |
+
b : `BSpline` object
|
| 630 |
+
A new instance representing the antiderivative.
|
| 631 |
+
|
| 632 |
+
Notes
|
| 633 |
+
-----
|
| 634 |
+
If antiderivative is computed and ``self.extrapolate='periodic'``,
|
| 635 |
+
it will be set to False for the returned instance. This is done because
|
| 636 |
+
the antiderivative is no longer periodic and its correct evaluation
|
| 637 |
+
outside of the initially given x interval is difficult.
|
| 638 |
+
|
| 639 |
+
See Also
|
| 640 |
+
--------
|
| 641 |
+
splder, splantider
|
| 642 |
+
|
| 643 |
+
"""
|
| 644 |
+
c = self._asarray(self.c, copy=True)
|
| 645 |
+
t = self.t
|
| 646 |
+
xp = array_namespace(t, c)
|
| 647 |
+
|
| 648 |
+
# pad the c array if needed
|
| 649 |
+
ct = t.shape[0] - c.shape[0]
|
| 650 |
+
if ct > 0:
|
| 651 |
+
c = concat_1d(xp, c, xp.zeros((ct,) + c.shape[1:]))
|
| 652 |
+
tck = _fitpack_impl.splantider((t, c, self.k), nu)
|
| 653 |
+
|
| 654 |
+
if self.extrapolate == 'periodic':
|
| 655 |
+
extrapolate = False
|
| 656 |
+
else:
|
| 657 |
+
extrapolate = self.extrapolate
|
| 658 |
+
|
| 659 |
+
return self.construct_fast(*tck, extrapolate=extrapolate,
|
| 660 |
+
axis=self.axis)
|
| 661 |
+
|
| 662 |
+
def integrate(self, a, b, extrapolate=None):
|
| 663 |
+
"""Compute a definite integral of the spline.
|
| 664 |
+
|
| 665 |
+
Parameters
|
| 666 |
+
----------
|
| 667 |
+
a : float
|
| 668 |
+
Lower limit of integration.
|
| 669 |
+
b : float
|
| 670 |
+
Upper limit of integration.
|
| 671 |
+
extrapolate : bool or 'periodic', optional
|
| 672 |
+
whether to extrapolate beyond the base interval,
|
| 673 |
+
``t[k] .. t[-k-1]``, or take the spline to be zero outside of the
|
| 674 |
+
base interval. If 'periodic', periodic extrapolation is used.
|
| 675 |
+
If None (default), use `self.extrapolate`.
|
| 676 |
+
|
| 677 |
+
Returns
|
| 678 |
+
-------
|
| 679 |
+
I : array_like
|
| 680 |
+
Definite integral of the spline over the interval ``[a, b]``.
|
| 681 |
+
|
| 682 |
+
Examples
|
| 683 |
+
--------
|
| 684 |
+
Construct the linear spline ``x if x < 1 else 2 - x`` on the base
|
| 685 |
+
interval :math:`[0, 2]`, and integrate it
|
| 686 |
+
|
| 687 |
+
>>> from scipy.interpolate import BSpline
|
| 688 |
+
>>> b = BSpline.basis_element([0, 1, 2])
|
| 689 |
+
>>> b.integrate(0, 1)
|
| 690 |
+
array(0.5)
|
| 691 |
+
|
| 692 |
+
If the integration limits are outside of the base interval, the result
|
| 693 |
+
is controlled by the `extrapolate` parameter
|
| 694 |
+
|
| 695 |
+
>>> b.integrate(-1, 1)
|
| 696 |
+
array(0.0)
|
| 697 |
+
>>> b.integrate(-1, 1, extrapolate=False)
|
| 698 |
+
array(0.5)
|
| 699 |
+
|
| 700 |
+
>>> import matplotlib.pyplot as plt
|
| 701 |
+
>>> fig, ax = plt.subplots()
|
| 702 |
+
>>> ax.grid(True)
|
| 703 |
+
>>> ax.axvline(0, c='r', lw=5, alpha=0.5) # base interval
|
| 704 |
+
>>> ax.axvline(2, c='r', lw=5, alpha=0.5)
|
| 705 |
+
>>> xx = [-1, 1, 2]
|
| 706 |
+
>>> ax.plot(xx, b(xx))
|
| 707 |
+
>>> plt.show()
|
| 708 |
+
|
| 709 |
+
"""
|
| 710 |
+
if extrapolate is None:
|
| 711 |
+
extrapolate = self.extrapolate
|
| 712 |
+
|
| 713 |
+
# Prepare self.t and self.c.
|
| 714 |
+
self._ensure_c_contiguous()
|
| 715 |
+
|
| 716 |
+
# Swap integration bounds if needed.
|
| 717 |
+
sign = 1
|
| 718 |
+
if b < a:
|
| 719 |
+
a, b = b, a
|
| 720 |
+
sign = -1
|
| 721 |
+
n = self._t.size - self.k - 1
|
| 722 |
+
|
| 723 |
+
if extrapolate != "periodic" and not extrapolate:
|
| 724 |
+
# Shrink the integration interval, if needed.
|
| 725 |
+
a = max(a, self._t[self.k])
|
| 726 |
+
b = min(b, self._t[n])
|
| 727 |
+
|
| 728 |
+
if self._c.ndim == 1:
|
| 729 |
+
# Fast path: use FITPACK's routine
|
| 730 |
+
# (cf _fitpack_impl.splint).
|
| 731 |
+
integral = _fitpack_impl.splint(a, b, (self._t, self._c, self.k))
|
| 732 |
+
return self._asarray(integral * sign)
|
| 733 |
+
|
| 734 |
+
# Compute the antiderivative.
|
| 735 |
+
c = self._c
|
| 736 |
+
ct = len(self._t) - len(c)
|
| 737 |
+
if ct > 0:
|
| 738 |
+
c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
|
| 739 |
+
ta, ca, ka = _fitpack_impl.splantider((self._t, c, self.k), 1)
|
| 740 |
+
|
| 741 |
+
if extrapolate == 'periodic':
|
| 742 |
+
# Split the integral into the part over period (can be several
|
| 743 |
+
# of them) and the remaining part.
|
| 744 |
+
|
| 745 |
+
ts, te = self._t[self.k], self._t[n]
|
| 746 |
+
period = te - ts
|
| 747 |
+
interval = b - a
|
| 748 |
+
n_periods, left = divmod(interval, period)
|
| 749 |
+
|
| 750 |
+
if n_periods > 0:
|
| 751 |
+
# Evaluate the difference of antiderivatives.
|
| 752 |
+
x = np.asarray([ts, te], dtype=np.float64)
|
| 753 |
+
out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
|
| 754 |
+
ka, x, 0, False)
|
| 755 |
+
integral = out[1] - out[0]
|
| 756 |
+
integral *= n_periods
|
| 757 |
+
else:
|
| 758 |
+
integral = np.zeros((1, prod(self._c.shape[1:])),
|
| 759 |
+
dtype=self._c.dtype)
|
| 760 |
+
|
| 761 |
+
# Map a to [ts, te], b is always a + left.
|
| 762 |
+
a = ts + (a - ts) % period
|
| 763 |
+
b = a + left
|
| 764 |
+
|
| 765 |
+
# If b <= te then we need to integrate over [a, b], otherwise
|
| 766 |
+
# over [a, te] and from xs to what is remained.
|
| 767 |
+
if b <= te:
|
| 768 |
+
x = np.asarray([a, b], dtype=np.float64)
|
| 769 |
+
out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
|
| 770 |
+
ka, x, 0, False)
|
| 771 |
+
integral += out[1] - out[0]
|
| 772 |
+
else:
|
| 773 |
+
x = np.asarray([a, te], dtype=np.float64)
|
| 774 |
+
out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
|
| 775 |
+
ka, x, 0, False)
|
| 776 |
+
integral += out[1] - out[0]
|
| 777 |
+
|
| 778 |
+
x = np.asarray([ts, ts + b - te], dtype=np.float64)
|
| 779 |
+
out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
|
| 780 |
+
ka, x, 0, False)
|
| 781 |
+
integral += out[1] - out[0]
|
| 782 |
+
else:
|
| 783 |
+
# Evaluate the difference of antiderivatives.
|
| 784 |
+
x = np.asarray([a, b], dtype=np.float64)
|
| 785 |
+
out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
|
| 786 |
+
ka, x, 0, extrapolate)
|
| 787 |
+
integral = out[1] - out[0]
|
| 788 |
+
|
| 789 |
+
integral *= sign
|
| 790 |
+
return self._asarray(integral.reshape(ca.shape[1:]))
|
| 791 |
+
|
| 792 |
+
@classmethod
|
| 793 |
+
def from_power_basis(cls, pp, bc_type='not-a-knot'):
|
| 794 |
+
r"""
|
| 795 |
+
Construct a polynomial in the B-spline basis
|
| 796 |
+
from a piecewise polynomial in the power basis.
|
| 797 |
+
|
| 798 |
+
For now, accepts ``CubicSpline`` instances only.
|
| 799 |
+
|
| 800 |
+
Parameters
|
| 801 |
+
----------
|
| 802 |
+
pp : CubicSpline
|
| 803 |
+
A piecewise polynomial in the power basis, as created
|
| 804 |
+
by ``CubicSpline``
|
| 805 |
+
bc_type : string, optional
|
| 806 |
+
Boundary condition type as in ``CubicSpline``: one of the
|
| 807 |
+
``not-a-knot``, ``natural``, ``clamped``, or ``periodic``.
|
| 808 |
+
Necessary for construction an instance of ``BSpline`` class.
|
| 809 |
+
Default is ``not-a-knot``.
|
| 810 |
+
|
| 811 |
+
Returns
|
| 812 |
+
-------
|
| 813 |
+
b : `BSpline` object
|
| 814 |
+
A new instance representing the initial polynomial
|
| 815 |
+
in the B-spline basis.
|
| 816 |
+
|
| 817 |
+
Notes
|
| 818 |
+
-----
|
| 819 |
+
.. versionadded:: 1.8.0
|
| 820 |
+
|
| 821 |
+
Accepts only ``CubicSpline`` instances for now.
|
| 822 |
+
|
| 823 |
+
The algorithm follows from differentiation
|
| 824 |
+
the Marsden's identity [1]: each of coefficients of spline
|
| 825 |
+
interpolation function in the B-spline basis is computed as follows:
|
| 826 |
+
|
| 827 |
+
.. math::
|
| 828 |
+
|
| 829 |
+
c_j = \sum_{m=0}^{k} \frac{(k-m)!}{k!}
|
| 830 |
+
c_{m,i} (-1)^{k-m} D^m p_{j,k}(x_i)
|
| 831 |
+
|
| 832 |
+
:math:`c_{m, i}` - a coefficient of CubicSpline,
|
| 833 |
+
:math:`D^m p_{j, k}(x_i)` - an m-th defivative of a dual polynomial
|
| 834 |
+
in :math:`x_i`.
|
| 835 |
+
|
| 836 |
+
``k`` always equals 3 for now.
|
| 837 |
+
|
| 838 |
+
First ``n - 2`` coefficients are computed in :math:`x_i = x_j`, e.g.
|
| 839 |
+
|
| 840 |
+
.. math::
|
| 841 |
+
|
| 842 |
+
c_1 = \sum_{m=0}^{k} \frac{(k-1)!}{k!} c_{m,1} D^m p_{j,3}(x_1)
|
| 843 |
+
|
| 844 |
+
Last ``nod + 2`` coefficients are computed in ``x[-2]``,
|
| 845 |
+
``nod`` - number of derivatives at the ends.
|
| 846 |
+
|
| 847 |
+
For example, consider :math:`x = [0, 1, 2, 3, 4]`,
|
| 848 |
+
:math:`y = [1, 1, 1, 1, 1]` and bc_type = ``natural``
|
| 849 |
+
|
| 850 |
+
The coefficients of CubicSpline in the power basis:
|
| 851 |
+
|
| 852 |
+
:math:`[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
|
| 853 |
+
[0, 0, 0, 0, 0], [1, 1, 1, 1, 1]]`
|
| 854 |
+
|
| 855 |
+
The knot vector: :math:`t = [0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]`
|
| 856 |
+
|
| 857 |
+
In this case
|
| 858 |
+
|
| 859 |
+
.. math::
|
| 860 |
+
|
| 861 |
+
c_j = \frac{0!}{k!} c_{3, i} k! = c_{3, i} = 1,~j = 0, ..., 6
|
| 862 |
+
|
| 863 |
+
References
|
| 864 |
+
----------
|
| 865 |
+
.. [1] Tom Lyche and Knut Morken, Spline Methods, 2005, Section 3.1.2
|
| 866 |
+
|
| 867 |
+
"""
|
| 868 |
+
from ._cubic import CubicSpline
|
| 869 |
+
if not isinstance(pp, CubicSpline):
|
| 870 |
+
raise NotImplementedError(f"Only CubicSpline objects are accepted "
|
| 871 |
+
f"for now. Got {type(pp)} instead.")
|
| 872 |
+
x = pp.x
|
| 873 |
+
coef = pp.c
|
| 874 |
+
k = pp.c.shape[0] - 1
|
| 875 |
+
n = x.shape[0]
|
| 876 |
+
|
| 877 |
+
if bc_type == 'not-a-knot':
|
| 878 |
+
t = _not_a_knot(x, k)
|
| 879 |
+
elif bc_type == 'natural' or bc_type == 'clamped':
|
| 880 |
+
t = _augknt(x, k)
|
| 881 |
+
elif bc_type == 'periodic':
|
| 882 |
+
t = _periodic_knots(x, k)
|
| 883 |
+
else:
|
| 884 |
+
raise TypeError(f'Unknown boundary condition: {bc_type}')
|
| 885 |
+
|
| 886 |
+
nod = t.shape[0] - (n + k + 1) # number of derivatives at the ends
|
| 887 |
+
c = np.zeros(n + nod, dtype=pp.c.dtype)
|
| 888 |
+
for m in range(k + 1):
|
| 889 |
+
for i in range(n - 2):
|
| 890 |
+
c[i] += poch(k + 1, -m) * coef[m, i]\
|
| 891 |
+
* np.power(-1, k - m)\
|
| 892 |
+
* _diff_dual_poly(i, k, x[i], m, t)
|
| 893 |
+
for j in range(n - 2, n + nod):
|
| 894 |
+
c[j] += poch(k + 1, -m) * coef[m, n - 2]\
|
| 895 |
+
* np.power(-1, k - m)\
|
| 896 |
+
* _diff_dual_poly(j, k, x[n - 2], m, t)
|
| 897 |
+
return cls.construct_fast(t, c, k, pp.extrapolate, pp.axis)
|
| 898 |
+
|
| 899 |
+
def insert_knot(self, x, m=1):
|
| 900 |
+
"""Insert a new knot at `x` of multiplicity `m`.
|
| 901 |
+
|
| 902 |
+
Given the knots and coefficients of a B-spline representation, create a
|
| 903 |
+
new B-spline with a knot inserted `m` times at point `x`.
|
| 904 |
+
|
| 905 |
+
Parameters
|
| 906 |
+
----------
|
| 907 |
+
x : float
|
| 908 |
+
The position of the new knot
|
| 909 |
+
m : int, optional
|
| 910 |
+
The number of times to insert the given knot (its multiplicity).
|
| 911 |
+
Default is 1.
|
| 912 |
+
|
| 913 |
+
Returns
|
| 914 |
+
-------
|
| 915 |
+
spl : `BSpline` object
|
| 916 |
+
A new `BSpline` object with the new knot inserted.
|
| 917 |
+
|
| 918 |
+
Notes
|
| 919 |
+
-----
|
| 920 |
+
Based on algorithms from [1]_ and [2]_.
|
| 921 |
+
|
| 922 |
+
In case of a periodic spline (``self.extrapolate == "periodic"``)
|
| 923 |
+
there must be either at least k interior knots t(j) satisfying
|
| 924 |
+
``t(k+1)<t(j)<=x`` or at least k interior knots t(j) satisfying
|
| 925 |
+
``x<=t(j)<t(n-k)``.
|
| 926 |
+
|
| 927 |
+
This routine is functionally equivalent to `scipy.interpolate.insert`.
|
| 928 |
+
|
| 929 |
+
.. versionadded:: 1.13
|
| 930 |
+
|
| 931 |
+
References
|
| 932 |
+
----------
|
| 933 |
+
.. [1] W. Boehm, "Inserting new knots into b-spline curves.",
|
| 934 |
+
Computer Aided Design, 12, p.199-201, 1980.
|
| 935 |
+
:doi:`10.1016/0010-4485(80)90154-2`.
|
| 936 |
+
.. [2] P. Dierckx, "Curve and surface fitting with splines, Monographs on
|
| 937 |
+
Numerical Analysis", Oxford University Press, 1993.
|
| 938 |
+
|
| 939 |
+
See Also
|
| 940 |
+
--------
|
| 941 |
+
scipy.interpolate.insert
|
| 942 |
+
|
| 943 |
+
Examples
|
| 944 |
+
--------
|
| 945 |
+
You can insert knots into a B-spline:
|
| 946 |
+
|
| 947 |
+
>>> import numpy as np
|
| 948 |
+
>>> from scipy.interpolate import BSpline, make_interp_spline
|
| 949 |
+
>>> x = np.linspace(0, 10, 5)
|
| 950 |
+
>>> y = np.sin(x)
|
| 951 |
+
>>> spl = make_interp_spline(x, y, k=3)
|
| 952 |
+
>>> spl.t
|
| 953 |
+
array([ 0., 0., 0., 0., 5., 10., 10., 10., 10.])
|
| 954 |
+
|
| 955 |
+
Insert a single knot
|
| 956 |
+
|
| 957 |
+
>>> spl_1 = spl.insert_knot(3)
|
| 958 |
+
>>> spl_1.t
|
| 959 |
+
array([ 0., 0., 0., 0., 3., 5., 10., 10., 10., 10.])
|
| 960 |
+
|
| 961 |
+
Insert a multiple knot
|
| 962 |
+
|
| 963 |
+
>>> spl_2 = spl.insert_knot(8, m=3)
|
| 964 |
+
>>> spl_2.t
|
| 965 |
+
array([ 0., 0., 0., 0., 5., 8., 8., 8., 10., 10., 10., 10.])
|
| 966 |
+
|
| 967 |
+
"""
|
| 968 |
+
x = float(x)
|
| 969 |
+
|
| 970 |
+
if x < self._t[self.k] or x > self._t[-self.k-1]:
|
| 971 |
+
raise ValueError(f"Cannot insert a knot at {x}.")
|
| 972 |
+
if m <= 0:
|
| 973 |
+
raise ValueError(f"`m` must be positive, got {m = }.")
|
| 974 |
+
|
| 975 |
+
tt = self._t.copy()
|
| 976 |
+
cc = self._c.copy()
|
| 977 |
+
|
| 978 |
+
for _ in range(m):
|
| 979 |
+
tt, cc = _insert(x, tt, cc, self.k, self.extrapolate == "periodic")
|
| 980 |
+
tt, cc = self._asarray(tt), self._asarray(cc)
|
| 981 |
+
return self.construct_fast(tt, cc, self.k, self.extrapolate, self.axis)
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
def _insert(xval, t, c, k, periodic=False):
|
| 985 |
+
"""Insert a single knot at `xval`."""
|
| 986 |
+
#
|
| 987 |
+
# This is a port of the FORTRAN `insert` routine by P. Dierckx,
|
| 988 |
+
# https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/insert.f
|
| 989 |
+
# which carries the following comment:
|
| 990 |
+
#
|
| 991 |
+
# subroutine insert inserts a new knot x into a spline function s(x)
|
| 992 |
+
# of degree k and calculates the b-spline representation of s(x) with
|
| 993 |
+
# respect to the new set of knots. in addition, if iopt.ne.0, s(x)
|
| 994 |
+
# will be considered as a periodic spline with period per=t(n-k)-t(k+1)
|
| 995 |
+
# satisfying the boundary constraints
|
| 996 |
+
# t(i+n-2*k-1) = t(i)+per ,i=1,2,...,2*k+1
|
| 997 |
+
# c(i+n-2*k-1) = c(i) ,i=1,2,...,k
|
| 998 |
+
# in that case, the knots and b-spline coefficients returned will also
|
| 999 |
+
# satisfy these boundary constraints, i.e.
|
| 1000 |
+
# tt(i+nn-2*k-1) = tt(i)+per ,i=1,2,...,2*k+1
|
| 1001 |
+
# cc(i+nn-2*k-1) = cc(i) ,i=1,2,...,k
|
| 1002 |
+
interval = _dierckx.find_interval(t, k, float(xval), k, False)
|
| 1003 |
+
if interval < 0:
|
| 1004 |
+
# extrapolated values are guarded for in BSpline.insert_knot
|
| 1005 |
+
raise ValueError(f"Cannot insert the knot at {xval}.")
|
| 1006 |
+
|
| 1007 |
+
# super edge case: a knot with multiplicity > k+1
|
| 1008 |
+
# see https://github.com/scipy/scipy/commit/037204c3e91
|
| 1009 |
+
if t[interval] == t[interval + k + 1]:
|
| 1010 |
+
interval -= 1
|
| 1011 |
+
|
| 1012 |
+
if periodic:
|
| 1013 |
+
if (interval + 1 <= 2*k) and (interval + 1 >= t.shape[0] - 2*k):
|
| 1014 |
+
# in case of a periodic spline (iopt.ne.0) there must be
|
| 1015 |
+
# either at least k interior knots t(j) satisfying t(k+1)<t(j)<=x
|
| 1016 |
+
# or at least k interior knots t(j) satisfying x<=t(j)<t(n-k)
|
| 1017 |
+
raise ValueError("Not enough internal knots.")
|
| 1018 |
+
|
| 1019 |
+
# knots
|
| 1020 |
+
tt = np.r_[t[:interval+1], xval, t[interval+1:]]
|
| 1021 |
+
|
| 1022 |
+
newshape = (c.shape[0] + 1,) + c.shape[1:]
|
| 1023 |
+
cc = np.zeros(newshape, dtype=c.dtype)
|
| 1024 |
+
|
| 1025 |
+
# coefficients
|
| 1026 |
+
cc[interval+1:, ...] = c[interval:, ...]
|
| 1027 |
+
|
| 1028 |
+
for i in range(interval, interval-k, -1):
|
| 1029 |
+
fac = (xval - tt[i]) / (tt[i+k+1] - tt[i])
|
| 1030 |
+
cc[i, ...] = fac*c[i, ...] + (1. - fac)*c[i-1, ...]
|
| 1031 |
+
|
| 1032 |
+
cc[:interval - k+1, ...] = c[:interval - k+1, ...]
|
| 1033 |
+
|
| 1034 |
+
if periodic:
|
| 1035 |
+
# c incorporate the boundary conditions for a periodic spline.
|
| 1036 |
+
n = tt.shape[0]
|
| 1037 |
+
nk = n - k - 1
|
| 1038 |
+
n2k = n - 2*k - 1
|
| 1039 |
+
T = tt[nk] - tt[k] # period
|
| 1040 |
+
|
| 1041 |
+
if interval >= nk - k:
|
| 1042 |
+
# adjust the left-hand boundary knots & coefs
|
| 1043 |
+
tt[:k] = tt[nk - k:nk] - T
|
| 1044 |
+
cc[:k, ...] = cc[n2k:n2k + k, ...]
|
| 1045 |
+
|
| 1046 |
+
if interval <= 2*k-1:
|
| 1047 |
+
# adjust the right-hand boundary knots & coefs
|
| 1048 |
+
tt[n-k:] = tt[k+1:k+1+k] + T
|
| 1049 |
+
cc[n2k:n2k + k, ...] = cc[:k, ...]
|
| 1050 |
+
|
| 1051 |
+
return tt, cc
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
#################################
|
| 1055 |
+
# Interpolating spline helpers #
|
| 1056 |
+
#################################
|
| 1057 |
+
|
| 1058 |
+
def _not_a_knot(x, k):
|
| 1059 |
+
"""Given data x, construct the knot vector w/ not-a-knot BC.
|
| 1060 |
+
cf de Boor, XIII(12).
|
| 1061 |
+
|
| 1062 |
+
For even k, it's a bit ad hoc: Greville sites + omit 2nd and 2nd-to-last
|
| 1063 |
+
data points, a la not-a-knot.
|
| 1064 |
+
This seems to match what Dierckx does, too:
|
| 1065 |
+
https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L63-L80
|
| 1066 |
+
"""
|
| 1067 |
+
x = np.asarray(x)
|
| 1068 |
+
if k % 2 == 1:
|
| 1069 |
+
k2 = (k + 1) // 2
|
| 1070 |
+
t = x.copy()
|
| 1071 |
+
else:
|
| 1072 |
+
k2 = k // 2
|
| 1073 |
+
t = (x[1:] + x[:-1]) / 2
|
| 1074 |
+
|
| 1075 |
+
t = t[k2:-k2]
|
| 1076 |
+
t = np.r_[(x[0],)*(k+1), t, (x[-1],)*(k+1)]
|
| 1077 |
+
return t
|
| 1078 |
+
|
| 1079 |
+
|
| 1080 |
+
def _augknt(x, k):
|
| 1081 |
+
"""Construct a knot vector appropriate for the order-k interpolation."""
|
| 1082 |
+
return np.r_[(x[0],)*k, x, (x[-1],)*k]
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
def _convert_string_aliases(deriv, target_shape):
|
| 1086 |
+
if isinstance(deriv, str):
|
| 1087 |
+
if deriv == "clamped":
|
| 1088 |
+
deriv = [(1, np.zeros(target_shape))]
|
| 1089 |
+
elif deriv == "natural":
|
| 1090 |
+
deriv = [(2, np.zeros(target_shape))]
|
| 1091 |
+
else:
|
| 1092 |
+
raise ValueError(f"Unknown boundary condition : {deriv}")
|
| 1093 |
+
return deriv
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def _process_deriv_spec(deriv):
|
| 1097 |
+
if deriv is not None:
|
| 1098 |
+
try:
|
| 1099 |
+
ords, vals = zip(*deriv)
|
| 1100 |
+
except TypeError as e:
|
| 1101 |
+
msg = ("Derivatives, `bc_type`, should be specified as a pair of "
|
| 1102 |
+
"iterables of pairs of (order, value).")
|
| 1103 |
+
raise ValueError(msg) from e
|
| 1104 |
+
else:
|
| 1105 |
+
ords, vals = [], []
|
| 1106 |
+
return np.atleast_1d(ords, vals)
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
def _woodbury_algorithm(A, ur, ll, b, k):
|
| 1110 |
+
'''
|
| 1111 |
+
Solve a cyclic banded linear system with upper right
|
| 1112 |
+
and lower blocks of size ``(k-1) / 2`` using
|
| 1113 |
+
the Woodbury formula
|
| 1114 |
+
|
| 1115 |
+
Parameters
|
| 1116 |
+
----------
|
| 1117 |
+
A : 2-D array, shape(k, n)
|
| 1118 |
+
Matrix of diagonals of original matrix (see
|
| 1119 |
+
``solve_banded`` documentation).
|
| 1120 |
+
ur : 2-D array, shape(bs, bs)
|
| 1121 |
+
Upper right block matrix.
|
| 1122 |
+
ll : 2-D array, shape(bs, bs)
|
| 1123 |
+
Lower left block matrix.
|
| 1124 |
+
b : 1-D array, shape(n,)
|
| 1125 |
+
Vector of constant terms of the system of linear equations.
|
| 1126 |
+
k : int
|
| 1127 |
+
B-spline degree.
|
| 1128 |
+
|
| 1129 |
+
Returns
|
| 1130 |
+
-------
|
| 1131 |
+
c : 1-D array, shape(n,)
|
| 1132 |
+
Solution of the original system of linear equations.
|
| 1133 |
+
|
| 1134 |
+
Notes
|
| 1135 |
+
-----
|
| 1136 |
+
This algorithm works only for systems with banded matrix A plus
|
| 1137 |
+
a correction term U @ V.T, where the matrix U @ V.T gives upper right
|
| 1138 |
+
and lower left block of A
|
| 1139 |
+
The system is solved with the following steps:
|
| 1140 |
+
1. New systems of linear equations are constructed:
|
| 1141 |
+
A @ z_i = u_i,
|
| 1142 |
+
u_i - column vector of U,
|
| 1143 |
+
i = 1, ..., k - 1
|
| 1144 |
+
2. Matrix Z is formed from vectors z_i:
|
| 1145 |
+
Z = [ z_1 | z_2 | ... | z_{k - 1} ]
|
| 1146 |
+
3. Matrix H = (1 + V.T @ Z)^{-1}
|
| 1147 |
+
4. The system A' @ y = b is solved
|
| 1148 |
+
5. x = y - Z @ (H @ V.T @ y)
|
| 1149 |
+
Also, ``n`` should be greater than ``k``, otherwise corner block
|
| 1150 |
+
elements will intersect with diagonals.
|
| 1151 |
+
|
| 1152 |
+
Examples
|
| 1153 |
+
--------
|
| 1154 |
+
Consider the case of n = 8, k = 5 (size of blocks - 2 x 2).
|
| 1155 |
+
The matrix of a system: U: V:
|
| 1156 |
+
x x x * * a b a b 0 0 0 0 1 0
|
| 1157 |
+
x x x x * * c 0 c 0 0 0 0 0 1
|
| 1158 |
+
x x x x x * * 0 0 0 0 0 0 0 0
|
| 1159 |
+
* x x x x x * 0 0 0 0 0 0 0 0
|
| 1160 |
+
* * x x x x x 0 0 0 0 0 0 0 0
|
| 1161 |
+
d * * x x x x 0 0 d 0 1 0 0 0
|
| 1162 |
+
e f * * x x x 0 0 e f 0 1 0 0
|
| 1163 |
+
|
| 1164 |
+
References
|
| 1165 |
+
----------
|
| 1166 |
+
.. [1] William H. Press, Saul A. Teukolsky, William T. Vetterling
|
| 1167 |
+
and Brian P. Flannery, Numerical Recipes, 2007, Section 2.7.3
|
| 1168 |
+
|
| 1169 |
+
'''
|
| 1170 |
+
k_mod = k - k % 2
|
| 1171 |
+
bs = int((k - 1) / 2) + (k + 1) % 2
|
| 1172 |
+
|
| 1173 |
+
n = A.shape[1] + 1
|
| 1174 |
+
U = np.zeros((n - 1, k_mod))
|
| 1175 |
+
VT = np.zeros((k_mod, n - 1)) # V transpose
|
| 1176 |
+
|
| 1177 |
+
# upper right block
|
| 1178 |
+
U[:bs, :bs] = ur
|
| 1179 |
+
VT[np.arange(bs), np.arange(bs) - bs] = 1
|
| 1180 |
+
|
| 1181 |
+
# lower left block
|
| 1182 |
+
U[-bs:, -bs:] = ll
|
| 1183 |
+
VT[np.arange(bs) - bs, np.arange(bs)] = 1
|
| 1184 |
+
|
| 1185 |
+
Z = solve_banded((bs, bs), A, U)
|
| 1186 |
+
|
| 1187 |
+
H = solve(np.identity(k_mod) + VT @ Z, np.identity(k_mod))
|
| 1188 |
+
|
| 1189 |
+
y = solve_banded((bs, bs), A, b)
|
| 1190 |
+
c = y - Z @ (H @ (VT @ y))
|
| 1191 |
+
|
| 1192 |
+
return c
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
def _periodic_knots(x, k):
|
| 1196 |
+
'''
|
| 1197 |
+
returns vector of nodes on circle
|
| 1198 |
+
'''
|
| 1199 |
+
xc = np.copy(x)
|
| 1200 |
+
n = len(xc)
|
| 1201 |
+
if k % 2 == 0:
|
| 1202 |
+
dx = np.diff(xc)
|
| 1203 |
+
xc[1: -1] -= dx[:-1] / 2
|
| 1204 |
+
dx = np.diff(xc)
|
| 1205 |
+
t = np.zeros(n + 2 * k)
|
| 1206 |
+
t[k: -k] = xc
|
| 1207 |
+
for i in range(0, k):
|
| 1208 |
+
# filling first `k` elements in descending order
|
| 1209 |
+
t[k - i - 1] = t[k - i] - dx[-(i % (n - 1)) - 1]
|
| 1210 |
+
# filling last `k` elements in ascending order
|
| 1211 |
+
t[-k + i] = t[-k + i - 1] + dx[i % (n - 1)]
|
| 1212 |
+
return t
|
| 1213 |
+
|
| 1214 |
+
|
| 1215 |
+
def _make_interp_per_full_matr(x, y, t, k):
|
| 1216 |
+
'''
|
| 1217 |
+
Returns a solution of a system for B-spline interpolation with periodic
|
| 1218 |
+
boundary conditions. First ``k - 1`` rows of matrix are conditions of
|
| 1219 |
+
periodicity (continuity of ``k - 1`` derivatives at the boundary points).
|
| 1220 |
+
Last ``n`` rows are interpolation conditions.
|
| 1221 |
+
RHS is ``k - 1`` zeros and ``n`` ordinates in this case.
|
| 1222 |
+
|
| 1223 |
+
Parameters
|
| 1224 |
+
----------
|
| 1225 |
+
x : 1-D array, shape (n,)
|
| 1226 |
+
Values of x - coordinate of a given set of points.
|
| 1227 |
+
y : 1-D array, shape (n,)
|
| 1228 |
+
Values of y - coordinate of a given set of points.
|
| 1229 |
+
t : 1-D array, shape(n+2*k,)
|
| 1230 |
+
Vector of knots.
|
| 1231 |
+
k : int
|
| 1232 |
+
The maximum degree of spline
|
| 1233 |
+
|
| 1234 |
+
Returns
|
| 1235 |
+
-------
|
| 1236 |
+
c : 1-D array, shape (n+k-1,)
|
| 1237 |
+
B-spline coefficients
|
| 1238 |
+
|
| 1239 |
+
Notes
|
| 1240 |
+
-----
|
| 1241 |
+
``t`` is supposed to be taken on circle.
|
| 1242 |
+
|
| 1243 |
+
'''
|
| 1244 |
+
|
| 1245 |
+
x, y, t = map(np.asarray, (x, y, t))
|
| 1246 |
+
|
| 1247 |
+
n = x.size
|
| 1248 |
+
# LHS: the colocation matrix + derivatives at edges
|
| 1249 |
+
matr = np.zeros((n + k - 1, n + k - 1))
|
| 1250 |
+
|
| 1251 |
+
# derivatives at x[0] and x[-1]:
|
| 1252 |
+
for i in range(k - 1):
|
| 1253 |
+
bb = _dierckx.evaluate_all_bspl(t, k, x[0], k, i + 1)
|
| 1254 |
+
matr[i, : k + 1] += bb
|
| 1255 |
+
bb = _dierckx.evaluate_all_bspl(t, k, x[-1], n + k - 1, i + 1)[:-1]
|
| 1256 |
+
matr[i, -k:] -= bb
|
| 1257 |
+
|
| 1258 |
+
# colocation matrix
|
| 1259 |
+
for i in range(n):
|
| 1260 |
+
xval = x[i]
|
| 1261 |
+
# find interval
|
| 1262 |
+
if xval == t[k]:
|
| 1263 |
+
left = k
|
| 1264 |
+
else:
|
| 1265 |
+
left = np.searchsorted(t, xval) - 1
|
| 1266 |
+
|
| 1267 |
+
# fill a row
|
| 1268 |
+
bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
|
| 1269 |
+
matr[i + k - 1, left-k:left+1] = bb
|
| 1270 |
+
|
| 1271 |
+
# RHS
|
| 1272 |
+
b = np.r_[[0] * (k - 1), y]
|
| 1273 |
+
|
| 1274 |
+
c = solve(matr, b)
|
| 1275 |
+
return c
|
| 1276 |
+
|
| 1277 |
+
|
| 1278 |
+
def _handle_lhs_derivatives(t, k, xval, ab, kl, ku, deriv_ords, offset=0):
|
| 1279 |
+
""" Fill in the entries of the colocation matrix corresponding to known
|
| 1280 |
+
derivatives at `xval`.
|
| 1281 |
+
|
| 1282 |
+
The colocation matrix is in the banded storage, as prepared by _coloc.
|
| 1283 |
+
No error checking.
|
| 1284 |
+
|
| 1285 |
+
Parameters
|
| 1286 |
+
----------
|
| 1287 |
+
t : ndarray, shape (nt + k + 1,)
|
| 1288 |
+
knots
|
| 1289 |
+
k : integer
|
| 1290 |
+
B-spline order
|
| 1291 |
+
xval : float
|
| 1292 |
+
The value at which to evaluate the derivatives at.
|
| 1293 |
+
ab : ndarray, shape(2*kl + ku + 1, nt), Fortran order
|
| 1294 |
+
B-spline colocation matrix.
|
| 1295 |
+
This argument is modified *in-place*.
|
| 1296 |
+
kl : integer
|
| 1297 |
+
Number of lower diagonals of ab.
|
| 1298 |
+
ku : integer
|
| 1299 |
+
Number of upper diagonals of ab.
|
| 1300 |
+
deriv_ords : 1D ndarray
|
| 1301 |
+
Orders of derivatives known at xval
|
| 1302 |
+
offset : integer, optional
|
| 1303 |
+
Skip this many rows of the matrix ab.
|
| 1304 |
+
|
| 1305 |
+
"""
|
| 1306 |
+
# find where `xval` is in the knot vector, `t`
|
| 1307 |
+
left = _dierckx.find_interval(t, k, float(xval), k, False)
|
| 1308 |
+
|
| 1309 |
+
# compute and fill in the derivatives @ xval
|
| 1310 |
+
for row in range(deriv_ords.shape[0]):
|
| 1311 |
+
nu = deriv_ords[row]
|
| 1312 |
+
wrk = _dierckx.evaluate_all_bspl(t, k, xval, left, nu)
|
| 1313 |
+
|
| 1314 |
+
# if A were a full matrix, it would be just
|
| 1315 |
+
# ``A[row + offset, left-k:left+1] = bb``.
|
| 1316 |
+
for a in range(k+1):
|
| 1317 |
+
clmn = left - k + a
|
| 1318 |
+
ab[kl + ku + offset + row - clmn, clmn] = wrk[a]
|
| 1319 |
+
|
| 1320 |
+
|
| 1321 |
+
def _make_periodic_spline(x, y, t, k, axis, *, xp):
|
| 1322 |
+
'''
|
| 1323 |
+
Compute the (coefficients of) interpolating B-spline with periodic
|
| 1324 |
+
boundary conditions.
|
| 1325 |
+
|
| 1326 |
+
Parameters
|
| 1327 |
+
----------
|
| 1328 |
+
x : array_like, shape (n,)
|
| 1329 |
+
Abscissas.
|
| 1330 |
+
y : array_like, shape (n,)
|
| 1331 |
+
Ordinates.
|
| 1332 |
+
k : int
|
| 1333 |
+
B-spline degree.
|
| 1334 |
+
t : array_like, shape (n + 2 * k,).
|
| 1335 |
+
Knots taken on a circle, ``k`` on the left and ``k`` on the right
|
| 1336 |
+
of the vector ``x``.
|
| 1337 |
+
|
| 1338 |
+
Returns
|
| 1339 |
+
-------
|
| 1340 |
+
b : `BSpline` object
|
| 1341 |
+
A `BSpline` object of the degree ``k`` and with knots ``t``.
|
| 1342 |
+
|
| 1343 |
+
Notes
|
| 1344 |
+
-----
|
| 1345 |
+
The original system is formed by ``n + k - 1`` equations where the first
|
| 1346 |
+
``k - 1`` of them stand for the ``k - 1`` derivatives continuity on the
|
| 1347 |
+
edges while the other equations correspond to an interpolating case
|
| 1348 |
+
(matching all the input points). Due to a special form of knot vector, it
|
| 1349 |
+
can be proved that in the original system the first and last ``k``
|
| 1350 |
+
coefficients of a spline function are the same, respectively. It follows
|
| 1351 |
+
from the fact that all ``k - 1`` derivatives are equal term by term at ends
|
| 1352 |
+
and that the matrix of the original system of linear equations is
|
| 1353 |
+
non-degenerate. So, we can reduce the number of equations to ``n - 1``
|
| 1354 |
+
(first ``k - 1`` equations could be reduced). Another trick of this
|
| 1355 |
+
implementation is cyclic shift of values of B-splines due to equality of
|
| 1356 |
+
``k`` unknown coefficients. With this we can receive matrix of the system
|
| 1357 |
+
with upper right and lower left blocks, and ``k`` diagonals. It allows
|
| 1358 |
+
to use Woodbury formula to optimize the computations.
|
| 1359 |
+
|
| 1360 |
+
'''
|
| 1361 |
+
n = y.shape[0]
|
| 1362 |
+
|
| 1363 |
+
extradim = prod(y.shape[1:])
|
| 1364 |
+
y_new = y.reshape(n, extradim)
|
| 1365 |
+
c = np.zeros((n + k - 1, extradim))
|
| 1366 |
+
|
| 1367 |
+
# n <= k case is solved with full matrix
|
| 1368 |
+
if n <= k:
|
| 1369 |
+
for i in range(extradim):
|
| 1370 |
+
c[:, i] = _make_interp_per_full_matr(x, y_new[:, i], t, k)
|
| 1371 |
+
c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
|
| 1372 |
+
t, c = xp.asarray(t), xp.asarray(c)
|
| 1373 |
+
return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
|
| 1374 |
+
|
| 1375 |
+
nt = len(t) - k - 1
|
| 1376 |
+
|
| 1377 |
+
# size of block elements
|
| 1378 |
+
kul = int(k / 2)
|
| 1379 |
+
|
| 1380 |
+
# kl = ku = k
|
| 1381 |
+
ab = np.zeros((3 * k + 1, nt), dtype=np.float64, order='F')
|
| 1382 |
+
|
| 1383 |
+
# upper right and lower left blocks
|
| 1384 |
+
ur = np.zeros((kul, kul))
|
| 1385 |
+
ll = np.zeros_like(ur)
|
| 1386 |
+
|
| 1387 |
+
# `offset` is made to shift all the non-zero elements to the end of the
|
| 1388 |
+
# matrix
|
| 1389 |
+
# NB: 1. drop the last element of `x` because `x[0] = x[-1] + T` & `y[0] == y[-1]`
|
| 1390 |
+
# 2. pass ab.T to _coloc to make it C-ordered; below it'll be fed to banded
|
| 1391 |
+
# LAPACK, which needs F-ordered arrays
|
| 1392 |
+
_dierckx._coloc(x[:-1], t, k, ab.T, k)
|
| 1393 |
+
|
| 1394 |
+
# remove zeros before the matrix
|
| 1395 |
+
ab = ab[-k - (k + 1) % 2:, :]
|
| 1396 |
+
|
| 1397 |
+
# The least elements in rows (except repetitions) are diagonals
|
| 1398 |
+
# of block matrices. Upper right matrix is an upper triangular
|
| 1399 |
+
# matrix while lower left is a lower triangular one.
|
| 1400 |
+
for i in range(kul):
|
| 1401 |
+
ur += np.diag(ab[-i - 1, i: kul], k=i)
|
| 1402 |
+
ll += np.diag(ab[i, -kul - (k % 2): n - 1 + 2 * kul - i], k=-i)
|
| 1403 |
+
|
| 1404 |
+
# remove elements that occur in the last point
|
| 1405 |
+
# (first and last points are equivalent)
|
| 1406 |
+
A = ab[:, kul: -k + kul]
|
| 1407 |
+
|
| 1408 |
+
for i in range(extradim):
|
| 1409 |
+
cc = _woodbury_algorithm(A, ur, ll, y_new[:, i][:-1], k)
|
| 1410 |
+
c[:, i] = np.concatenate((cc[-kul:], cc, cc[:kul + k % 2]))
|
| 1411 |
+
c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
|
| 1412 |
+
t, c = xp.asarray(t), xp.asarray(c)
|
| 1413 |
+
return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
|
| 1414 |
+
|
| 1415 |
+
|
| 1416 |
+
@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
|
| 1417 |
+
def make_interp_spline(x, y, k=3, t=None, bc_type=None, axis=0,
|
| 1418 |
+
check_finite=True):
|
| 1419 |
+
"""Create an interpolating B-spline with specified degree and boundary conditions.
|
| 1420 |
+
|
| 1421 |
+
Parameters
|
| 1422 |
+
----------
|
| 1423 |
+
x : array_like, shape (n,)
|
| 1424 |
+
Abscissas.
|
| 1425 |
+
y : array_like, shape (n, ...)
|
| 1426 |
+
Ordinates.
|
| 1427 |
+
k : int, optional
|
| 1428 |
+
B-spline degree. Default is cubic, ``k = 3``.
|
| 1429 |
+
t : array_like, shape (nt + k + 1,), optional.
|
| 1430 |
+
Knots.
|
| 1431 |
+
The number of knots needs to agree with the number of data points and
|
| 1432 |
+
the number of derivatives at the edges. Specifically, ``nt - n`` must
|
| 1433 |
+
equal ``len(deriv_l) + len(deriv_r)``.
|
| 1434 |
+
bc_type : 2-tuple or None
|
| 1435 |
+
Boundary conditions.
|
| 1436 |
+
Default is None, which means choosing the boundary conditions
|
| 1437 |
+
automatically. Otherwise, it must be a length-two tuple where the first
|
| 1438 |
+
element (``deriv_l``) sets the boundary conditions at ``x[0]`` and
|
| 1439 |
+
the second element (``deriv_r``) sets the boundary conditions at
|
| 1440 |
+
``x[-1]``. Each of these must be an iterable of pairs
|
| 1441 |
+
``(order, value)`` which gives the values of derivatives of specified
|
| 1442 |
+
orders at the given edge of the interpolation interval.
|
| 1443 |
+
Alternatively, the following string aliases are recognized:
|
| 1444 |
+
|
| 1445 |
+
* ``"clamped"``: The first derivatives at the ends are zero. This is
|
| 1446 |
+
equivalent to ``bc_type=([(1, 0.0)], [(1, 0.0)])``.
|
| 1447 |
+
* ``"natural"``: The second derivatives at ends are zero. This is
|
| 1448 |
+
equivalent to ``bc_type=([(2, 0.0)], [(2, 0.0)])``.
|
| 1449 |
+
* ``"not-a-knot"`` (default): The first and second segments are the
|
| 1450 |
+
same polynomial. This is equivalent to having ``bc_type=None``.
|
| 1451 |
+
* ``"periodic"``: The values and the first ``k-1`` derivatives at the
|
| 1452 |
+
ends are equivalent.
|
| 1453 |
+
|
| 1454 |
+
axis : int, optional
|
| 1455 |
+
Interpolation axis. Default is 0.
|
| 1456 |
+
check_finite : bool, optional
|
| 1457 |
+
Whether to check that the input arrays contain only finite numbers.
|
| 1458 |
+
Disabling may give a performance gain, but may result in problems
|
| 1459 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 1460 |
+
Default is True.
|
| 1461 |
+
|
| 1462 |
+
Returns
|
| 1463 |
+
-------
|
| 1464 |
+
b : `BSpline` object
|
| 1465 |
+
A `BSpline` object of the degree ``k`` and with knots ``t``.
|
| 1466 |
+
|
| 1467 |
+
See Also
|
| 1468 |
+
--------
|
| 1469 |
+
BSpline : base class representing the B-spline objects
|
| 1470 |
+
CubicSpline : a cubic spline in the polynomial basis
|
| 1471 |
+
make_lsq_spline : a similar factory function for spline fitting
|
| 1472 |
+
UnivariateSpline : a wrapper over FITPACK spline fitting routines
|
| 1473 |
+
splrep : a wrapper over FITPACK spline fitting routines
|
| 1474 |
+
|
| 1475 |
+
Examples
|
| 1476 |
+
--------
|
| 1477 |
+
Use cubic interpolation on Chebyshev nodes:
|
| 1478 |
+
|
| 1479 |
+
>>> import numpy as np
|
| 1480 |
+
>>> import matplotlib.pyplot as plt
|
| 1481 |
+
>>> def cheb_nodes(N):
|
| 1482 |
+
... jj = 2.*np.arange(N) + 1
|
| 1483 |
+
... x = np.cos(np.pi * jj / 2 / N)[::-1]
|
| 1484 |
+
... return x
|
| 1485 |
+
|
| 1486 |
+
>>> x = cheb_nodes(20)
|
| 1487 |
+
>>> y = np.sqrt(1 - x**2)
|
| 1488 |
+
|
| 1489 |
+
>>> from scipy.interpolate import BSpline, make_interp_spline
|
| 1490 |
+
>>> b = make_interp_spline(x, y)
|
| 1491 |
+
>>> np.allclose(b(x), y)
|
| 1492 |
+
True
|
| 1493 |
+
|
| 1494 |
+
Note that the default is a cubic spline with a not-a-knot boundary condition
|
| 1495 |
+
|
| 1496 |
+
>>> b.k
|
| 1497 |
+
3
|
| 1498 |
+
|
| 1499 |
+
Here we use a 'natural' spline, with zero 2nd derivatives at edges:
|
| 1500 |
+
|
| 1501 |
+
>>> l, r = [(2, 0.0)], [(2, 0.0)]
|
| 1502 |
+
>>> b_n = make_interp_spline(x, y, bc_type=(l, r)) # or, bc_type="natural"
|
| 1503 |
+
>>> np.allclose(b_n(x), y)
|
| 1504 |
+
True
|
| 1505 |
+
>>> x0, x1 = x[0], x[-1]
|
| 1506 |
+
>>> np.allclose([b_n(x0, 2), b_n(x1, 2)], [0, 0])
|
| 1507 |
+
True
|
| 1508 |
+
|
| 1509 |
+
Interpolation of parametric curves is also supported. As an example, we
|
| 1510 |
+
compute a discretization of a snail curve in polar coordinates
|
| 1511 |
+
|
| 1512 |
+
>>> phi = np.linspace(0, 2.*np.pi, 40)
|
| 1513 |
+
>>> r = 0.3 + np.cos(phi)
|
| 1514 |
+
>>> x, y = r*np.cos(phi), r*np.sin(phi) # convert to Cartesian coordinates
|
| 1515 |
+
|
| 1516 |
+
Build an interpolating curve, parameterizing it by the angle
|
| 1517 |
+
|
| 1518 |
+
>>> spl = make_interp_spline(phi, np.c_[x, y])
|
| 1519 |
+
|
| 1520 |
+
Evaluate the interpolant on a finer grid (note that we transpose the result
|
| 1521 |
+
to unpack it into a pair of x- and y-arrays)
|
| 1522 |
+
|
| 1523 |
+
>>> phi_new = np.linspace(0, 2.*np.pi, 100)
|
| 1524 |
+
>>> x_new, y_new = spl(phi_new).T
|
| 1525 |
+
|
| 1526 |
+
Plot the result
|
| 1527 |
+
|
| 1528 |
+
>>> plt.plot(x, y, 'o')
|
| 1529 |
+
>>> plt.plot(x_new, y_new, '-')
|
| 1530 |
+
>>> plt.show()
|
| 1531 |
+
|
| 1532 |
+
Build a B-spline curve with 2 dimensional y
|
| 1533 |
+
|
| 1534 |
+
>>> x = np.linspace(0, 2*np.pi, 10)
|
| 1535 |
+
>>> y = np.array([np.sin(x), np.cos(x)])
|
| 1536 |
+
|
| 1537 |
+
Periodic condition is satisfied because y coordinates of points on the ends
|
| 1538 |
+
are equivalent
|
| 1539 |
+
|
| 1540 |
+
>>> ax = plt.axes(projection='3d')
|
| 1541 |
+
>>> xx = np.linspace(0, 2*np.pi, 100)
|
| 1542 |
+
>>> bspl = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
|
| 1543 |
+
>>> ax.plot3D(xx, *bspl(xx))
|
| 1544 |
+
>>> ax.scatter3D(x, *y, color='red')
|
| 1545 |
+
>>> plt.show()
|
| 1546 |
+
|
| 1547 |
+
"""
|
| 1548 |
+
# convert string aliases for the boundary conditions
|
| 1549 |
+
if bc_type is None or bc_type == 'not-a-knot' or bc_type == 'periodic':
|
| 1550 |
+
deriv_l, deriv_r = None, None
|
| 1551 |
+
elif isinstance(bc_type, str):
|
| 1552 |
+
deriv_l, deriv_r = bc_type, bc_type
|
| 1553 |
+
else:
|
| 1554 |
+
try:
|
| 1555 |
+
deriv_l, deriv_r = bc_type
|
| 1556 |
+
except TypeError as e:
|
| 1557 |
+
raise ValueError(f"Unknown boundary condition: {bc_type}") from e
|
| 1558 |
+
|
| 1559 |
+
xp = array_namespace(x, y, t)
|
| 1560 |
+
x = _as_float_array(x, check_finite)
|
| 1561 |
+
y = _as_float_array(y, check_finite)
|
| 1562 |
+
|
| 1563 |
+
axis = normalize_axis_index(axis, y.ndim)
|
| 1564 |
+
y = np.moveaxis(y, axis, 0) # now internally interp axis is zero
|
| 1565 |
+
|
| 1566 |
+
# sanity check the input
|
| 1567 |
+
if bc_type == 'periodic' and not np.allclose(y[0], y[-1], atol=1e-15):
|
| 1568 |
+
raise ValueError("First and last points does not match while "
|
| 1569 |
+
"periodic case expected")
|
| 1570 |
+
if x.size != y.shape[0]:
|
| 1571 |
+
raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
|
| 1572 |
+
if np.any(x[1:] == x[:-1]):
|
| 1573 |
+
raise ValueError("Expect x to not have duplicates")
|
| 1574 |
+
if x.ndim != 1 or np.any(x[1:] < x[:-1]):
|
| 1575 |
+
raise ValueError("Expect x to be a 1D strictly increasing sequence.")
|
| 1576 |
+
|
| 1577 |
+
# special-case k=0 right away
|
| 1578 |
+
if k == 0:
|
| 1579 |
+
if any(_ is not None for _ in (t, deriv_l, deriv_r)):
|
| 1580 |
+
raise ValueError("Too much info for k=0: t and bc_type can only "
|
| 1581 |
+
"be None.")
|
| 1582 |
+
t = np.r_[x, x[-1]]
|
| 1583 |
+
c = np.asarray(y)
|
| 1584 |
+
c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
|
| 1585 |
+
t, c = xp.asarray(t), xp.asarray(c)
|
| 1586 |
+
return BSpline.construct_fast(t, c, k, axis=axis)
|
| 1587 |
+
|
| 1588 |
+
# special-case k=1 (e.g., Lyche and Morken, Eq.(2.16))
|
| 1589 |
+
if k == 1 and t is None:
|
| 1590 |
+
if not (deriv_l is None and deriv_r is None):
|
| 1591 |
+
raise ValueError("Too much info for k=1: bc_type can only be None.")
|
| 1592 |
+
t = np.r_[x[0], x, x[-1]]
|
| 1593 |
+
c = np.asarray(y)
|
| 1594 |
+
c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
|
| 1595 |
+
t, c = xp.asarray(t), xp.asarray(c)
|
| 1596 |
+
return BSpline.construct_fast(t, c, k, axis=axis)
|
| 1597 |
+
|
| 1598 |
+
k = operator.index(k)
|
| 1599 |
+
|
| 1600 |
+
if bc_type == 'periodic' and t is not None:
|
| 1601 |
+
raise NotImplementedError("For periodic case t is constructed "
|
| 1602 |
+
"automatically and can not be passed "
|
| 1603 |
+
"manually")
|
| 1604 |
+
|
| 1605 |
+
# come up with a sensible knot vector, if needed
|
| 1606 |
+
if t is None:
|
| 1607 |
+
if deriv_l is None and deriv_r is None:
|
| 1608 |
+
if bc_type == 'periodic':
|
| 1609 |
+
t = _periodic_knots(x, k)
|
| 1610 |
+
else:
|
| 1611 |
+
t = _not_a_knot(x, k)
|
| 1612 |
+
else:
|
| 1613 |
+
t = _augknt(x, k)
|
| 1614 |
+
|
| 1615 |
+
t = _as_float_array(t, check_finite)
|
| 1616 |
+
|
| 1617 |
+
if k < 0:
|
| 1618 |
+
raise ValueError("Expect non-negative k.")
|
| 1619 |
+
if t.ndim != 1 or np.any(t[1:] < t[:-1]):
|
| 1620 |
+
raise ValueError("Expect t to be a 1-D sorted array_like.")
|
| 1621 |
+
if t.size < x.size + k + 1:
|
| 1622 |
+
raise ValueError(f"Got {t.size} knots, need at least {x.size + k + 1}.")
|
| 1623 |
+
if (x[0] < t[k]) or (x[-1] > t[-k]):
|
| 1624 |
+
raise ValueError(f'Out of bounds w/ x = {x}.')
|
| 1625 |
+
|
| 1626 |
+
if bc_type == 'periodic':
|
| 1627 |
+
return _make_periodic_spline(x, y, t, k, axis, xp=xp)
|
| 1628 |
+
|
| 1629 |
+
# Here : deriv_l, r = [(nu, value), ...]
|
| 1630 |
+
deriv_l = _convert_string_aliases(deriv_l, y.shape[1:])
|
| 1631 |
+
deriv_l_ords, deriv_l_vals = _process_deriv_spec(deriv_l)
|
| 1632 |
+
nleft = deriv_l_ords.shape[0]
|
| 1633 |
+
|
| 1634 |
+
deriv_r = _convert_string_aliases(deriv_r, y.shape[1:])
|
| 1635 |
+
deriv_r_ords, deriv_r_vals = _process_deriv_spec(deriv_r)
|
| 1636 |
+
nright = deriv_r_ords.shape[0]
|
| 1637 |
+
|
| 1638 |
+
if not all(0 <= i <= k for i in deriv_l_ords):
|
| 1639 |
+
raise ValueError(f"Bad boundary conditions at {x[0]}.")
|
| 1640 |
+
|
| 1641 |
+
if not all(0 <= i <= k for i in deriv_r_ords):
|
| 1642 |
+
raise ValueError(f"Bad boundary conditions at {x[-1]}.")
|
| 1643 |
+
|
| 1644 |
+
# have `n` conditions for `nt` coefficients; need nt-n derivatives
|
| 1645 |
+
n = x.size
|
| 1646 |
+
nt = t.size - k - 1
|
| 1647 |
+
|
| 1648 |
+
if nt - n != nleft + nright:
|
| 1649 |
+
raise ValueError("The number of derivatives at boundaries does not "
|
| 1650 |
+
f"match: expected {nt-n}, got {nleft}+{nright}")
|
| 1651 |
+
|
| 1652 |
+
# bail out if the `y` array is zero-sized
|
| 1653 |
+
if y.size == 0:
|
| 1654 |
+
c = np.zeros((nt,) + y.shape[1:], dtype=float)
|
| 1655 |
+
return BSpline.construct_fast(t, c, k, axis=axis)
|
| 1656 |
+
|
| 1657 |
+
# set up the LHS: the colocation matrix + derivatives at boundaries
|
| 1658 |
+
# NB: ab is in F order for banded LAPACK; _coloc needs C-ordered arrays,
|
| 1659 |
+
# this pass ab.T into _coloc
|
| 1660 |
+
kl = ku = k
|
| 1661 |
+
ab = np.zeros((2*kl + ku + 1, nt), dtype=np.float64, order='F')
|
| 1662 |
+
_dierckx._coloc(x, t, k, ab.T, nleft)
|
| 1663 |
+
if nleft > 0:
|
| 1664 |
+
_handle_lhs_derivatives(t, k, x[0], ab, kl, ku, deriv_l_ords)
|
| 1665 |
+
if nright > 0:
|
| 1666 |
+
_handle_lhs_derivatives(t, k, x[-1], ab, kl, ku, deriv_r_ords,
|
| 1667 |
+
offset=nt-nright)
|
| 1668 |
+
|
| 1669 |
+
# set up the RHS: values to interpolate (+ derivative values, if any)
|
| 1670 |
+
extradim = prod(y.shape[1:])
|
| 1671 |
+
rhs = np.empty((nt, extradim), dtype=y.dtype)
|
| 1672 |
+
if nleft > 0:
|
| 1673 |
+
rhs[:nleft] = deriv_l_vals.reshape(-1, extradim)
|
| 1674 |
+
rhs[nleft:nt - nright] = y.reshape(-1, extradim)
|
| 1675 |
+
if nright > 0:
|
| 1676 |
+
rhs[nt - nright:] = deriv_r_vals.reshape(-1, extradim)
|
| 1677 |
+
|
| 1678 |
+
# solve Ab @ x = rhs; this is the relevant part of linalg.solve_banded
|
| 1679 |
+
if check_finite:
|
| 1680 |
+
ab, rhs = map(np.asarray_chkfinite, (ab, rhs))
|
| 1681 |
+
gbsv, = get_lapack_funcs(('gbsv',), (ab, rhs))
|
| 1682 |
+
lu, piv, c, info = gbsv(kl, ku, ab, rhs,
|
| 1683 |
+
overwrite_ab=True, overwrite_b=True)
|
| 1684 |
+
|
| 1685 |
+
if info > 0:
|
| 1686 |
+
raise LinAlgError("Colocation matrix is singular.")
|
| 1687 |
+
elif info < 0:
|
| 1688 |
+
raise ValueError(f'illegal value in {-info}-th argument of internal gbsv')
|
| 1689 |
+
c = np.ascontiguousarray(c.reshape((nt,) + y.shape[1:]))
|
| 1690 |
+
t, c = xp.asarray(t), xp.asarray(c)
|
| 1691 |
+
return BSpline.construct_fast(t, c, k, axis=axis)
|
| 1692 |
+
|
| 1693 |
+
|
| 1694 |
+
@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
|
| 1695 |
+
def make_lsq_spline(x, y, t, k=3, w=None, axis=0, check_finite=True, *, method="qr"):
|
| 1696 |
+
r"""Create a smoothing B-spline satisfying the Least SQuares (LSQ) criterion.
|
| 1697 |
+
|
| 1698 |
+
The result is a linear combination
|
| 1699 |
+
|
| 1700 |
+
.. math::
|
| 1701 |
+
|
| 1702 |
+
S(x) = \sum_j c_j B_j(x; t)
|
| 1703 |
+
|
| 1704 |
+
of the B-spline basis elements, :math:`B_j(x; t)`, which minimizes
|
| 1705 |
+
|
| 1706 |
+
.. math::
|
| 1707 |
+
|
| 1708 |
+
\sum_{j} \left( w_j \times (S(x_j) - y_j) \right)^2
|
| 1709 |
+
|
| 1710 |
+
Parameters
|
| 1711 |
+
----------
|
| 1712 |
+
x : array_like, shape (m,)
|
| 1713 |
+
Abscissas.
|
| 1714 |
+
y : array_like, shape (m, ...)
|
| 1715 |
+
Ordinates.
|
| 1716 |
+
t : array_like, shape (n + k + 1,).
|
| 1717 |
+
Knots.
|
| 1718 |
+
Knots and data points must satisfy Schoenberg-Whitney conditions.
|
| 1719 |
+
k : int, optional
|
| 1720 |
+
B-spline degree. Default is cubic, ``k = 3``.
|
| 1721 |
+
w : array_like, shape (m,), optional
|
| 1722 |
+
Weights for spline fitting. Must be positive. If ``None``,
|
| 1723 |
+
then weights are all equal.
|
| 1724 |
+
Default is ``None``.
|
| 1725 |
+
axis : int, optional
|
| 1726 |
+
Interpolation axis. Default is zero.
|
| 1727 |
+
check_finite : bool, optional
|
| 1728 |
+
Whether to check that the input arrays contain only finite numbers.
|
| 1729 |
+
Disabling may give a performance gain, but may result in problems
|
| 1730 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
| 1731 |
+
Default is True.
|
| 1732 |
+
method : str, optional
|
| 1733 |
+
Method for solving the linear LSQ problem. Allowed values are "norm-eq"
|
| 1734 |
+
(Explicitly construct and solve the normal system of equations), and
|
| 1735 |
+
"qr" (Use the QR factorization of the design matrix).
|
| 1736 |
+
Default is "qr".
|
| 1737 |
+
|
| 1738 |
+
Returns
|
| 1739 |
+
-------
|
| 1740 |
+
b : `BSpline` object
|
| 1741 |
+
A `BSpline` object of the degree ``k`` with knots ``t``.
|
| 1742 |
+
|
| 1743 |
+
See Also
|
| 1744 |
+
--------
|
| 1745 |
+
BSpline : base class representing the B-spline objects
|
| 1746 |
+
make_interp_spline : a similar factory function for interpolating splines
|
| 1747 |
+
LSQUnivariateSpline : a FITPACK-based spline fitting routine
|
| 1748 |
+
splrep : a FITPACK-based fitting routine
|
| 1749 |
+
|
| 1750 |
+
Notes
|
| 1751 |
+
-----
|
| 1752 |
+
The number of data points must be larger than the spline degree ``k``.
|
| 1753 |
+
|
| 1754 |
+
Knots ``t`` must satisfy the Schoenberg-Whitney conditions,
|
| 1755 |
+
i.e., there must be a subset of data points ``x[j]`` such that
|
| 1756 |
+
``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
|
| 1757 |
+
|
| 1758 |
+
Examples
|
| 1759 |
+
--------
|
| 1760 |
+
Generate some noisy data:
|
| 1761 |
+
|
| 1762 |
+
>>> import numpy as np
|
| 1763 |
+
>>> import matplotlib.pyplot as plt
|
| 1764 |
+
>>> rng = np.random.default_rng()
|
| 1765 |
+
>>> x = np.linspace(-3, 3, 50)
|
| 1766 |
+
>>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
|
| 1767 |
+
|
| 1768 |
+
Now fit a smoothing cubic spline with a pre-defined internal knots.
|
| 1769 |
+
Here we make the knot vector (k+1)-regular by adding boundary knots:
|
| 1770 |
+
|
| 1771 |
+
>>> from scipy.interpolate import make_lsq_spline, BSpline
|
| 1772 |
+
>>> t = [-1, 0, 1]
|
| 1773 |
+
>>> k = 3
|
| 1774 |
+
>>> t = np.r_[(x[0],)*(k+1),
|
| 1775 |
+
... t,
|
| 1776 |
+
... (x[-1],)*(k+1)]
|
| 1777 |
+
>>> spl = make_lsq_spline(x, y, t, k)
|
| 1778 |
+
|
| 1779 |
+
For comparison, we also construct an interpolating spline for the same
|
| 1780 |
+
set of data:
|
| 1781 |
+
|
| 1782 |
+
>>> from scipy.interpolate import make_interp_spline
|
| 1783 |
+
>>> spl_i = make_interp_spline(x, y)
|
| 1784 |
+
|
| 1785 |
+
Plot both:
|
| 1786 |
+
|
| 1787 |
+
>>> xs = np.linspace(-3, 3, 100)
|
| 1788 |
+
>>> plt.plot(x, y, 'ro', ms=5)
|
| 1789 |
+
>>> plt.plot(xs, spl(xs), 'g-', lw=3, label='LSQ spline')
|
| 1790 |
+
>>> plt.plot(xs, spl_i(xs), 'b-', lw=3, alpha=0.7, label='interp spline')
|
| 1791 |
+
>>> plt.legend(loc='best')
|
| 1792 |
+
>>> plt.show()
|
| 1793 |
+
|
| 1794 |
+
**NaN handling**: If the input arrays contain ``nan`` values, the result is
|
| 1795 |
+
not useful since the underlying spline fitting routines cannot deal with
|
| 1796 |
+
``nan``. A workaround is to use zero weights for not-a-number data points:
|
| 1797 |
+
|
| 1798 |
+
>>> y[8] = np.nan
|
| 1799 |
+
>>> w = np.isnan(y)
|
| 1800 |
+
>>> y[w] = 0.
|
| 1801 |
+
>>> tck = make_lsq_spline(x, y, t, w=~w)
|
| 1802 |
+
|
| 1803 |
+
Notice the need to replace a ``nan`` by a numerical value (precise value
|
| 1804 |
+
does not matter as long as the corresponding weight is zero.)
|
| 1805 |
+
|
| 1806 |
+
"""
|
| 1807 |
+
xp = array_namespace(x, y, t, w)
|
| 1808 |
+
|
| 1809 |
+
x = _as_float_array(x, check_finite)
|
| 1810 |
+
y = _as_float_array(y, check_finite)
|
| 1811 |
+
t = _as_float_array(t, check_finite)
|
| 1812 |
+
if w is not None:
|
| 1813 |
+
w = _as_float_array(w, check_finite)
|
| 1814 |
+
else:
|
| 1815 |
+
w = np.ones_like(x)
|
| 1816 |
+
k = operator.index(k)
|
| 1817 |
+
|
| 1818 |
+
axis = normalize_axis_index(axis, y.ndim)
|
| 1819 |
+
|
| 1820 |
+
y = np.moveaxis(y, axis, 0) # now internally interp axis is zero
|
| 1821 |
+
if not y.flags.c_contiguous:
|
| 1822 |
+
# C routines in _dierckx currently require C contiguity
|
| 1823 |
+
y = y.copy(order='C')
|
| 1824 |
+
|
| 1825 |
+
if x.ndim != 1:
|
| 1826 |
+
raise ValueError("Expect x to be a 1-D sequence.")
|
| 1827 |
+
if x.shape[0] < k+1:
|
| 1828 |
+
raise ValueError("Need more x points.")
|
| 1829 |
+
if k < 0:
|
| 1830 |
+
raise ValueError("Expect non-negative k.")
|
| 1831 |
+
if t.ndim != 1 or np.any(t[1:] - t[:-1] < 0):
|
| 1832 |
+
raise ValueError("Expect t to be a 1D strictly increasing sequence.")
|
| 1833 |
+
if x.size != y.shape[0]:
|
| 1834 |
+
raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
|
| 1835 |
+
if k > 0 and np.any((x < t[k]) | (x > t[-k])):
|
| 1836 |
+
raise ValueError(f'Out of bounds w/ x = {x}.')
|
| 1837 |
+
if x.size != w.size:
|
| 1838 |
+
raise ValueError(f'Shapes of x {x.shape} and w {w.shape} are incompatible')
|
| 1839 |
+
if method == "norm-eq" and np.any(x[1:] - x[:-1] <= 0):
|
| 1840 |
+
raise ValueError("Expect x to be a 1D strictly increasing sequence.")
|
| 1841 |
+
if method == "qr" and any(x[1:] - x[:-1] < 0):
|
| 1842 |
+
raise ValueError("Expect x to be a 1D non-decreasing sequence.")
|
| 1843 |
+
|
| 1844 |
+
# number of coefficients
|
| 1845 |
+
n = t.size - k - 1
|
| 1846 |
+
|
| 1847 |
+
# complex y: view as float, preserve the length
|
| 1848 |
+
was_complex = y.dtype.kind == 'c'
|
| 1849 |
+
yy = y.view(float)
|
| 1850 |
+
if was_complex and y.ndim == 1:
|
| 1851 |
+
yy = yy.reshape(y.shape[0], 2)
|
| 1852 |
+
|
| 1853 |
+
# multiple r.h.s
|
| 1854 |
+
extradim = prod(yy.shape[1:])
|
| 1855 |
+
yy = yy.reshape(-1, extradim)
|
| 1856 |
+
|
| 1857 |
+
# complex y: view as float, preserve the length
|
| 1858 |
+
was_complex = y.dtype.kind == 'c'
|
| 1859 |
+
yy = y.view(float)
|
| 1860 |
+
if was_complex and y.ndim == 1:
|
| 1861 |
+
yy = yy.reshape(y.shape[0], 2)
|
| 1862 |
+
|
| 1863 |
+
# multiple r.h.s
|
| 1864 |
+
extradim = prod(yy.shape[1:])
|
| 1865 |
+
yy = yy.reshape(-1, extradim)
|
| 1866 |
+
|
| 1867 |
+
if method == "norm-eq":
|
| 1868 |
+
# construct A.T @ A and rhs with A the colocation matrix, and
|
| 1869 |
+
# rhs = A.T @ y for solving the LSQ problem ``A.T @ A @ c = A.T @ y``
|
| 1870 |
+
lower = True
|
| 1871 |
+
ab = np.zeros((k+1, n), dtype=np.float64, order='F')
|
| 1872 |
+
rhs = np.zeros((n, extradim), dtype=np.float64)
|
| 1873 |
+
_dierckx._norm_eq_lsq(x, t, k,
|
| 1874 |
+
yy,
|
| 1875 |
+
w,
|
| 1876 |
+
ab.T, rhs)
|
| 1877 |
+
|
| 1878 |
+
# undo complex -> float and flattening the trailing dims
|
| 1879 |
+
if was_complex:
|
| 1880 |
+
rhs = rhs.view(complex)
|
| 1881 |
+
|
| 1882 |
+
rhs = rhs.reshape((n,) + y.shape[1:])
|
| 1883 |
+
|
| 1884 |
+
# have observation matrix & rhs, can solve the LSQ problem
|
| 1885 |
+
cho_decomp = cholesky_banded(ab, overwrite_ab=True, lower=lower,
|
| 1886 |
+
check_finite=check_finite)
|
| 1887 |
+
m = rhs.shape[0]
|
| 1888 |
+
c = cho_solve_banded((cho_decomp, lower), rhs.reshape(m, -1), overwrite_b=True,
|
| 1889 |
+
check_finite=check_finite).reshape(rhs.shape)
|
| 1890 |
+
elif method == "qr":
|
| 1891 |
+
_, _, c, _, _ = _lsq_solve_qr(x, yy, t, k, w)
|
| 1892 |
+
|
| 1893 |
+
if was_complex:
|
| 1894 |
+
c = c.view(complex)
|
| 1895 |
+
|
| 1896 |
+
else:
|
| 1897 |
+
raise ValueError(f"Unknown {method =}.")
|
| 1898 |
+
|
| 1899 |
+
|
| 1900 |
+
# restore the shape of `c` for both single and multiple r.h.s.
|
| 1901 |
+
c = c.reshape((n,) + y.shape[1:])
|
| 1902 |
+
c = np.ascontiguousarray(c)
|
| 1903 |
+
t, c = xp.asarray(t), xp.asarray(c)
|
| 1904 |
+
return BSpline.construct_fast(t, c, k, axis=axis)
|
| 1905 |
+
|
| 1906 |
+
|
| 1907 |
+
######################
|
| 1908 |
+
# LSQ spline helpers #
|
| 1909 |
+
######################
|
| 1910 |
+
|
| 1911 |
+
def _lsq_solve_qr_for_root_rati_periodic(x, y, t, k, w):
|
| 1912 |
+
"""Solve for the LSQ spline coeffs given x, y and knots.
|
| 1913 |
+
|
| 1914 |
+
`y` is always 2D: for 1D data, the shape is ``(m, 1)``.
|
| 1915 |
+
`w` is always 1D: one weight value per `x` value.
|
| 1916 |
+
|
| 1917 |
+
"""
|
| 1918 |
+
y_w = y * w[:, None]
|
| 1919 |
+
# Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L221-L238
|
| 1920 |
+
R, H1, H2, offset, nc = _dierckx.data_matrix_periodic(x, t, k, w, False)
|
| 1921 |
+
# Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L239-L314
|
| 1922 |
+
A1, A2, Z, p, _ = _dierckx.qr_reduce_periodic(
|
| 1923 |
+
R, H1, H2, offset, nc, y_w, k,
|
| 1924 |
+
len(t), True
|
| 1925 |
+
) # modifies arguments in-place
|
| 1926 |
+
# Ref: https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpbacp.f
|
| 1927 |
+
c, residuals, _ = _dierckx.fpbacp(A1, A2, Z, k, k, x, y, t, w)
|
| 1928 |
+
return R, A1, A2, Z, y_w, c, p, residuals
|
| 1929 |
+
|
| 1930 |
+
|
| 1931 |
+
def _lsq_solve_qr(x, y, t, k, w, periodic=False):
|
| 1932 |
+
"""Solve for the LSQ spline coeffs given x, y and knots.
|
| 1933 |
+
|
| 1934 |
+
`y` is always 2D: for 1D data, the shape is ``(m, 1)``.
|
| 1935 |
+
`w` is always 1D: one weight value per `x` value.
|
| 1936 |
+
|
| 1937 |
+
"""
|
| 1938 |
+
y_w = y * w[:, None]
|
| 1939 |
+
if not periodic:
|
| 1940 |
+
A, offset, nc = _dierckx.data_matrix(x, t, k, w)
|
| 1941 |
+
_dierckx.qr_reduce(A, offset, nc, y_w) # modifies arguments in-place
|
| 1942 |
+
c, residuals, fp = _dierckx.fpback(A, nc, x, y, t, k, w, y_w)
|
| 1943 |
+
return A, y_w, c, fp, residuals
|
| 1944 |
+
else:
|
| 1945 |
+
# Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L221-L238
|
| 1946 |
+
R, H1, H2, offset, nc = _dierckx.data_matrix_periodic(x, t, k, w, False)
|
| 1947 |
+
# Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L239-L314
|
| 1948 |
+
A1, A2, Z, fp = _dierckx.qr_reduce_periodic(
|
| 1949 |
+
R, H1, H2, offset, nc, y_w, k,
|
| 1950 |
+
len(t), False) # modifies arguments in-place
|
| 1951 |
+
# Ref: https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpbacp.f
|
| 1952 |
+
c, residuals, _ = _dierckx.fpbacp(A1, A2, Z, k, k, x, y, t, w)
|
| 1953 |
+
return R, y_w, c, fp, residuals
|
| 1954 |
+
|
| 1955 |
+
|
| 1956 |
+
|
| 1957 |
+
|
| 1958 |
+
#############################
|
| 1959 |
+
# Smoothing spline helpers #
|
| 1960 |
+
#############################
|
| 1961 |
+
|
| 1962 |
+
def _compute_optimal_gcv_parameter(X, wE, y, w):
|
| 1963 |
+
"""
|
| 1964 |
+
Returns an optimal regularization parameter from the GCV criteria [1].
|
| 1965 |
+
|
| 1966 |
+
Parameters
|
| 1967 |
+
----------
|
| 1968 |
+
X : array, shape (5, n)
|
| 1969 |
+
5 bands of the design matrix ``X`` stored in LAPACK banded storage.
|
| 1970 |
+
wE : array, shape (5, n)
|
| 1971 |
+
5 bands of the penalty matrix :math:`W^{-1} E` stored in LAPACK banded
|
| 1972 |
+
storage.
|
| 1973 |
+
y : array, shape (n,)
|
| 1974 |
+
Ordinates.
|
| 1975 |
+
w : array, shape (n,)
|
| 1976 |
+
Vector of weights.
|
| 1977 |
+
|
| 1978 |
+
Returns
|
| 1979 |
+
-------
|
| 1980 |
+
lam : float
|
| 1981 |
+
An optimal from the GCV criteria point of view regularization
|
| 1982 |
+
parameter.
|
| 1983 |
+
|
| 1984 |
+
Notes
|
| 1985 |
+
-----
|
| 1986 |
+
No checks are performed.
|
| 1987 |
+
|
| 1988 |
+
References
|
| 1989 |
+
----------
|
| 1990 |
+
.. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
|
| 1991 |
+
for observational data, Philadelphia, Pennsylvania: Society for
|
| 1992 |
+
Industrial and Applied Mathematics, 1990, pp. 45-65.
|
| 1993 |
+
:doi:`10.1137/1.9781611970128`
|
| 1994 |
+
|
| 1995 |
+
"""
|
| 1996 |
+
|
| 1997 |
+
def compute_banded_symmetric_XT_W_Y(X, w, Y):
|
| 1998 |
+
"""
|
| 1999 |
+
Assuming that the product :math:`X^T W Y` is symmetric and both ``X``
|
| 2000 |
+
and ``Y`` are 5-banded, compute the unique bands of the product.
|
| 2001 |
+
|
| 2002 |
+
Parameters
|
| 2003 |
+
----------
|
| 2004 |
+
X : array, shape (5, n)
|
| 2005 |
+
5 bands of the matrix ``X`` stored in LAPACK banded storage.
|
| 2006 |
+
w : array, shape (n,)
|
| 2007 |
+
Array of weights
|
| 2008 |
+
Y : array, shape (5, n)
|
| 2009 |
+
5 bands of the matrix ``Y`` stored in LAPACK banded storage.
|
| 2010 |
+
|
| 2011 |
+
Returns
|
| 2012 |
+
-------
|
| 2013 |
+
res : array, shape (4, n)
|
| 2014 |
+
The result of the product :math:`X^T Y` stored in the banded way.
|
| 2015 |
+
|
| 2016 |
+
Notes
|
| 2017 |
+
-----
|
| 2018 |
+
As far as the matrices ``X`` and ``Y`` are 5-banded, their product
|
| 2019 |
+
:math:`X^T W Y` is 7-banded. It is also symmetric, so we can store only
|
| 2020 |
+
unique diagonals.
|
| 2021 |
+
|
| 2022 |
+
"""
|
| 2023 |
+
# compute W Y
|
| 2024 |
+
W_Y = np.copy(Y)
|
| 2025 |
+
|
| 2026 |
+
W_Y[2] *= w
|
| 2027 |
+
for i in range(2):
|
| 2028 |
+
W_Y[i, 2 - i:] *= w[:-2 + i]
|
| 2029 |
+
W_Y[3 + i, :-1 - i] *= w[1 + i:]
|
| 2030 |
+
|
| 2031 |
+
n = X.shape[1]
|
| 2032 |
+
res = np.zeros((4, n))
|
| 2033 |
+
for i in range(n):
|
| 2034 |
+
for j in range(min(n-i, 4)):
|
| 2035 |
+
res[-j-1, i + j] = sum(X[j:, i] * W_Y[:5-j, i + j])
|
| 2036 |
+
return res
|
| 2037 |
+
|
| 2038 |
+
def compute_b_inv(A):
|
| 2039 |
+
"""
|
| 2040 |
+
Inverse 3 central bands of matrix :math:`A=U^T D^{-1} U` assuming that
|
| 2041 |
+
``U`` is a unit upper triangular banded matrix using an algorithm
|
| 2042 |
+
proposed in [1].
|
| 2043 |
+
|
| 2044 |
+
Parameters
|
| 2045 |
+
----------
|
| 2046 |
+
A : array, shape (4, n)
|
| 2047 |
+
Matrix to inverse, stored in LAPACK banded storage.
|
| 2048 |
+
|
| 2049 |
+
Returns
|
| 2050 |
+
-------
|
| 2051 |
+
B : array, shape (4, n)
|
| 2052 |
+
3 unique bands of the symmetric matrix that is an inverse to ``A``.
|
| 2053 |
+
The first row is filled with zeros.
|
| 2054 |
+
|
| 2055 |
+
Notes
|
| 2056 |
+
-----
|
| 2057 |
+
The algorithm is based on the cholesky decomposition and, therefore,
|
| 2058 |
+
in case matrix ``A`` is close to not positive defined, the function
|
| 2059 |
+
raises LinalgError.
|
| 2060 |
+
|
| 2061 |
+
Both matrices ``A`` and ``B`` are stored in LAPACK banded storage.
|
| 2062 |
+
|
| 2063 |
+
References
|
| 2064 |
+
----------
|
| 2065 |
+
.. [1] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
|
| 2066 |
+
spline functions," Numerische Mathematik, vol. 47, no. 1,
|
| 2067 |
+
pp. 99-106, 1985.
|
| 2068 |
+
:doi:`10.1007/BF01389878`
|
| 2069 |
+
|
| 2070 |
+
"""
|
| 2071 |
+
|
| 2072 |
+
def find_b_inv_elem(i, j, U, D, B):
|
| 2073 |
+
rng = min(3, n - i - 1)
|
| 2074 |
+
rng_sum = 0.
|
| 2075 |
+
if j == 0:
|
| 2076 |
+
# use 2-nd formula from [1]
|
| 2077 |
+
for k in range(1, rng + 1):
|
| 2078 |
+
rng_sum -= U[-k - 1, i + k] * B[-k - 1, i + k]
|
| 2079 |
+
rng_sum += D[i]
|
| 2080 |
+
B[-1, i] = rng_sum
|
| 2081 |
+
else:
|
| 2082 |
+
# use 1-st formula from [1]
|
| 2083 |
+
for k in range(1, rng + 1):
|
| 2084 |
+
diag = abs(k - j)
|
| 2085 |
+
ind = i + min(k, j)
|
| 2086 |
+
rng_sum -= U[-k - 1, i + k] * B[-diag - 1, ind + diag]
|
| 2087 |
+
B[-j - 1, i + j] = rng_sum
|
| 2088 |
+
|
| 2089 |
+
U = cholesky_banded(A)
|
| 2090 |
+
for i in range(2, 5):
|
| 2091 |
+
U[-i, i-1:] /= U[-1, :-i+1]
|
| 2092 |
+
D = 1. / (U[-1])**2
|
| 2093 |
+
U[-1] /= U[-1]
|
| 2094 |
+
|
| 2095 |
+
n = U.shape[1]
|
| 2096 |
+
|
| 2097 |
+
B = np.zeros(shape=(4, n))
|
| 2098 |
+
for i in range(n - 1, -1, -1):
|
| 2099 |
+
for j in range(min(3, n - i - 1), -1, -1):
|
| 2100 |
+
find_b_inv_elem(i, j, U, D, B)
|
| 2101 |
+
# the first row contains garbage and should be removed
|
| 2102 |
+
B[0] = [0.] * n
|
| 2103 |
+
return B
|
| 2104 |
+
|
| 2105 |
+
def _gcv(lam, X, XtWX, wE, XtE, y):
|
| 2106 |
+
r"""
|
| 2107 |
+
Computes the generalized cross-validation criteria [1].
|
| 2108 |
+
|
| 2109 |
+
Parameters
|
| 2110 |
+
----------
|
| 2111 |
+
lam : float, (:math:`\lambda \geq 0`)
|
| 2112 |
+
Regularization parameter.
|
| 2113 |
+
X : array, shape (5, n)
|
| 2114 |
+
Matrix is stored in LAPACK banded storage.
|
| 2115 |
+
XtWX : array, shape (4, n)
|
| 2116 |
+
Product :math:`X^T W X` stored in LAPACK banded storage.
|
| 2117 |
+
wE : array, shape (5, n)
|
| 2118 |
+
Matrix :math:`W^{-1} E` stored in LAPACK banded storage.
|
| 2119 |
+
XtE : array, shape (4, n)
|
| 2120 |
+
Product :math:`X^T E` stored in LAPACK banded storage.
|
| 2121 |
+
|
| 2122 |
+
Returns
|
| 2123 |
+
-------
|
| 2124 |
+
res : float
|
| 2125 |
+
Value of the GCV criteria with the regularization parameter
|
| 2126 |
+
:math:`\lambda`.
|
| 2127 |
+
|
| 2128 |
+
Notes
|
| 2129 |
+
-----
|
| 2130 |
+
Criteria is computed from the formula (1.3.2) [3]:
|
| 2131 |
+
|
| 2132 |
+
.. math:
|
| 2133 |
+
|
| 2134 |
+
GCV(\lambda) = \dfrac{1}{n} \sum\limits_{k = 1}^{n} \dfrac{ \left(
|
| 2135 |
+
y_k - f_{\lambda}(x_k) \right)^2}{\left( 1 - \Tr{A}/n\right)^2}$.
|
| 2136 |
+
The criteria is discussed in section 1.3 [3].
|
| 2137 |
+
|
| 2138 |
+
The numerator is computed using (2.2.4) [3] and the denominator is
|
| 2139 |
+
computed using an algorithm from [2] (see in the ``compute_b_inv``
|
| 2140 |
+
function).
|
| 2141 |
+
|
| 2142 |
+
References
|
| 2143 |
+
----------
|
| 2144 |
+
.. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
|
| 2145 |
+
for observational data, Philadelphia, Pennsylvania: Society for
|
| 2146 |
+
Industrial and Applied Mathematics, 1990, pp. 45-65.
|
| 2147 |
+
:doi:`10.1137/1.9781611970128`
|
| 2148 |
+
.. [2] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
|
| 2149 |
+
spline functions," Numerische Mathematik, vol. 47, no. 1,
|
| 2150 |
+
pp. 99-106, 1985.
|
| 2151 |
+
:doi:`10.1007/BF01389878`
|
| 2152 |
+
.. [3] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
|
| 2153 |
+
BSc thesis, 2022. Might be available (in Russian)
|
| 2154 |
+
`here <https://www.hse.ru/ba/am/students/diplomas/620910604>`_
|
| 2155 |
+
|
| 2156 |
+
"""
|
| 2157 |
+
# Compute the numerator from (2.2.4) [3]
|
| 2158 |
+
n = X.shape[1]
|
| 2159 |
+
c = solve_banded((2, 2), X + lam * wE, y)
|
| 2160 |
+
res = np.zeros(n)
|
| 2161 |
+
# compute ``W^{-1} E c`` with respect to banded-storage of ``E``
|
| 2162 |
+
tmp = wE * c
|
| 2163 |
+
for i in range(n):
|
| 2164 |
+
for j in range(max(0, i - n + 3), min(5, i + 3)):
|
| 2165 |
+
res[i] += tmp[j, i + 2 - j]
|
| 2166 |
+
numer = np.linalg.norm(lam * res)**2 / n
|
| 2167 |
+
|
| 2168 |
+
# compute the denominator
|
| 2169 |
+
lhs = XtWX + lam * XtE
|
| 2170 |
+
try:
|
| 2171 |
+
b_banded = compute_b_inv(lhs)
|
| 2172 |
+
# compute the trace of the product b_banded @ XtX
|
| 2173 |
+
tr = b_banded * XtWX
|
| 2174 |
+
tr[:-1] *= 2
|
| 2175 |
+
# find the denominator
|
| 2176 |
+
denom = (1 - sum(sum(tr)) / n)**2
|
| 2177 |
+
except LinAlgError:
|
| 2178 |
+
# cholesky decomposition cannot be performed
|
| 2179 |
+
raise ValueError('Seems like the problem is ill-posed')
|
| 2180 |
+
|
| 2181 |
+
res = numer / denom
|
| 2182 |
+
|
| 2183 |
+
return res
|
| 2184 |
+
|
| 2185 |
+
n = X.shape[1]
|
| 2186 |
+
|
| 2187 |
+
XtWX = compute_banded_symmetric_XT_W_Y(X, w, X)
|
| 2188 |
+
XtE = compute_banded_symmetric_XT_W_Y(X, w, wE)
|
| 2189 |
+
|
| 2190 |
+
if y.ndim == 1:
|
| 2191 |
+
gcv_est = minimize_scalar(
|
| 2192 |
+
_gcv, bounds=(0, n), method='Bounded', args=(X, XtWX, wE, XtE, y)
|
| 2193 |
+
)
|
| 2194 |
+
if gcv_est.success:
|
| 2195 |
+
return gcv_est.x
|
| 2196 |
+
raise ValueError(f"Unable to find minimum of the GCV "
|
| 2197 |
+
f"function: {gcv_est.message}")
|
| 2198 |
+
elif y.ndim == 2:
|
| 2199 |
+
gcv_est = np.empty(y.shape[1])
|
| 2200 |
+
for i in range(y.shape[1]):
|
| 2201 |
+
est = minimize_scalar(
|
| 2202 |
+
_gcv, bounds=(0, n), method='Bounded', args=(X, XtWX, wE, XtE, y[:, i])
|
| 2203 |
+
)
|
| 2204 |
+
if est.success:
|
| 2205 |
+
gcv_est[i] = est.x
|
| 2206 |
+
else:
|
| 2207 |
+
raise ValueError(f"Unable to find minimum of the GCV "
|
| 2208 |
+
f"function: {gcv_est.message}")
|
| 2209 |
+
return gcv_est
|
| 2210 |
+
else:
|
| 2211 |
+
# trailing dims must have been flattened already.
|
| 2212 |
+
raise RuntimeError("Internal error. Please report it to scipy developers.")
|
| 2213 |
+
|
| 2214 |
+
|
| 2215 |
+
def _coeff_of_divided_diff(x):
|
| 2216 |
+
"""
|
| 2217 |
+
Returns the coefficients of the divided difference.
|
| 2218 |
+
|
| 2219 |
+
Parameters
|
| 2220 |
+
----------
|
| 2221 |
+
x : array, shape (n,)
|
| 2222 |
+
Array which is used for the computation of divided difference.
|
| 2223 |
+
|
| 2224 |
+
Returns
|
| 2225 |
+
-------
|
| 2226 |
+
res : array_like, shape (n,)
|
| 2227 |
+
Coefficients of the divided difference.
|
| 2228 |
+
|
| 2229 |
+
Notes
|
| 2230 |
+
-----
|
| 2231 |
+
Vector ``x`` should have unique elements, otherwise an error division by
|
| 2232 |
+
zero might be raised.
|
| 2233 |
+
|
| 2234 |
+
No checks are performed.
|
| 2235 |
+
|
| 2236 |
+
"""
|
| 2237 |
+
n = x.shape[0]
|
| 2238 |
+
res = np.zeros(n)
|
| 2239 |
+
for i in range(n):
|
| 2240 |
+
pp = 1.
|
| 2241 |
+
for k in range(n):
|
| 2242 |
+
if k != i:
|
| 2243 |
+
pp *= (x[i] - x[k])
|
| 2244 |
+
res[i] = 1. / pp
|
| 2245 |
+
return res
|
| 2246 |
+
|
| 2247 |
+
|
| 2248 |
+
@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
|
| 2249 |
+
def make_smoothing_spline(x, y, w=None, lam=None, *, axis=0):
|
| 2250 |
+
r"""
|
| 2251 |
+
Create a smoothing B-spline satisfying the Generalized Cross Validation (GCV) criterion.
|
| 2252 |
+
|
| 2253 |
+
Compute the (coefficients of) smoothing cubic spline function using
|
| 2254 |
+
``lam`` to control the tradeoff between the amount of smoothness of the
|
| 2255 |
+
curve and its proximity to the data. In case ``lam`` is None, using the
|
| 2256 |
+
GCV criteria [1] to find it.
|
| 2257 |
+
|
| 2258 |
+
A smoothing spline is found as a solution to the regularized weighted
|
| 2259 |
+
linear regression problem:
|
| 2260 |
+
|
| 2261 |
+
.. math::
|
| 2262 |
+
|
| 2263 |
+
\sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2 +
|
| 2264 |
+
\lambda\int\limits_{x_1}^{x_n} (f^{(2)}(u))^2 d u
|
| 2265 |
+
|
| 2266 |
+
where :math:`f` is a spline function, :math:`w` is a vector of weights and
|
| 2267 |
+
:math:`\lambda` is a regularization parameter.
|
| 2268 |
+
|
| 2269 |
+
If ``lam`` is None, we use the GCV criteria to find an optimal
|
| 2270 |
+
regularization parameter, otherwise we solve the regularized weighted
|
| 2271 |
+
linear regression problem with given parameter. The parameter controls
|
| 2272 |
+
the tradeoff in the following way: the larger the parameter becomes, the
|
| 2273 |
+
smoother the function gets.
|
| 2274 |
+
|
| 2275 |
+
Parameters
|
| 2276 |
+
----------
|
| 2277 |
+
x : array_like, shape (n,)
|
| 2278 |
+
Abscissas. `n` must be at least 5.
|
| 2279 |
+
y : array_like, shape (n, ...)
|
| 2280 |
+
Ordinates. `n` must be at least 5.
|
| 2281 |
+
w : array_like, shape (n,), optional
|
| 2282 |
+
Vector of weights. Default is ``np.ones_like(x)``.
|
| 2283 |
+
lam : float, (:math:`\lambda \geq 0`), optional
|
| 2284 |
+
Regularization parameter. If ``lam`` is None, then it is found from
|
| 2285 |
+
the GCV criteria. Default is None.
|
| 2286 |
+
axis : int, optional
|
| 2287 |
+
The data axis. Default is zero.
|
| 2288 |
+
The assumption is that ``y.shape[axis] == n``, and all other axes of ``y``
|
| 2289 |
+
are batching axes.
|
| 2290 |
+
|
| 2291 |
+
Returns
|
| 2292 |
+
-------
|
| 2293 |
+
func : `BSpline` object
|
| 2294 |
+
An object representing a spline in the B-spline basis
|
| 2295 |
+
as a solution of the problem of smoothing splines using
|
| 2296 |
+
the GCV criteria [1] in case ``lam`` is None, otherwise using the
|
| 2297 |
+
given parameter ``lam``.
|
| 2298 |
+
|
| 2299 |
+
Notes
|
| 2300 |
+
-----
|
| 2301 |
+
This algorithm is a clean room reimplementation of the algorithm
|
| 2302 |
+
introduced by Woltring in FORTRAN [2]. The original version cannot be used
|
| 2303 |
+
in SciPy source code because of the license issues. The details of the
|
| 2304 |
+
reimplementation are discussed here (available only in Russian) [4].
|
| 2305 |
+
|
| 2306 |
+
If the vector of weights ``w`` is None, we assume that all the points are
|
| 2307 |
+
equal in terms of weights, and vector of weights is vector of ones.
|
| 2308 |
+
|
| 2309 |
+
Note that in weighted residual sum of squares, weights are not squared:
|
| 2310 |
+
:math:`\sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2` while in
|
| 2311 |
+
``splrep`` the sum is built from the squared weights.
|
| 2312 |
+
|
| 2313 |
+
In cases when the initial problem is ill-posed (for example, the product
|
| 2314 |
+
:math:`X^T W X` where :math:`X` is a design matrix is not a positive
|
| 2315 |
+
defined matrix) a ValueError is raised.
|
| 2316 |
+
|
| 2317 |
+
References
|
| 2318 |
+
----------
|
| 2319 |
+
.. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models for
|
| 2320 |
+
observational data, Philadelphia, Pennsylvania: Society for Industrial
|
| 2321 |
+
and Applied Mathematics, 1990, pp. 45-65.
|
| 2322 |
+
:doi:`10.1137/1.9781611970128`
|
| 2323 |
+
.. [2] H. J. Woltring, A Fortran package for generalized, cross-validatory
|
| 2324 |
+
spline smoothing and differentiation, Advances in Engineering
|
| 2325 |
+
Software, vol. 8, no. 2, pp. 104-113, 1986.
|
| 2326 |
+
:doi:`10.1016/0141-1195(86)90098-7`
|
| 2327 |
+
.. [3] T. Hastie, J. Friedman, and R. Tisbshirani, "Smoothing Splines" in
|
| 2328 |
+
The elements of Statistical Learning: Data Mining, Inference, and
|
| 2329 |
+
prediction, New York: Springer, 2017, pp. 241-249.
|
| 2330 |
+
:doi:`10.1007/978-0-387-84858-7`
|
| 2331 |
+
.. [4] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
|
| 2332 |
+
BSc thesis, 2022.
|
| 2333 |
+
`<https://www.hse.ru/ba/am/students/diplomas/620910604>`_ (in
|
| 2334 |
+
Russian)
|
| 2335 |
+
|
| 2336 |
+
Examples
|
| 2337 |
+
--------
|
| 2338 |
+
Generate some noisy data
|
| 2339 |
+
|
| 2340 |
+
>>> import numpy as np
|
| 2341 |
+
>>> np.random.seed(1234)
|
| 2342 |
+
>>> n = 200
|
| 2343 |
+
>>> def func(x):
|
| 2344 |
+
... return x**3 + x**2 * np.sin(4 * x)
|
| 2345 |
+
>>> x = np.sort(np.random.random_sample(n) * 4 - 2)
|
| 2346 |
+
>>> y = func(x) + np.random.normal(scale=1.5, size=n)
|
| 2347 |
+
|
| 2348 |
+
Make a smoothing spline function
|
| 2349 |
+
|
| 2350 |
+
>>> from scipy.interpolate import make_smoothing_spline
|
| 2351 |
+
>>> spl = make_smoothing_spline(x, y)
|
| 2352 |
+
|
| 2353 |
+
Plot both
|
| 2354 |
+
|
| 2355 |
+
>>> import matplotlib.pyplot as plt
|
| 2356 |
+
>>> grid = np.linspace(x[0], x[-1], 400)
|
| 2357 |
+
>>> plt.plot(x, y, '.')
|
| 2358 |
+
>>> plt.plot(grid, spl(grid), label='Spline')
|
| 2359 |
+
>>> plt.plot(grid, func(grid), label='Original function')
|
| 2360 |
+
>>> plt.legend(loc='best')
|
| 2361 |
+
>>> plt.show()
|
| 2362 |
+
|
| 2363 |
+
""" # noqa:E501
|
| 2364 |
+
xp = array_namespace(x, y)
|
| 2365 |
+
|
| 2366 |
+
x = np.ascontiguousarray(x, dtype=float)
|
| 2367 |
+
y = np.ascontiguousarray(y, dtype=float)
|
| 2368 |
+
|
| 2369 |
+
if any(x[1:] - x[:-1] <= 0):
|
| 2370 |
+
raise ValueError('``x`` should be an ascending array')
|
| 2371 |
+
|
| 2372 |
+
if x.ndim != 1 or x.shape[0] != y.shape[axis]:
|
| 2373 |
+
raise ValueError(f'``x`` should be 1D and {x.shape = } == {y.shape = }')
|
| 2374 |
+
|
| 2375 |
+
if w is None:
|
| 2376 |
+
w = np.ones(len(x))
|
| 2377 |
+
else:
|
| 2378 |
+
w = np.ascontiguousarray(w)
|
| 2379 |
+
if any(w <= 0):
|
| 2380 |
+
raise ValueError('Invalid vector of weights')
|
| 2381 |
+
|
| 2382 |
+
t = np.r_[[x[0]] * 3, x, [x[-1]] * 3]
|
| 2383 |
+
n = x.shape[0]
|
| 2384 |
+
|
| 2385 |
+
if n <= 4:
|
| 2386 |
+
raise ValueError('``x`` and ``y`` length must be at least 5')
|
| 2387 |
+
|
| 2388 |
+
# Internals assume that the data axis is the zero-th axis
|
| 2389 |
+
axis = normalize_axis_index(axis, y.ndim)
|
| 2390 |
+
y = np.moveaxis(y, axis, 0)
|
| 2391 |
+
|
| 2392 |
+
# flatten the trailing axes of y to simplify further manipulations
|
| 2393 |
+
y_shape1 = y.shape[1:]
|
| 2394 |
+
if y_shape1 != ():
|
| 2395 |
+
y = y.reshape((n, -1))
|
| 2396 |
+
|
| 2397 |
+
# It is known that the solution to the stated minimization problem exists
|
| 2398 |
+
# and is a natural cubic spline with vector of knots equal to the unique
|
| 2399 |
+
# elements of ``x`` [3], so we will solve the problem in the basis of
|
| 2400 |
+
# natural splines.
|
| 2401 |
+
|
| 2402 |
+
# create design matrix in the B-spline basis
|
| 2403 |
+
X_bspl = BSpline.design_matrix(x, t, 3)
|
| 2404 |
+
# move from B-spline basis to the basis of natural splines using equations
|
| 2405 |
+
# (2.1.7) [4]
|
| 2406 |
+
# central elements
|
| 2407 |
+
X = np.zeros((5, n))
|
| 2408 |
+
for i in range(1, 4):
|
| 2409 |
+
X[i, 2: -2] = X_bspl[i: i - 4, 3: -3][np.diag_indices(n - 4)]
|
| 2410 |
+
|
| 2411 |
+
# first elements
|
| 2412 |
+
X[1, 1] = X_bspl[0, 0]
|
| 2413 |
+
X[2, :2] = ((x[2] + x[1] - 2 * x[0]) * X_bspl[0, 0],
|
| 2414 |
+
X_bspl[1, 1] + X_bspl[1, 2])
|
| 2415 |
+
X[3, :2] = ((x[2] - x[0]) * X_bspl[1, 1], X_bspl[2, 2])
|
| 2416 |
+
|
| 2417 |
+
# last elements
|
| 2418 |
+
X[1, -2:] = (X_bspl[-3, -3], (x[-1] - x[-3]) * X_bspl[-2, -2])
|
| 2419 |
+
X[2, -2:] = (X_bspl[-2, -3] + X_bspl[-2, -2],
|
| 2420 |
+
(2 * x[-1] - x[-2] - x[-3]) * X_bspl[-1, -1])
|
| 2421 |
+
X[3, -2] = X_bspl[-1, -1]
|
| 2422 |
+
|
| 2423 |
+
# create penalty matrix and divide it by vector of weights: W^{-1} E
|
| 2424 |
+
wE = np.zeros((5, n))
|
| 2425 |
+
wE[2:, 0] = _coeff_of_divided_diff(x[:3]) / w[:3]
|
| 2426 |
+
wE[1:, 1] = _coeff_of_divided_diff(x[:4]) / w[:4]
|
| 2427 |
+
for j in range(2, n - 2):
|
| 2428 |
+
wE[:, j] = (x[j+2] - x[j-2]) * _coeff_of_divided_diff(x[j-2:j+3])\
|
| 2429 |
+
/ w[j-2: j+3]
|
| 2430 |
+
|
| 2431 |
+
wE[:-1, -2] = -_coeff_of_divided_diff(x[-4:]) / w[-4:]
|
| 2432 |
+
wE[:-2, -1] = _coeff_of_divided_diff(x[-3:]) / w[-3:]
|
| 2433 |
+
wE *= 6
|
| 2434 |
+
|
| 2435 |
+
if lam is None:
|
| 2436 |
+
lam = _compute_optimal_gcv_parameter(X, wE, y, w)
|
| 2437 |
+
elif lam < 0.:
|
| 2438 |
+
raise ValueError('Regularization parameter should be non-negative')
|
| 2439 |
+
|
| 2440 |
+
# solve the initial problem in the basis of natural splines
|
| 2441 |
+
if np.ndim(lam) == 0:
|
| 2442 |
+
c = solve_banded((2, 2), X + lam * wE, y)
|
| 2443 |
+
elif np.ndim(lam) == 1:
|
| 2444 |
+
# XXX: solve_banded does not suppport batched `ab` matrices; loop manually
|
| 2445 |
+
c = np.empty((n, lam.shape[0]))
|
| 2446 |
+
for i in range(lam.shape[0]):
|
| 2447 |
+
c[:, i] = solve_banded((2, 2), X + lam[i] * wE, y[:, i])
|
| 2448 |
+
else:
|
| 2449 |
+
# this should not happen, ever
|
| 2450 |
+
raise RuntimeError("Internal error, please report it to SciPy developers.")
|
| 2451 |
+
c = c.reshape((c.shape[0], *y_shape1))
|
| 2452 |
+
|
| 2453 |
+
# hack: these are c[0], c[1] etc, shape-compatible with np.r_ below
|
| 2454 |
+
c0, c1 = c[0:1, ...], c[1:2, ...] # c[0], c[1]
|
| 2455 |
+
cm0, cm1 = c[-1:-2:-1, ...], c[-2:-3:-1, ...] # c[-1], c[-2]
|
| 2456 |
+
|
| 2457 |
+
# move back to B-spline basis using equations (2.2.10) [4]
|
| 2458 |
+
c_ = np.r_[c0 * (t[5] + t[4] - 2 * t[3]) + c1,
|
| 2459 |
+
c0 * (t[5] - t[3]) + c1,
|
| 2460 |
+
c[1: -1, ...],
|
| 2461 |
+
cm0 * (t[-4] - t[-6]) + cm1,
|
| 2462 |
+
cm0 * (2 * t[-4] - t[-5] - t[-6]) + cm1]
|
| 2463 |
+
|
| 2464 |
+
t, c_ = xp.asarray(t), xp.asarray(c_)
|
| 2465 |
+
return BSpline.construct_fast(t, c_, 3, axis=axis)
|
| 2466 |
+
|
| 2467 |
+
|
| 2468 |
+
########################
|
| 2469 |
+
# FITPACK look-alikes #
|
| 2470 |
+
########################
|
| 2471 |
+
|
| 2472 |
+
def fpcheck(x, t, k, periodic=False):
|
| 2473 |
+
"""Check consistency of data vector `x` and knot vector `t`.
|
| 2474 |
+
|
| 2475 |
+
Parameters
|
| 2476 |
+
----------
|
| 2477 |
+
x : array_like, shape (m,)
|
| 2478 |
+
1D sorted array of data points.
|
| 2479 |
+
t : array_like, shape (n,)
|
| 2480 |
+
1D non-decreasing knot vector.
|
| 2481 |
+
k : int
|
| 2482 |
+
Degree of the spline.
|
| 2483 |
+
periodic : bool, optional
|
| 2484 |
+
Whether the spline is periodic. Default is False.
|
| 2485 |
+
|
| 2486 |
+
Raises
|
| 2487 |
+
------
|
| 2488 |
+
ValueError
|
| 2489 |
+
If the configuration of `x`, `t`, and `k` violates any required condition.
|
| 2490 |
+
"""
|
| 2491 |
+
# This routine is a unified clone of the FITPACK Fortran routines `fpchec.f`
|
| 2492 |
+
# and `fpchep.f`:
|
| 2493 |
+
# - https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f
|
| 2494 |
+
# - https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchep.f
|
| 2495 |
+
#
|
| 2496 |
+
# These routines verify the number and position of the knots t(j), j=1,...,n,
|
| 2497 |
+
# of a spline of degree k, relative to the number and distribution of data points
|
| 2498 |
+
# x(i), i=1,...,m. If all of the following conditions are fulfilled,
|
| 2499 |
+
# validation passes.
|
| 2500 |
+
#
|
| 2501 |
+
# For non-periodic splines:
|
| 2502 |
+
# 1) k+1 <= n-k-1 <= m
|
| 2503 |
+
# 2) t(1) <= t(2) <= ... <= t(k+1)
|
| 2504 |
+
# t(n-k) <= t(n-k+1) <= ... <= t(n)
|
| 2505 |
+
# 3) t(k+1) < t(k+2) < ... < t(n-k)
|
| 2506 |
+
# 4) t(k+1) <= x(i) <= t(n-k)
|
| 2507 |
+
# 5) Schoenberg-Whitney conditions hold: there exists a subset y(j) such that
|
| 2508 |
+
# t(j) < y(j) < t(j+k+1), for j = 1, ..., n-k-1
|
| 2509 |
+
#
|
| 2510 |
+
# For periodic splines:
|
| 2511 |
+
# 1) k+1 <= n-k-1 <= m + k - 1
|
| 2512 |
+
# 2) Same boundary knot monotonicity as above
|
| 2513 |
+
# 3) Same strict interior knot increase as above
|
| 2514 |
+
# 4) t(k+1) <= x(i) <= t(n-k)
|
| 2515 |
+
# 5) Schoenberg-Whitney conditions must hold for *some periodic shift*
|
| 2516 |
+
# of the data sequence; i.e. wrapped data points x(i) must satisfy
|
| 2517 |
+
# t(j) < y(j) < t(j+k+1), j = k+1, ..., n-k-1
|
| 2518 |
+
x = np.asarray(x)
|
| 2519 |
+
t = np.asarray(t)
|
| 2520 |
+
|
| 2521 |
+
if x.ndim != 1 or t.ndim != 1:
|
| 2522 |
+
raise ValueError(f"Expect `x` and `t` be 1D sequences. Got {x = } and {t = }")
|
| 2523 |
+
|
| 2524 |
+
m = x.shape[0]
|
| 2525 |
+
n = t.shape[0]
|
| 2526 |
+
nk1 = n - k - 1
|
| 2527 |
+
|
| 2528 |
+
# check condition no 1
|
| 2529 |
+
if periodic:
|
| 2530 |
+
# c 1) k+1 <= nk1 <= m+k-1
|
| 2531 |
+
if not (k + 1 <= nk1 <= m + k - 1):
|
| 2532 |
+
raise ValueError(f"Need k+1 <= n-k-1 <= m+k-1. Got {m = }, {n = }, {k = }")
|
| 2533 |
+
else:
|
| 2534 |
+
# c 1) k+1 <= n-k-1 <= m
|
| 2535 |
+
if not (k + 1 <= nk1 <= m):
|
| 2536 |
+
raise ValueError(f"Need k+1 <= n-k-1 <= m. Got {m = }, {n = } and {k = }.")
|
| 2537 |
+
|
| 2538 |
+
# check condition no 2
|
| 2539 |
+
# c 2) t(1) <= t(2) <= ... <= t(k+1)
|
| 2540 |
+
# c t(n-k) <= t(n-k+1) <= ... <= t(n)
|
| 2541 |
+
if (t[:k+1] > t[1:k+2]).any():
|
| 2542 |
+
raise ValueError(f"First k knots must be ordered; got {t = }.")
|
| 2543 |
+
|
| 2544 |
+
if (t[nk1:] < t[nk1-1:-1]).any():
|
| 2545 |
+
raise ValueError(f"Last k knots must be ordered; got {t = }.")
|
| 2546 |
+
|
| 2547 |
+
# c check condition no 3
|
| 2548 |
+
# c 3) t(k+1) < t(k+2) < ... < t(n-k)
|
| 2549 |
+
if (t[k+1:n-k] <= t[k:n-k-1]).any():
|
| 2550 |
+
raise ValueError(f"Internal knots must be distinct. Got {t = }.")
|
| 2551 |
+
|
| 2552 |
+
# c check condition no 4
|
| 2553 |
+
# c 4) t(k+1) <= x(i) <= t(n-k)
|
| 2554 |
+
# NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow.
|
| 2555 |
+
if (x[0] < t[k]) or (x[-1] > t[n-k-1]):
|
| 2556 |
+
raise ValueError(f"Out of bounds: {x = } and {t = }.")
|
| 2557 |
+
|
| 2558 |
+
# c check condition no 5
|
| 2559 |
+
# c 5) the conditions specified by Schoenberg and Whitney must hold
|
| 2560 |
+
# c for at least one subset of data points y(j) such that
|
| 2561 |
+
# c t(j) < y(j) < t(j+k+1)
|
| 2562 |
+
# c
|
| 2563 |
+
# c For non-periodic splines:
|
| 2564 |
+
# c j = 1, 2, ..., n-k-1 (i.e., j in [1, n-k-1])
|
| 2565 |
+
# c The data points must lie strictly inside some B-spline supports.
|
| 2566 |
+
# c
|
| 2567 |
+
# c For periodic splines:
|
| 2568 |
+
# c j = k+1, ..., n-k-1
|
| 2569 |
+
# c The condition must hold for a wrapped subset of the data points,
|
| 2570 |
+
# c i.e., there exists a cyclic shift of the data such that
|
| 2571 |
+
# c t(j) < x(i) < t(j+k+1)
|
| 2572 |
+
# c holds for all j in that range. The test must account for the
|
| 2573 |
+
# c periodic domain length: per = t(n-k) - t(k+1), and wrap around x(i)
|
| 2574 |
+
# c as x(i) + per if needed.
|
| 2575 |
+
mesg = f"Schoenberg-Whitney condition is violated with {t = } and {x =}."
|
| 2576 |
+
|
| 2577 |
+
if periodic:
|
| 2578 |
+
per = t[n - k - 1] - t[k]
|
| 2579 |
+
m1 = m - 1
|
| 2580 |
+
for shift in range(1, m):
|
| 2581 |
+
for j in range(k, nk1):
|
| 2582 |
+
tj = t[j]
|
| 2583 |
+
tl = t[j + k + 1]
|
| 2584 |
+
found = False
|
| 2585 |
+
for i in range(shift, shift + m1 + 1):
|
| 2586 |
+
idx = i if i < m else i - m
|
| 2587 |
+
xi = x[idx] + (0 if i < m else per)
|
| 2588 |
+
if tj < xi < tl:
|
| 2589 |
+
found = True
|
| 2590 |
+
break
|
| 2591 |
+
if not found:
|
| 2592 |
+
break
|
| 2593 |
+
else:
|
| 2594 |
+
return
|
| 2595 |
+
raise ValueError(mesg)
|
| 2596 |
+
else:
|
| 2597 |
+
if (x[0] >= t[k+1]) or (x[-1] <= t[n-k-2]):
|
| 2598 |
+
raise ValueError(mesg)
|
| 2599 |
+
|
| 2600 |
+
m = x.shape[0]
|
| 2601 |
+
l = k+1
|
| 2602 |
+
nk3 = n - k - 3
|
| 2603 |
+
if nk3 < 2:
|
| 2604 |
+
return
|
| 2605 |
+
for j in range(1, nk3+1):
|
| 2606 |
+
tj = t[j]
|
| 2607 |
+
l += 1
|
| 2608 |
+
tl = t[l]
|
| 2609 |
+
i = np.argmax(x > tj)
|
| 2610 |
+
if i >= m-1:
|
| 2611 |
+
raise ValueError(mesg)
|
| 2612 |
+
if x[i] >= tl:
|
| 2613 |
+
raise ValueError(mesg)
|
| 2614 |
+
return
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_cubic.py
ADDED
|
@@ -0,0 +1,1029 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interpolation algorithms using piecewise cubic polynomials."""
|
| 2 |
+
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from scipy.linalg import solve, solve_banded
|
| 8 |
+
from scipy._lib._array_api import array_namespace, xp_size, xp_capabilities
|
| 9 |
+
from scipy._lib.array_api_compat import numpy as np_compat
|
| 10 |
+
|
| 11 |
+
from . import PPoly
|
| 12 |
+
from ._polyint import _isscalar
|
| 13 |
+
|
| 14 |
+
__all__ = ["CubicHermiteSpline", "PchipInterpolator", "pchip_interpolate",
|
| 15 |
+
"Akima1DInterpolator", "CubicSpline"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def prepare_input(x, y, axis, dydx=None, xp=None):
|
| 19 |
+
"""Prepare input for cubic spline interpolators.
|
| 20 |
+
|
| 21 |
+
All data are converted to numpy arrays and checked for correctness.
|
| 22 |
+
Axes equal to `axis` of arrays `y` and `dydx` are moved to be the 0th
|
| 23 |
+
axis. The value of `axis` is converted to lie in
|
| 24 |
+
[0, number of dimensions of `y`).
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
x, y = map(xp.asarray, (x, y))
|
| 28 |
+
if xp.isdtype(x.dtype, "complex floating"):
|
| 29 |
+
raise ValueError("`x` must contain real values.")
|
| 30 |
+
x = xp.astype(x, xp.float64)
|
| 31 |
+
|
| 32 |
+
if xp.isdtype(y.dtype, "complex floating"):
|
| 33 |
+
dtype = xp.complex128
|
| 34 |
+
else:
|
| 35 |
+
dtype = xp.float64
|
| 36 |
+
|
| 37 |
+
if dydx is not None:
|
| 38 |
+
dydx = xp.asarray(dydx)
|
| 39 |
+
if y.shape != dydx.shape:
|
| 40 |
+
raise ValueError("The shapes of `y` and `dydx` must be identical.")
|
| 41 |
+
if xp.isdtype(dydx.dtype, "complex floating"):
|
| 42 |
+
dtype = xp.complex128
|
| 43 |
+
dydx = xp.astype(dydx, dtype, copy=False)
|
| 44 |
+
|
| 45 |
+
y = xp.astype(y, dtype, copy=False)
|
| 46 |
+
axis = axis % y.ndim
|
| 47 |
+
if x.ndim != 1:
|
| 48 |
+
raise ValueError("`x` must be 1-dimensional.")
|
| 49 |
+
if x.shape[0] < 2:
|
| 50 |
+
raise ValueError("`x` must contain at least 2 elements.")
|
| 51 |
+
if x.shape[0] != y.shape[axis]:
|
| 52 |
+
raise ValueError(f"The length of `y` along `axis`={axis} doesn't "
|
| 53 |
+
"match the length of `x`")
|
| 54 |
+
|
| 55 |
+
if not xp.all(xp.isfinite(x)):
|
| 56 |
+
raise ValueError("`x` must contain only finite values.")
|
| 57 |
+
if not xp.all(xp.isfinite(y)):
|
| 58 |
+
raise ValueError("`y` must contain only finite values.")
|
| 59 |
+
|
| 60 |
+
if dydx is not None and not xp.all(xp.isfinite(dydx)):
|
| 61 |
+
raise ValueError("`dydx` must contain only finite values.")
|
| 62 |
+
|
| 63 |
+
dx = xp.diff(x)
|
| 64 |
+
if xp.any(dx <= 0):
|
| 65 |
+
raise ValueError("`x` must be strictly increasing sequence.")
|
| 66 |
+
|
| 67 |
+
y = xp.moveaxis(y, axis, 0)
|
| 68 |
+
if dydx is not None:
|
| 69 |
+
dydx = xp.moveaxis(dydx, axis, 0)
|
| 70 |
+
|
| 71 |
+
return x, dx, y, axis, dydx
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@xp_capabilities(
|
| 75 |
+
cpu_only=True, jax_jit=False,
|
| 76 |
+
skip_backends=[
|
| 77 |
+
("dask.array",
|
| 78 |
+
"https://github.com/data-apis/array-api-extra/issues/488")
|
| 79 |
+
]
|
| 80 |
+
)
|
| 81 |
+
class CubicHermiteSpline(PPoly):
|
| 82 |
+
"""Piecewise cubic interpolator to fit values and first derivatives (C1 smooth).
|
| 83 |
+
|
| 84 |
+
The result is represented as a `PPoly` instance.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
x : array_like, shape (n,)
|
| 89 |
+
1-D array containing values of the independent variable.
|
| 90 |
+
Values must be real, finite and in strictly increasing order.
|
| 91 |
+
y : array_like
|
| 92 |
+
Array containing values of the dependent variable. It can have
|
| 93 |
+
arbitrary number of dimensions, but the length along ``axis``
|
| 94 |
+
(see below) must match the length of ``x``. Values must be finite.
|
| 95 |
+
dydx : array_like
|
| 96 |
+
Array containing derivatives of the dependent variable. It can have
|
| 97 |
+
arbitrary number of dimensions, but the length along ``axis``
|
| 98 |
+
(see below) must match the length of ``x``. Values must be finite.
|
| 99 |
+
axis : int, optional
|
| 100 |
+
Axis along which `y` is assumed to be varying. Meaning that for
|
| 101 |
+
``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
|
| 102 |
+
Default is 0.
|
| 103 |
+
extrapolate : {bool, 'periodic', None}, optional
|
| 104 |
+
If bool, determines whether to extrapolate to out-of-bounds points
|
| 105 |
+
based on first and last intervals, or to return NaNs. If 'periodic',
|
| 106 |
+
periodic extrapolation is used. If None (default), it is set to True.
|
| 107 |
+
|
| 108 |
+
Attributes
|
| 109 |
+
----------
|
| 110 |
+
x : ndarray, shape (n,)
|
| 111 |
+
Breakpoints. The same ``x`` which was passed to the constructor.
|
| 112 |
+
c : ndarray, shape (4, n-1, ...)
|
| 113 |
+
Coefficients of the polynomials on each segment. The trailing
|
| 114 |
+
dimensions match the dimensions of `y`, excluding ``axis``.
|
| 115 |
+
For example, if `y` is 1-D, then ``c[k, i]`` is a coefficient for
|
| 116 |
+
``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
|
| 117 |
+
axis : int
|
| 118 |
+
Interpolation axis. The same axis which was passed to the
|
| 119 |
+
constructor.
|
| 120 |
+
|
| 121 |
+
Methods
|
| 122 |
+
-------
|
| 123 |
+
__call__
|
| 124 |
+
derivative
|
| 125 |
+
antiderivative
|
| 126 |
+
integrate
|
| 127 |
+
solve
|
| 128 |
+
roots
|
| 129 |
+
|
| 130 |
+
See Also
|
| 131 |
+
--------
|
| 132 |
+
Akima1DInterpolator : Akima 1D interpolator.
|
| 133 |
+
PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
|
| 134 |
+
CubicSpline : Cubic spline data interpolator.
|
| 135 |
+
PPoly : Piecewise polynomial in terms of coefficients and breakpoints
|
| 136 |
+
|
| 137 |
+
Notes
|
| 138 |
+
-----
|
| 139 |
+
If you want to create a higher-order spline matching higher-order
|
| 140 |
+
derivatives, use `BPoly.from_derivatives`.
|
| 141 |
+
|
| 142 |
+
References
|
| 143 |
+
----------
|
| 144 |
+
.. [1] `Cubic Hermite spline
|
| 145 |
+
<https://en.wikipedia.org/wiki/Cubic_Hermite_spline>`_
|
| 146 |
+
on Wikipedia.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
def __init__(self, x, y, dydx, axis=0, extrapolate=None):
|
| 150 |
+
xp = array_namespace(x, y, dydx)
|
| 151 |
+
|
| 152 |
+
if extrapolate is None:
|
| 153 |
+
extrapolate = True
|
| 154 |
+
|
| 155 |
+
x, dx, y, axis, dydx = prepare_input(x, y, axis, dydx, xp=xp)
|
| 156 |
+
|
| 157 |
+
dxr = xp.reshape(dx, (dx.shape[0], ) + (1, ) * (y.ndim - 1))
|
| 158 |
+
slope = xp.diff(y, axis=0) / dxr
|
| 159 |
+
t = (dydx[:-1, ...] + dydx[1:, ...] - 2 * slope) / dxr
|
| 160 |
+
|
| 161 |
+
c = xp.stack((
|
| 162 |
+
t / dxr,
|
| 163 |
+
(slope - dydx[:-1, ...]) / dxr - t,
|
| 164 |
+
dydx[:-1, ...],
|
| 165 |
+
y[:-1, ...]
|
| 166 |
+
))
|
| 167 |
+
|
| 168 |
+
super().__init__(c, x, extrapolate=extrapolate)
|
| 169 |
+
self.axis = axis
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@xp_capabilities(
|
| 173 |
+
cpu_only=True, jax_jit=False,
|
| 174 |
+
skip_backends=[
|
| 175 |
+
("dask.array",
|
| 176 |
+
"https://github.com/data-apis/array-api-extra/issues/488")
|
| 177 |
+
]
|
| 178 |
+
)
|
| 179 |
+
class PchipInterpolator(CubicHermiteSpline):
|
| 180 |
+
r"""PCHIP shape-preserving interpolator (C1 smooth).
|
| 181 |
+
|
| 182 |
+
``x`` and ``y`` are arrays of values used to approximate some function f,
|
| 183 |
+
with ``y = f(x)``. The interpolant uses monotonic cubic splines
|
| 184 |
+
to find the value of new points. (PCHIP stands for Piecewise Cubic
|
| 185 |
+
Hermite Interpolating Polynomial).
|
| 186 |
+
|
| 187 |
+
Parameters
|
| 188 |
+
----------
|
| 189 |
+
x : ndarray, shape (npoints, )
|
| 190 |
+
A 1-D array of monotonically increasing real values. ``x`` cannot
|
| 191 |
+
include duplicate values (otherwise f is overspecified)
|
| 192 |
+
y : ndarray, shape (..., npoints, ...)
|
| 193 |
+
An N-D array of real values. ``y``'s length along the interpolation
|
| 194 |
+
axis must be equal to the length of ``x``. Use the ``axis``
|
| 195 |
+
parameter to select the interpolation axis.
|
| 196 |
+
axis : int, optional
|
| 197 |
+
Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
|
| 198 |
+
to ``axis=0``.
|
| 199 |
+
extrapolate : bool, optional
|
| 200 |
+
Whether to extrapolate to out-of-bounds points based on first
|
| 201 |
+
and last intervals, or to return NaNs.
|
| 202 |
+
|
| 203 |
+
Methods
|
| 204 |
+
-------
|
| 205 |
+
__call__
|
| 206 |
+
derivative
|
| 207 |
+
antiderivative
|
| 208 |
+
integrate
|
| 209 |
+
solve
|
| 210 |
+
roots
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
See Also
|
| 214 |
+
--------
|
| 215 |
+
CubicHermiteSpline : Piecewise-cubic interpolator.
|
| 216 |
+
Akima1DInterpolator : Akima 1D interpolator.
|
| 217 |
+
CubicSpline : Cubic spline data interpolator.
|
| 218 |
+
PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
|
| 219 |
+
|
| 220 |
+
Notes
|
| 221 |
+
-----
|
| 222 |
+
The interpolator preserves monotonicity in the interpolation data and does
|
| 223 |
+
not overshoot if the data is not smooth.
|
| 224 |
+
|
| 225 |
+
The first derivatives are guaranteed to be continuous, but the second
|
| 226 |
+
derivatives may jump at :math:`x_k`.
|
| 227 |
+
|
| 228 |
+
Determines the derivatives at the points :math:`x_k`, :math:`f'_k`,
|
| 229 |
+
by using PCHIP algorithm [1]_.
|
| 230 |
+
|
| 231 |
+
Let :math:`h_k = x_{k+1} - x_k`, and :math:`d_k = (y_{k+1} - y_k) / h_k`
|
| 232 |
+
are the slopes at internal points :math:`x_k`.
|
| 233 |
+
If the signs of :math:`d_k` and :math:`d_{k-1}` are different or either of
|
| 234 |
+
them equals zero, then :math:`f'_k = 0`. Otherwise, it is given by the
|
| 235 |
+
weighted harmonic mean
|
| 236 |
+
|
| 237 |
+
.. math::
|
| 238 |
+
|
| 239 |
+
\frac{w_1 + w_2}{f'_k} = \frac{w_1}{d_{k-1}} + \frac{w_2}{d_k}
|
| 240 |
+
|
| 241 |
+
where :math:`w_1 = 2 h_k + h_{k-1}` and :math:`w_2 = h_k + 2 h_{k-1}`.
|
| 242 |
+
|
| 243 |
+
The end slopes are set using a one-sided scheme [2]_.
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
References
|
| 247 |
+
----------
|
| 248 |
+
.. [1] F. N. Fritsch and J. Butland,
|
| 249 |
+
A method for constructing local
|
| 250 |
+
monotone piecewise cubic interpolants,
|
| 251 |
+
SIAM J. Sci. Comput., 5(2), 300-304 (1984).
|
| 252 |
+
:doi:`10.1137/0905021`.
|
| 253 |
+
.. [2] C. Moler, Numerical Computing with Matlab, 2004.
|
| 254 |
+
:doi:`10.1137/1.9780898717952`
|
| 255 |
+
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
# PchipInterpolator is not generic in scipy-stubs
|
| 259 |
+
__class_getitem__ = None
|
| 260 |
+
|
| 261 |
+
def __init__(self, x, y, axis=0, extrapolate=None):
|
| 262 |
+
xp = array_namespace(x, y)
|
| 263 |
+
x, _, y, axis, _ = prepare_input(x, y, axis, xp=xp)
|
| 264 |
+
if xp.isdtype(y.dtype, "complex floating"):
|
| 265 |
+
msg = ("`PchipInterpolator` only works with real values for `y`. "
|
| 266 |
+
"If you are trying to use the real components of the passed array, "
|
| 267 |
+
"use `np.real` on the array before passing to `PchipInterpolator`.")
|
| 268 |
+
raise ValueError(msg)
|
| 269 |
+
xv = xp.reshape(x, (x.shape[0],) + (1,)*(y.ndim-1))
|
| 270 |
+
dk = self._find_derivatives(xv, y, xp=xp)
|
| 271 |
+
super().__init__(x, y, dk, axis=0, extrapolate=extrapolate)
|
| 272 |
+
self.axis = axis
|
| 273 |
+
|
| 274 |
+
@staticmethod
|
| 275 |
+
def _edge_case(h0, h1, m0, m1, xp):
|
| 276 |
+
# one-sided three-point estimate for the derivative
|
| 277 |
+
d = ((2*h0 + h1)*m0 - h0*m1) / (h0 + h1)
|
| 278 |
+
|
| 279 |
+
# try to preserve shape
|
| 280 |
+
mask = xp.sign(d) != xp.sign(m0)
|
| 281 |
+
mask2 = (xp.sign(m0) != xp.sign(m1)) & (xp.abs(d) > 3.*xp.abs(m0))
|
| 282 |
+
mmm = (~mask) & mask2
|
| 283 |
+
|
| 284 |
+
d[mask] = 0.
|
| 285 |
+
d[mmm] = 3.*m0[mmm]
|
| 286 |
+
|
| 287 |
+
return d
|
| 288 |
+
|
| 289 |
+
@staticmethod
|
| 290 |
+
def _find_derivatives(x, y, xp):
|
| 291 |
+
# Determine the derivatives at the points y_k, d_k, by using
|
| 292 |
+
# PCHIP algorithm is:
|
| 293 |
+
# We choose the derivatives at the point x_k by
|
| 294 |
+
# Let m_k be the slope of the kth segment (between k and k+1)
|
| 295 |
+
# If m_k=0 or m_{k-1}=0 or sgn(m_k) != sgn(m_{k-1}) then d_k == 0
|
| 296 |
+
# else use weighted harmonic mean:
|
| 297 |
+
# w_1 = 2h_k + h_{k-1}, w_2 = h_k + 2h_{k-1}
|
| 298 |
+
# 1/d_k = 1/(w_1 + w_2)*(w_1 / m_k + w_2 / m_{k-1})
|
| 299 |
+
# where h_k is the spacing between x_k and x_{k+1}
|
| 300 |
+
y_shape = y.shape
|
| 301 |
+
if y.ndim == 1:
|
| 302 |
+
# So that _edge_case doesn't end up assigning to scalars
|
| 303 |
+
x = x[:, None]
|
| 304 |
+
y = y[:, None]
|
| 305 |
+
|
| 306 |
+
hk = x[1:] - x[:-1]
|
| 307 |
+
mk = (y[1:] - y[:-1]) / hk
|
| 308 |
+
|
| 309 |
+
if y.shape[0] == 2:
|
| 310 |
+
# edge case: only have two points, use linear interpolation
|
| 311 |
+
dk = xp.zeros_like(y)
|
| 312 |
+
dk[0] = mk
|
| 313 |
+
dk[1] = mk
|
| 314 |
+
return xp.reshape(dk, y_shape)
|
| 315 |
+
|
| 316 |
+
smk = xp.sign(mk)
|
| 317 |
+
condition = (smk[1:] != smk[:-1]) | (mk[1:] == 0) | (mk[:-1] == 0)
|
| 318 |
+
|
| 319 |
+
w1 = 2*hk[1:] + hk[:-1]
|
| 320 |
+
w2 = hk[1:] + 2*hk[:-1]
|
| 321 |
+
|
| 322 |
+
# values where division by zero occurs will be excluded
|
| 323 |
+
# by 'condition' afterwards
|
| 324 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
| 325 |
+
whmean = (w1/mk[:-1] + w2/mk[1:]) / (w1 + w2)
|
| 326 |
+
|
| 327 |
+
dk = np.zeros_like(y)
|
| 328 |
+
dk[1:-1][condition] = 0.0
|
| 329 |
+
dk[1:-1][~condition] = 1.0 / whmean[~condition]
|
| 330 |
+
|
| 331 |
+
# special case endpoints, as suggested in
|
| 332 |
+
# Cleve Moler, Numerical Computing with MATLAB, Chap 3.6 (pchiptx.m)
|
| 333 |
+
dk[0] = PchipInterpolator._edge_case(hk[0], hk[1], mk[0], mk[1], xp=xp)
|
| 334 |
+
dk[-1] = PchipInterpolator._edge_case(hk[-1], hk[-2], mk[-1], mk[-2], xp=xp)
|
| 335 |
+
|
| 336 |
+
return xp.reshape(dk, y_shape)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def pchip_interpolate(xi, yi, x, der=0, axis=0):
|
| 340 |
+
"""
|
| 341 |
+
Convenience function for pchip interpolation.
|
| 342 |
+
|
| 343 |
+
xi and yi are arrays of values used to approximate some function f,
|
| 344 |
+
with ``yi = f(xi)``. The interpolant uses monotonic cubic splines
|
| 345 |
+
to find the value of new points x and the derivatives there.
|
| 346 |
+
|
| 347 |
+
See `scipy.interpolate.PchipInterpolator` for details.
|
| 348 |
+
|
| 349 |
+
Parameters
|
| 350 |
+
----------
|
| 351 |
+
xi : array_like
|
| 352 |
+
A sorted list of x-coordinates, of length N.
|
| 353 |
+
yi : array_like
|
| 354 |
+
A 1-D array of real values. `yi`'s length along the interpolation
|
| 355 |
+
axis must be equal to the length of `xi`. If N-D array, use axis
|
| 356 |
+
parameter to select correct axis.
|
| 357 |
+
x : scalar or array_like
|
| 358 |
+
Of length M.
|
| 359 |
+
der : int or list, optional
|
| 360 |
+
Derivatives to extract. The 0th derivative can be included to
|
| 361 |
+
return the function value.
|
| 362 |
+
axis : int, optional
|
| 363 |
+
Axis in the yi array corresponding to the x-coordinate values.
|
| 364 |
+
|
| 365 |
+
Returns
|
| 366 |
+
-------
|
| 367 |
+
y : scalar or array_like
|
| 368 |
+
The result, of length R or length M or M by R.
|
| 369 |
+
|
| 370 |
+
See Also
|
| 371 |
+
--------
|
| 372 |
+
PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
|
| 373 |
+
|
| 374 |
+
Examples
|
| 375 |
+
--------
|
| 376 |
+
We can interpolate 2D observed data using pchip interpolation:
|
| 377 |
+
|
| 378 |
+
>>> import numpy as np
|
| 379 |
+
>>> import matplotlib.pyplot as plt
|
| 380 |
+
>>> from scipy.interpolate import pchip_interpolate
|
| 381 |
+
>>> x_observed = np.linspace(0.0, 10.0, 11)
|
| 382 |
+
>>> y_observed = np.sin(x_observed)
|
| 383 |
+
>>> x = np.linspace(min(x_observed), max(x_observed), num=100)
|
| 384 |
+
>>> y = pchip_interpolate(x_observed, y_observed, x)
|
| 385 |
+
>>> plt.plot(x_observed, y_observed, "o", label="observation")
|
| 386 |
+
>>> plt.plot(x, y, label="pchip interpolation")
|
| 387 |
+
>>> plt.legend()
|
| 388 |
+
>>> plt.show()
|
| 389 |
+
|
| 390 |
+
"""
|
| 391 |
+
P = PchipInterpolator(xi, yi, axis=axis)
|
| 392 |
+
|
| 393 |
+
if der == 0:
|
| 394 |
+
return P(x)
|
| 395 |
+
elif _isscalar(der):
|
| 396 |
+
return P.derivative(der)(x)
|
| 397 |
+
else:
|
| 398 |
+
return [P.derivative(nu)(x) for nu in der]
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
@xp_capabilities(cpu_only=True, xfail_backends=[
|
| 402 |
+
("dask.array", "lacks nd fancy indexing"),
|
| 403 |
+
("jax.numpy", "immutable arrays"),
|
| 404 |
+
("array_api_strict", "fancy indexing __setitem__"),
|
| 405 |
+
])
|
| 406 |
+
class Akima1DInterpolator(CubicHermiteSpline):
|
| 407 |
+
r"""Akima "visually pleasing" interpolator (C1 smooth).
|
| 408 |
+
|
| 409 |
+
Fit piecewise cubic polynomials, given vectors x and y. The interpolation
|
| 410 |
+
method by Akima uses a continuously differentiable sub-spline built from
|
| 411 |
+
piecewise cubic polynomials. The resultant curve passes through the given
|
| 412 |
+
data points and will appear smooth and natural.
|
| 413 |
+
|
| 414 |
+
Parameters
|
| 415 |
+
----------
|
| 416 |
+
x : ndarray, shape (npoints, )
|
| 417 |
+
1-D array of monotonically increasing real values.
|
| 418 |
+
y : ndarray, shape (..., npoints, ...)
|
| 419 |
+
N-D array of real values. The length of ``y`` along the interpolation axis
|
| 420 |
+
must be equal to the length of ``x``. Use the ``axis`` parameter to
|
| 421 |
+
select the interpolation axis.
|
| 422 |
+
axis : int, optional
|
| 423 |
+
Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
|
| 424 |
+
to ``axis=0``.
|
| 425 |
+
method : {'akima', 'makima'}, optional
|
| 426 |
+
If ``"makima"``, use the modified Akima interpolation [2]_.
|
| 427 |
+
Defaults to ``"akima"``, use the Akima interpolation [1]_.
|
| 428 |
+
|
| 429 |
+
.. versionadded:: 1.13.0
|
| 430 |
+
|
| 431 |
+
extrapolate : {bool, None}, optional
|
| 432 |
+
If bool, determines whether to extrapolate to out-of-bounds points
|
| 433 |
+
based on first and last intervals, or to return NaNs. If None,
|
| 434 |
+
``extrapolate`` is set to False.
|
| 435 |
+
|
| 436 |
+
Methods
|
| 437 |
+
-------
|
| 438 |
+
__call__
|
| 439 |
+
derivative
|
| 440 |
+
antiderivative
|
| 441 |
+
integrate
|
| 442 |
+
solve
|
| 443 |
+
roots
|
| 444 |
+
|
| 445 |
+
See Also
|
| 446 |
+
--------
|
| 447 |
+
PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
|
| 448 |
+
CubicSpline : Cubic spline data interpolator.
|
| 449 |
+
PPoly : Piecewise polynomial in terms of coefficients and breakpoints
|
| 450 |
+
|
| 451 |
+
Notes
|
| 452 |
+
-----
|
| 453 |
+
.. versionadded:: 0.14
|
| 454 |
+
|
| 455 |
+
Use only for precise data, as the fitted curve passes through the given
|
| 456 |
+
points exactly. This routine is useful for plotting a pleasingly smooth
|
| 457 |
+
curve through a few given points for purposes of plotting.
|
| 458 |
+
|
| 459 |
+
Let :math:`\delta_i = (y_{i+1} - y_i) / (x_{i+1} - x_i)` be the slopes of
|
| 460 |
+
the interval :math:`\left[x_i, x_{i+1}\right)`. Akima's derivative at
|
| 461 |
+
:math:`x_i` is defined as:
|
| 462 |
+
|
| 463 |
+
.. math::
|
| 464 |
+
|
| 465 |
+
d_i = \frac{w_1}{w_1 + w_2}\delta_{i-1} + \frac{w_2}{w_1 + w_2}\delta_i
|
| 466 |
+
|
| 467 |
+
In the Akima interpolation [1]_ (``method="akima"``), the weights are:
|
| 468 |
+
|
| 469 |
+
.. math::
|
| 470 |
+
|
| 471 |
+
\begin{aligned}
|
| 472 |
+
w_1 &= |\delta_{i+1} - \delta_i| \\
|
| 473 |
+
w_2 &= |\delta_{i-1} - \delta_{i-2}|
|
| 474 |
+
\end{aligned}
|
| 475 |
+
|
| 476 |
+
In the modified Akima interpolation [2]_ (``method="makima"``),
|
| 477 |
+
to eliminate overshoot and avoid edge cases of both numerator and
|
| 478 |
+
denominator being equal to 0, the weights are modified as follows:
|
| 479 |
+
|
| 480 |
+
.. math::
|
| 481 |
+
|
| 482 |
+
\begin{align*}
|
| 483 |
+
w_1 &= |\delta_{i+1} - \delta_i| + |\delta_{i+1} + \delta_i| / 2 \\
|
| 484 |
+
w_2 &= |\delta_{i-1} - \delta_{i-2}| + |\delta_{i-1} + \delta_{i-2}| / 2
|
| 485 |
+
\end{align*}
|
| 486 |
+
|
| 487 |
+
Examples
|
| 488 |
+
--------
|
| 489 |
+
Comparison of ``method="akima"`` and ``method="makima"``:
|
| 490 |
+
|
| 491 |
+
>>> import numpy as np
|
| 492 |
+
>>> from scipy.interpolate import Akima1DInterpolator
|
| 493 |
+
>>> import matplotlib.pyplot as plt
|
| 494 |
+
>>> x = np.linspace(1, 7, 7)
|
| 495 |
+
>>> y = np.array([-1, -1, -1, 0, 1, 1, 1])
|
| 496 |
+
>>> xs = np.linspace(min(x), max(x), num=100)
|
| 497 |
+
>>> y_akima = Akima1DInterpolator(x, y, method="akima")(xs)
|
| 498 |
+
>>> y_makima = Akima1DInterpolator(x, y, method="makima")(xs)
|
| 499 |
+
|
| 500 |
+
>>> fig, ax = plt.subplots()
|
| 501 |
+
>>> ax.plot(x, y, "o", label="data")
|
| 502 |
+
>>> ax.plot(xs, y_akima, label="akima")
|
| 503 |
+
>>> ax.plot(xs, y_makima, label="makima")
|
| 504 |
+
>>> ax.legend()
|
| 505 |
+
>>> fig.show()
|
| 506 |
+
|
| 507 |
+
The overshoot that occurred in ``"akima"`` has been avoided in ``"makima"``.
|
| 508 |
+
|
| 509 |
+
References
|
| 510 |
+
----------
|
| 511 |
+
.. [1] A new method of interpolation and smooth curve fitting based
|
| 512 |
+
on local procedures. Hiroshi Akima, J. ACM, October 1970, 17(4),
|
| 513 |
+
589-602. :doi:`10.1145/321607.321609`
|
| 514 |
+
.. [2] Makima Piecewise Cubic Interpolation. Cleve Moler and Cosmin Ionita, 2019.
|
| 515 |
+
https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/
|
| 516 |
+
|
| 517 |
+
"""
|
| 518 |
+
|
| 519 |
+
# PchipInterpolator is not generic in scipy-stubs
|
| 520 |
+
__class_getitem__ = None
|
| 521 |
+
|
| 522 |
+
def __init__(self, x, y, axis=0, *, method: Literal["akima", "makima"]="akima",
|
| 523 |
+
extrapolate:bool | None = None):
|
| 524 |
+
if method not in {"akima", "makima"}:
|
| 525 |
+
raise NotImplementedError(f"`method`={method} is unsupported.")
|
| 526 |
+
# Original implementation in MATLAB by N. Shamsundar (BSD licensed), see
|
| 527 |
+
# https://www.mathworks.com/matlabcentral/fileexchange/1814-akima-interpolation
|
| 528 |
+
|
| 529 |
+
xp = array_namespace(x, y)
|
| 530 |
+
x, dx, y, axis, _ = prepare_input(x, y, axis, xp=xp)
|
| 531 |
+
|
| 532 |
+
if xp.isdtype(y.dtype, "complex floating"):
|
| 533 |
+
msg = ("`Akima1DInterpolator` only works with real values for `y`. "
|
| 534 |
+
"If you are trying to use the real components of the passed array, "
|
| 535 |
+
"use `np.real` on the array before passing to "
|
| 536 |
+
"`Akima1DInterpolator`.")
|
| 537 |
+
raise ValueError(msg)
|
| 538 |
+
|
| 539 |
+
# Akima extrapolation historically False; parent class defaults to True.
|
| 540 |
+
extrapolate = False if extrapolate is None else extrapolate
|
| 541 |
+
|
| 542 |
+
if y.shape[0] == 2:
|
| 543 |
+
# edge case: only have two points, use linear interpolation
|
| 544 |
+
xv = xp.reshape(x, (x.shape[0],) + (1,)*(y.ndim-1))
|
| 545 |
+
hk = xv[1:, ...] - xv[:-1, ...]
|
| 546 |
+
mk = (y[1:, ...] - y[:-1, ...]) / hk
|
| 547 |
+
t = xp.zeros_like(y)
|
| 548 |
+
t[...] = mk
|
| 549 |
+
else:
|
| 550 |
+
# determine slopes between breakpoints
|
| 551 |
+
m = xp.empty((x.shape[0] + 3, ) + y.shape[1:])
|
| 552 |
+
dx = dx[(slice(None), ) + (None, ) * (y.ndim - 1)]
|
| 553 |
+
m[2:-2, ...] = xp.diff(y, axis=0) / dx
|
| 554 |
+
|
| 555 |
+
# add two additional points on the left ...
|
| 556 |
+
m[1, ...] = 2. * m[2, ...] - m[3, ...]
|
| 557 |
+
m[0, ...] = 2. * m[1, ...] - m[2, ...]
|
| 558 |
+
# ... and on the right
|
| 559 |
+
m[-2, ...] = 2. * m[-3, ...] - m[-4, ...]
|
| 560 |
+
m[-1, ...] = 2. * m[-2, ...] - m[-3, ...]
|
| 561 |
+
|
| 562 |
+
# if m1 == m2 != m3 == m4, the slope at the breakpoint is not
|
| 563 |
+
# defined. This is the fill value:
|
| 564 |
+
t = .5 * (m[3:, ...] + m[:-3, ...])
|
| 565 |
+
# get the denominator of the slope t
|
| 566 |
+
dm = xp.abs(xp.diff(m, axis=0))
|
| 567 |
+
if method == "makima":
|
| 568 |
+
pm = xp.abs(m[1:, ...] + m[:-1, ...])
|
| 569 |
+
f1 = dm[2:, ...] + 0.5 * pm[2:, ...]
|
| 570 |
+
f2 = dm[:-2, ...] + 0.5 * pm[:-2, ...]
|
| 571 |
+
else:
|
| 572 |
+
f1 = dm[2:, ...]
|
| 573 |
+
f2 = dm[:-2, ...]
|
| 574 |
+
|
| 575 |
+
# makima is more numerically stable for small f12,
|
| 576 |
+
# so a finite cutoff should not improve any behavior
|
| 577 |
+
# however, akima has a qualitative discontinuity near f12=0
|
| 578 |
+
# a finite cutoff moves it, but cannot remove it.
|
| 579 |
+
# the cutoff break_mult could be made a keyword argument
|
| 580 |
+
# method='akima' also benefits from a check for m2=m3
|
| 581 |
+
break_mult = 1.e-9
|
| 582 |
+
|
| 583 |
+
f12 = f1 + f2
|
| 584 |
+
|
| 585 |
+
# These are the mask of where the slope at breakpoint is defined:
|
| 586 |
+
mmax = xp.max(f12) if xp_size(f12) > 0 else -xp.inf
|
| 587 |
+
ind = xp.nonzero(f12 > break_mult * mmax)
|
| 588 |
+
|
| 589 |
+
x_ind, y_ind = ind[0], ind[1:]
|
| 590 |
+
# Set the slope at breakpoint
|
| 591 |
+
t[ind] = m[(x_ind + 1,) + y_ind] + (
|
| 592 |
+
(f2[ind] / f12[ind])
|
| 593 |
+
* (m[(x_ind + 2,) + y_ind] - m[(x_ind + 1,) + y_ind])
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
super().__init__(x, y, t, axis=0, extrapolate=extrapolate)
|
| 597 |
+
self.axis = axis
|
| 598 |
+
|
| 599 |
+
def extend(self, c, x, right=True):
|
| 600 |
+
raise NotImplementedError("Extending a 1-D Akima interpolator is not "
|
| 601 |
+
"yet implemented")
|
| 602 |
+
|
| 603 |
+
# These are inherited from PPoly, but they do not produce an Akima
|
| 604 |
+
# interpolator. Hence stub them out.
|
| 605 |
+
@classmethod
|
| 606 |
+
def from_spline(cls, tck, extrapolate=None):
|
| 607 |
+
raise NotImplementedError("This method does not make sense for "
|
| 608 |
+
"an Akima interpolator.")
|
| 609 |
+
|
| 610 |
+
@classmethod
|
| 611 |
+
def from_bernstein_basis(cls, bp, extrapolate=None):
|
| 612 |
+
raise NotImplementedError("This method does not make sense for "
|
| 613 |
+
"an Akima interpolator.")
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
@xp_capabilities(
|
| 617 |
+
cpu_only=True, jax_jit=False,
|
| 618 |
+
skip_backends=[
|
| 619 |
+
("dask.array",
|
| 620 |
+
"https://github.com/data-apis/array-api-extra/issues/488")
|
| 621 |
+
]
|
| 622 |
+
)
|
| 623 |
+
class CubicSpline(CubicHermiteSpline):
|
| 624 |
+
"""Piecewise cubic interpolator to fit values (C2 smooth).
|
| 625 |
+
|
| 626 |
+
Interpolate data with a piecewise cubic polynomial which is twice
|
| 627 |
+
continuously differentiable [1]_. The result is represented as a `PPoly`
|
| 628 |
+
instance with breakpoints matching the given data.
|
| 629 |
+
|
| 630 |
+
Parameters
|
| 631 |
+
----------
|
| 632 |
+
x : array_like, shape (n,)
|
| 633 |
+
1-D array containing values of the independent variable.
|
| 634 |
+
Values must be real, finite and in strictly increasing order.
|
| 635 |
+
y : array_like
|
| 636 |
+
Array containing values of the dependent variable. It can have
|
| 637 |
+
arbitrary number of dimensions, but the length along ``axis``
|
| 638 |
+
(see below) must match the length of ``x``. Values must be finite.
|
| 639 |
+
axis : int, optional
|
| 640 |
+
Axis along which `y` is assumed to be varying. Meaning that for
|
| 641 |
+
``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
|
| 642 |
+
Default is 0.
|
| 643 |
+
bc_type : string or 2-tuple, optional
|
| 644 |
+
Boundary condition type. Two additional equations, given by the
|
| 645 |
+
boundary conditions, are required to determine all coefficients of
|
| 646 |
+
polynomials on each segment [2]_.
|
| 647 |
+
|
| 648 |
+
If `bc_type` is a string, then the specified condition will be applied
|
| 649 |
+
at both ends of a spline. Available conditions are:
|
| 650 |
+
|
| 651 |
+
* 'not-a-knot' (default): The first and second segment at a curve end
|
| 652 |
+
are the same polynomial. It is a good default when there is no
|
| 653 |
+
information on boundary conditions.
|
| 654 |
+
* 'periodic': The interpolated functions is assumed to be periodic
|
| 655 |
+
of period ``x[-1] - x[0]``. The first and last value of `y` must be
|
| 656 |
+
identical: ``y[0] == y[-1]``. This boundary condition will result in
|
| 657 |
+
``y'[0] == y'[-1]`` and ``y''[0] == y''[-1]``.
|
| 658 |
+
* 'clamped': The first derivative at curves ends are zero. Assuming
|
| 659 |
+
a 1D `y`, ``bc_type=((1, 0.0), (1, 0.0))`` is the same condition.
|
| 660 |
+
* 'natural': The second derivative at curve ends are zero. Assuming
|
| 661 |
+
a 1D `y`, ``bc_type=((2, 0.0), (2, 0.0))`` is the same condition.
|
| 662 |
+
|
| 663 |
+
If `bc_type` is a 2-tuple, the first and the second value will be
|
| 664 |
+
applied at the curve start and end respectively. The tuple values can
|
| 665 |
+
be one of the previously mentioned strings (except 'periodic') or a
|
| 666 |
+
tuple ``(order, deriv_values)`` allowing to specify arbitrary
|
| 667 |
+
derivatives at curve ends:
|
| 668 |
+
|
| 669 |
+
* `order`: the derivative order, 1 or 2.
|
| 670 |
+
* `deriv_value`: array_like containing derivative values, shape must
|
| 671 |
+
be the same as `y`, excluding ``axis`` dimension. For example, if
|
| 672 |
+
`y` is 1-D, then `deriv_value` must be a scalar. If `y` is 3-D with
|
| 673 |
+
the shape (n0, n1, n2) and axis=2, then `deriv_value` must be 2-D
|
| 674 |
+
and have the shape (n0, n1).
|
| 675 |
+
extrapolate : {bool, 'periodic', None}, optional
|
| 676 |
+
If bool, determines whether to extrapolate to out-of-bounds points
|
| 677 |
+
based on first and last intervals, or to return NaNs. If 'periodic',
|
| 678 |
+
periodic extrapolation is used. If None (default), ``extrapolate`` is
|
| 679 |
+
set to 'periodic' for ``bc_type='periodic'`` and to True otherwise.
|
| 680 |
+
|
| 681 |
+
Attributes
|
| 682 |
+
----------
|
| 683 |
+
x : ndarray, shape (n,)
|
| 684 |
+
Breakpoints. The same ``x`` which was passed to the constructor.
|
| 685 |
+
c : ndarray, shape (4, n-1, ...)
|
| 686 |
+
Coefficients of the polynomials on each segment. The trailing
|
| 687 |
+
dimensions match the dimensions of `y`, excluding ``axis``.
|
| 688 |
+
For example, if `y` is 1-d, then ``c[k, i]`` is a coefficient for
|
| 689 |
+
``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
|
| 690 |
+
axis : int
|
| 691 |
+
Interpolation axis. The same axis which was passed to the
|
| 692 |
+
constructor.
|
| 693 |
+
|
| 694 |
+
Methods
|
| 695 |
+
-------
|
| 696 |
+
__call__
|
| 697 |
+
derivative
|
| 698 |
+
antiderivative
|
| 699 |
+
integrate
|
| 700 |
+
solve
|
| 701 |
+
roots
|
| 702 |
+
|
| 703 |
+
See Also
|
| 704 |
+
--------
|
| 705 |
+
Akima1DInterpolator : Akima 1D interpolator.
|
| 706 |
+
PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
|
| 707 |
+
PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
|
| 708 |
+
|
| 709 |
+
Notes
|
| 710 |
+
-----
|
| 711 |
+
Parameters `bc_type` and ``extrapolate`` work independently, i.e. the
|
| 712 |
+
former controls only construction of a spline, and the latter only
|
| 713 |
+
evaluation.
|
| 714 |
+
|
| 715 |
+
When a boundary condition is 'not-a-knot' and n = 2, it is replaced by
|
| 716 |
+
a condition that the first derivative is equal to the linear interpolant
|
| 717 |
+
slope. When both boundary conditions are 'not-a-knot' and n = 3, the
|
| 718 |
+
solution is sought as a parabola passing through given points.
|
| 719 |
+
|
| 720 |
+
When 'not-a-knot' boundary conditions is applied to both ends, the
|
| 721 |
+
resulting spline will be the same as returned by `splrep` (with ``s=0``)
|
| 722 |
+
and `InterpolatedUnivariateSpline`, but these two methods use a
|
| 723 |
+
representation in B-spline basis.
|
| 724 |
+
|
| 725 |
+
.. versionadded:: 0.18.0
|
| 726 |
+
|
| 727 |
+
Examples
|
| 728 |
+
--------
|
| 729 |
+
In this example the cubic spline is used to interpolate a sampled sinusoid.
|
| 730 |
+
You can see that the spline continuity property holds for the first and
|
| 731 |
+
second derivatives and violates only for the third derivative.
|
| 732 |
+
|
| 733 |
+
>>> import numpy as np
|
| 734 |
+
>>> from scipy.interpolate import CubicSpline
|
| 735 |
+
>>> import matplotlib.pyplot as plt
|
| 736 |
+
>>> x = np.arange(10)
|
| 737 |
+
>>> y = np.sin(x)
|
| 738 |
+
>>> cs = CubicSpline(x, y)
|
| 739 |
+
>>> xs = np.arange(-0.5, 9.6, 0.1)
|
| 740 |
+
>>> fig, ax = plt.subplots(figsize=(6.5, 4))
|
| 741 |
+
>>> ax.plot(x, y, 'o', label='data')
|
| 742 |
+
>>> ax.plot(xs, np.sin(xs), label='true')
|
| 743 |
+
>>> ax.plot(xs, cs(xs), label="S")
|
| 744 |
+
>>> ax.plot(xs, cs(xs, 1), label="S'")
|
| 745 |
+
>>> ax.plot(xs, cs(xs, 2), label="S''")
|
| 746 |
+
>>> ax.plot(xs, cs(xs, 3), label="S'''")
|
| 747 |
+
>>> ax.set_xlim(-0.5, 9.5)
|
| 748 |
+
>>> ax.legend(loc='lower left', ncol=2)
|
| 749 |
+
>>> plt.show()
|
| 750 |
+
|
| 751 |
+
In the second example, the unit circle is interpolated with a spline. A
|
| 752 |
+
periodic boundary condition is used. You can see that the first derivative
|
| 753 |
+
values, ds/dx=0, ds/dy=1 at the periodic point (1, 0) are correctly
|
| 754 |
+
computed. Note that a circle cannot be exactly represented by a cubic
|
| 755 |
+
spline. To increase precision, more breakpoints would be required.
|
| 756 |
+
|
| 757 |
+
>>> theta = 2 * np.pi * np.linspace(0, 1, 5)
|
| 758 |
+
>>> y = np.c_[np.cos(theta), np.sin(theta)]
|
| 759 |
+
>>> cs = CubicSpline(theta, y, bc_type='periodic')
|
| 760 |
+
>>> print("ds/dx={:.1f} ds/dy={:.1f}".format(cs(0, 1)[0], cs(0, 1)[1]))
|
| 761 |
+
ds/dx=0.0 ds/dy=1.0
|
| 762 |
+
>>> xs = 2 * np.pi * np.linspace(0, 1, 100)
|
| 763 |
+
>>> fig, ax = plt.subplots(figsize=(6.5, 4))
|
| 764 |
+
>>> ax.plot(y[:, 0], y[:, 1], 'o', label='data')
|
| 765 |
+
>>> ax.plot(np.cos(xs), np.sin(xs), label='true')
|
| 766 |
+
>>> ax.plot(cs(xs)[:, 0], cs(xs)[:, 1], label='spline')
|
| 767 |
+
>>> ax.axes.set_aspect('equal')
|
| 768 |
+
>>> ax.legend(loc='center')
|
| 769 |
+
>>> plt.show()
|
| 770 |
+
|
| 771 |
+
The third example is the interpolation of a polynomial y = x**3 on the
|
| 772 |
+
interval 0 <= x<= 1. A cubic spline can represent this function exactly.
|
| 773 |
+
To achieve that we need to specify values and first derivatives at
|
| 774 |
+
endpoints of the interval. Note that y' = 3 * x**2 and thus y'(0) = 0 and
|
| 775 |
+
y'(1) = 3.
|
| 776 |
+
|
| 777 |
+
>>> cs = CubicSpline([0, 1], [0, 1], bc_type=((1, 0), (1, 3)))
|
| 778 |
+
>>> x = np.linspace(0, 1)
|
| 779 |
+
>>> np.allclose(x**3, cs(x))
|
| 780 |
+
True
|
| 781 |
+
|
| 782 |
+
References
|
| 783 |
+
----------
|
| 784 |
+
.. [1] `Cubic Spline Interpolation
|
| 785 |
+
<https://en.wikiversity.org/wiki/Cubic_Spline_Interpolation>`_
|
| 786 |
+
on Wikiversity.
|
| 787 |
+
.. [2] Carl de Boor, "A Practical Guide to Splines", Springer-Verlag, 1978.
|
| 788 |
+
"""
|
| 789 |
+
|
| 790 |
+
def __init__(self, x, y, axis=0, bc_type='not-a-knot', extrapolate=None):
|
| 791 |
+
xp = array_namespace(x, y)
|
| 792 |
+
x, dx, y, axis, _ = prepare_input(x, y, axis, xp=np_compat)
|
| 793 |
+
n = len(x)
|
| 794 |
+
|
| 795 |
+
bc, y = self._validate_bc(bc_type, y, y.shape[1:], axis)
|
| 796 |
+
|
| 797 |
+
if extrapolate is None:
|
| 798 |
+
if bc[0] == 'periodic':
|
| 799 |
+
extrapolate = 'periodic'
|
| 800 |
+
else:
|
| 801 |
+
extrapolate = True
|
| 802 |
+
|
| 803 |
+
if y.size == 0:
|
| 804 |
+
# bail out early for zero-sized arrays
|
| 805 |
+
s = np.zeros_like(y)
|
| 806 |
+
else:
|
| 807 |
+
dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1))
|
| 808 |
+
slope = np.diff(y, axis=0) / dxr
|
| 809 |
+
|
| 810 |
+
# If bc is 'not-a-knot' this change is just a convention.
|
| 811 |
+
# If bc is 'periodic' then we already checked that y[0] == y[-1],
|
| 812 |
+
# and the spline is just a constant, we handle this case in the
|
| 813 |
+
# same way by setting the first derivatives to slope, which is 0.
|
| 814 |
+
if n == 2:
|
| 815 |
+
if bc[0] in ['not-a-knot', 'periodic']:
|
| 816 |
+
bc[0] = (1, slope[0])
|
| 817 |
+
if bc[1] in ['not-a-knot', 'periodic']:
|
| 818 |
+
bc[1] = (1, slope[0])
|
| 819 |
+
|
| 820 |
+
# This is a special case, when both conditions are 'not-a-knot'
|
| 821 |
+
# and n == 3. In this case 'not-a-knot' can't be handled regularly
|
| 822 |
+
# as the both conditions are identical. We handle this case by
|
| 823 |
+
# constructing a parabola passing through given points.
|
| 824 |
+
if n == 3 and bc[0] == 'not-a-knot' and bc[1] == 'not-a-knot':
|
| 825 |
+
A = np.zeros((3, 3)) # This is a standard matrix.
|
| 826 |
+
b = np.empty((3,) + y.shape[1:], dtype=y.dtype)
|
| 827 |
+
|
| 828 |
+
A[0, 0] = 1
|
| 829 |
+
A[0, 1] = 1
|
| 830 |
+
A[1, 0] = dx[1]
|
| 831 |
+
A[1, 1] = 2 * (dx[0] + dx[1])
|
| 832 |
+
A[1, 2] = dx[0]
|
| 833 |
+
A[2, 1] = 1
|
| 834 |
+
A[2, 2] = 1
|
| 835 |
+
|
| 836 |
+
b[0] = 2 * slope[0]
|
| 837 |
+
b[1] = 3 * (dxr[0] * slope[1] + dxr[1] * slope[0])
|
| 838 |
+
b[2] = 2 * slope[1]
|
| 839 |
+
|
| 840 |
+
m = b.shape[0]
|
| 841 |
+
s = solve(A, b.reshape(m, -1), overwrite_a=True, overwrite_b=True,
|
| 842 |
+
check_finite=False).reshape(b.shape)
|
| 843 |
+
elif n == 3 and bc[0] == 'periodic':
|
| 844 |
+
# In case when number of points is 3 we compute the derivatives
|
| 845 |
+
# manually
|
| 846 |
+
t = (slope / dxr).sum(0) / (1. / dxr).sum(0)
|
| 847 |
+
s = np.broadcast_to(t, (n,) + y.shape[1:])
|
| 848 |
+
else:
|
| 849 |
+
# Find derivative values at each x[i] by solving a tridiagonal
|
| 850 |
+
# system.
|
| 851 |
+
A = np.zeros((3, n)) # This is a banded matrix representation.
|
| 852 |
+
b = np.empty((n,) + y.shape[1:], dtype=y.dtype)
|
| 853 |
+
|
| 854 |
+
# Filling the system for i=1..n-2
|
| 855 |
+
# (x[i-1] - x[i]) * s[i-1] +\
|
| 856 |
+
# 2 * ((x[i] - x[i-1]) + (x[i+1] - x[i])) * s[i] +\
|
| 857 |
+
# (x[i] - x[i-1]) * s[i+1] =\
|
| 858 |
+
# 3 * ((x[i+1] - x[i])*(y[i] - y[i-1])/(x[i] - x[i-1]) +\
|
| 859 |
+
# (x[i] - x[i-1])*(y[i+1] - y[i])/(x[i+1] - x[i]))
|
| 860 |
+
|
| 861 |
+
A[1, 1:-1] = 2 * (dx[:-1] + dx[1:]) # The diagonal
|
| 862 |
+
A[0, 2:] = dx[:-1] # The upper diagonal
|
| 863 |
+
A[-1, :-2] = dx[1:] # The lower diagonal
|
| 864 |
+
|
| 865 |
+
b[1:-1] = 3 * (dxr[1:] * slope[:-1] + dxr[:-1] * slope[1:])
|
| 866 |
+
|
| 867 |
+
bc_start, bc_end = bc
|
| 868 |
+
|
| 869 |
+
if bc_start == 'periodic':
|
| 870 |
+
# Due to the periodicity, and because y[-1] = y[0], the
|
| 871 |
+
# linear system has (n-1) unknowns/equations instead of n:
|
| 872 |
+
A = A[:, 0:-1]
|
| 873 |
+
A[1, 0] = 2 * (dx[-1] + dx[0])
|
| 874 |
+
A[0, 1] = dx[-1]
|
| 875 |
+
|
| 876 |
+
b = b[:-1]
|
| 877 |
+
|
| 878 |
+
# Also, due to the periodicity, the system is not tri-diagonal.
|
| 879 |
+
# We need to compute a "condensed" matrix of shape (n-2, n-2).
|
| 880 |
+
# See https://web.archive.org/web/20151220180652/http://www.cfm.brown.edu/people/gk/chap6/node14.html
|
| 881 |
+
# for more explanations.
|
| 882 |
+
# The condensed matrix is obtained by removing the last column
|
| 883 |
+
# and last row of the (n-1, n-1) system matrix. The removed
|
| 884 |
+
# values are saved in scalar variables with the (n-1, n-1)
|
| 885 |
+
# system matrix indices forming their names:
|
| 886 |
+
a_m1_0 = dx[-2] # lower left corner value: A[-1, 0]
|
| 887 |
+
a_m1_m2 = dx[-1]
|
| 888 |
+
a_m1_m1 = 2 * (dx[-1] + dx[-2])
|
| 889 |
+
a_m2_m1 = dx[-3]
|
| 890 |
+
a_0_m1 = dx[0]
|
| 891 |
+
|
| 892 |
+
b[0] = 3 * (dxr[0] * slope[-1] + dxr[-1] * slope[0])
|
| 893 |
+
b[-1] = 3 * (dxr[-1] * slope[-2] + dxr[-2] * slope[-1])
|
| 894 |
+
|
| 895 |
+
Ac = A[:, :-1]
|
| 896 |
+
b1 = b[:-1]
|
| 897 |
+
b2 = np.zeros_like(b1)
|
| 898 |
+
b2[0] = -a_0_m1
|
| 899 |
+
b2[-1] = -a_m2_m1
|
| 900 |
+
|
| 901 |
+
# s1 and s2 are the solutions of (n-2, n-2) system
|
| 902 |
+
m = b1.shape[0]
|
| 903 |
+
s1 = solve_banded((1, 1), Ac, b1.reshape(m, -1), overwrite_ab=False,
|
| 904 |
+
overwrite_b=False, check_finite=False)
|
| 905 |
+
s1 = s1.reshape(b1.shape)
|
| 906 |
+
|
| 907 |
+
m = b2.shape[0]
|
| 908 |
+
s2 = solve_banded((1, 1), Ac, b2.reshape(m, -1), overwrite_ab=False,
|
| 909 |
+
overwrite_b=False, check_finite=False)
|
| 910 |
+
s2 = s2.reshape(b2.shape)
|
| 911 |
+
|
| 912 |
+
# computing the s[n-2] solution:
|
| 913 |
+
s_m1 = ((b[-1] - a_m1_0 * s1[0] - a_m1_m2 * s1[-1]) /
|
| 914 |
+
(a_m1_m1 + a_m1_0 * s2[0] + a_m1_m2 * s2[-1]))
|
| 915 |
+
|
| 916 |
+
# s is the solution of the (n, n) system:
|
| 917 |
+
s = np.empty((n,) + y.shape[1:], dtype=y.dtype)
|
| 918 |
+
s[:-2] = s1 + s_m1 * s2
|
| 919 |
+
s[-2] = s_m1
|
| 920 |
+
s[-1] = s[0]
|
| 921 |
+
else:
|
| 922 |
+
if bc_start == 'not-a-knot':
|
| 923 |
+
A[1, 0] = dx[1]
|
| 924 |
+
A[0, 1] = x[2] - x[0]
|
| 925 |
+
d = x[2] - x[0]
|
| 926 |
+
b[0] = ((dxr[0] + 2*d) * dxr[1] * slope[0] +
|
| 927 |
+
dxr[0]**2 * slope[1]) / d
|
| 928 |
+
elif bc_start[0] == 1:
|
| 929 |
+
A[1, 0] = 1
|
| 930 |
+
A[0, 1] = 0
|
| 931 |
+
b[0] = bc_start[1]
|
| 932 |
+
elif bc_start[0] == 2:
|
| 933 |
+
A[1, 0] = 2 * dx[0]
|
| 934 |
+
A[0, 1] = dx[0]
|
| 935 |
+
b[0] = -0.5 * bc_start[1] * dx[0]**2 + 3 * (y[1] - y[0])
|
| 936 |
+
|
| 937 |
+
if bc_end == 'not-a-knot':
|
| 938 |
+
A[1, -1] = dx[-2]
|
| 939 |
+
A[-1, -2] = x[-1] - x[-3]
|
| 940 |
+
d = x[-1] - x[-3]
|
| 941 |
+
b[-1] = ((dxr[-1]**2*slope[-2] +
|
| 942 |
+
(2*d + dxr[-1])*dxr[-2]*slope[-1]) / d)
|
| 943 |
+
elif bc_end[0] == 1:
|
| 944 |
+
A[1, -1] = 1
|
| 945 |
+
A[-1, -2] = 0
|
| 946 |
+
b[-1] = bc_end[1]
|
| 947 |
+
elif bc_end[0] == 2:
|
| 948 |
+
A[1, -1] = 2 * dx[-1]
|
| 949 |
+
A[-1, -2] = dx[-1]
|
| 950 |
+
b[-1] = 0.5 * bc_end[1] * dx[-1]**2 + 3 * (y[-1] - y[-2])
|
| 951 |
+
|
| 952 |
+
m = b.shape[0]
|
| 953 |
+
s = solve_banded((1, 1), A, b.reshape(m, -1), overwrite_ab=True,
|
| 954 |
+
overwrite_b=True, check_finite=False)
|
| 955 |
+
s = s.reshape(b.shape)
|
| 956 |
+
|
| 957 |
+
x, y, s = map(xp.asarray, (x, y, s))
|
| 958 |
+
super().__init__(x, y, s, axis=0, extrapolate=extrapolate)
|
| 959 |
+
self.axis = axis
|
| 960 |
+
|
| 961 |
+
@staticmethod
|
| 962 |
+
def _validate_bc(bc_type, y, expected_deriv_shape, axis):
|
| 963 |
+
"""Validate and prepare boundary conditions.
|
| 964 |
+
|
| 965 |
+
Returns
|
| 966 |
+
-------
|
| 967 |
+
validated_bc : 2-tuple
|
| 968 |
+
Boundary conditions for a curve start and end.
|
| 969 |
+
y : ndarray
|
| 970 |
+
y casted to complex dtype if one of the boundary conditions has
|
| 971 |
+
complex dtype.
|
| 972 |
+
"""
|
| 973 |
+
if isinstance(bc_type, str):
|
| 974 |
+
if bc_type == 'periodic':
|
| 975 |
+
if not np.allclose(y[0], y[-1], rtol=1e-15, atol=1e-15):
|
| 976 |
+
raise ValueError(
|
| 977 |
+
f"The first and last `y` point along axis {axis} must "
|
| 978 |
+
"be identical (within machine precision) when "
|
| 979 |
+
"bc_type='periodic'.")
|
| 980 |
+
|
| 981 |
+
bc_type = (bc_type, bc_type)
|
| 982 |
+
|
| 983 |
+
else:
|
| 984 |
+
if len(bc_type) != 2:
|
| 985 |
+
raise ValueError("`bc_type` must contain 2 elements to "
|
| 986 |
+
"specify start and end conditions.")
|
| 987 |
+
|
| 988 |
+
if 'periodic' in bc_type:
|
| 989 |
+
raise ValueError("'periodic' `bc_type` is defined for both "
|
| 990 |
+
"curve ends and cannot be used with other "
|
| 991 |
+
"boundary conditions.")
|
| 992 |
+
|
| 993 |
+
validated_bc = []
|
| 994 |
+
for bc in bc_type:
|
| 995 |
+
if isinstance(bc, str):
|
| 996 |
+
if bc == 'clamped':
|
| 997 |
+
validated_bc.append((1, np.zeros(expected_deriv_shape)))
|
| 998 |
+
elif bc == 'natural':
|
| 999 |
+
validated_bc.append((2, np.zeros(expected_deriv_shape)))
|
| 1000 |
+
elif bc in ['not-a-knot', 'periodic']:
|
| 1001 |
+
validated_bc.append(bc)
|
| 1002 |
+
else:
|
| 1003 |
+
raise ValueError(f"bc_type={bc} is not allowed.")
|
| 1004 |
+
else:
|
| 1005 |
+
try:
|
| 1006 |
+
deriv_order, deriv_value = bc
|
| 1007 |
+
except Exception as e:
|
| 1008 |
+
raise ValueError(
|
| 1009 |
+
"A specified derivative value must be "
|
| 1010 |
+
"given in the form (order, value)."
|
| 1011 |
+
) from e
|
| 1012 |
+
|
| 1013 |
+
if deriv_order not in [1, 2]:
|
| 1014 |
+
raise ValueError("The specified derivative order must "
|
| 1015 |
+
"be 1 or 2.")
|
| 1016 |
+
|
| 1017 |
+
deriv_value = np.asarray(deriv_value)
|
| 1018 |
+
if deriv_value.shape != expected_deriv_shape:
|
| 1019 |
+
raise ValueError(
|
| 1020 |
+
f"`deriv_value` shape {deriv_value.shape} is not "
|
| 1021 |
+
f"the expected one {expected_deriv_shape}."
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
if np.issubdtype(deriv_value.dtype, np.complexfloating):
|
| 1025 |
+
y = y.astype(complex, copy=False)
|
| 1026 |
+
|
| 1027 |
+
validated_bc.append((deriv_order, deriv_value))
|
| 1028 |
+
|
| 1029 |
+
return validated_bc, y
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_fitpack.cpython-311-x86_64-linux-gnu.so
ADDED
|
Binary file (95.6 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_ndbspline.py
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ericAlias
|
| 8 |
+
|
| 9 |
+
from . import _dierckx # type: ignore[attr-defined]
|
| 10 |
+
|
| 11 |
+
import scipy.sparse.linalg as ssl
|
| 12 |
+
from scipy.sparse import csr_array
|
| 13 |
+
from scipy._lib._array_api import array_namespace, xp_capabilities
|
| 14 |
+
|
| 15 |
+
from ._bsplines import _not_a_knot, BSpline
|
| 16 |
+
|
| 17 |
+
__all__ = ["NdBSpline"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _get_dtype(dtype):
|
| 21 |
+
"""Return np.complex128 for complex dtypes, np.float64 otherwise."""
|
| 22 |
+
if np.issubdtype(dtype, np.complexfloating):
|
| 23 |
+
return np.complex128
|
| 24 |
+
else:
|
| 25 |
+
return np.float64
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@xp_capabilities(
|
| 29 |
+
cpu_only=True, jax_jit=False,
|
| 30 |
+
skip_backends=[
|
| 31 |
+
("dask.array",
|
| 32 |
+
"https://github.com/data-apis/array-api-extra/issues/488")
|
| 33 |
+
]
|
| 34 |
+
)
|
| 35 |
+
class NdBSpline:
|
| 36 |
+
"""Tensor product spline object.
|
| 37 |
+
|
| 38 |
+
The value at point ``xp = (x1, x2, ..., xN)`` is evaluated as a linear
|
| 39 |
+
combination of products of one-dimensional b-splines in each of the ``N``
|
| 40 |
+
dimensions::
|
| 41 |
+
|
| 42 |
+
c[i1, i2, ..., iN] * B(x1; i1, t1) * B(x2; i2, t2) * ... * B(xN; iN, tN)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
Here ``B(x; i, t)`` is the ``i``-th b-spline defined by the knot vector
|
| 46 |
+
``t`` evaluated at ``x``.
|
| 47 |
+
|
| 48 |
+
Parameters
|
| 49 |
+
----------
|
| 50 |
+
t : tuple of 1D ndarrays
|
| 51 |
+
knot vectors in directions 1, 2, ... N,
|
| 52 |
+
``len(t[i]) == n[i] + k + 1``
|
| 53 |
+
c : ndarray, shape (n1, n2, ..., nN, ...)
|
| 54 |
+
b-spline coefficients
|
| 55 |
+
k : int or length-d tuple of integers
|
| 56 |
+
spline degrees.
|
| 57 |
+
A single integer is interpreted as having this degree for
|
| 58 |
+
all dimensions.
|
| 59 |
+
extrapolate : bool, optional
|
| 60 |
+
Whether to extrapolate out-of-bounds inputs, or return `nan`.
|
| 61 |
+
Default is to extrapolate.
|
| 62 |
+
|
| 63 |
+
Attributes
|
| 64 |
+
----------
|
| 65 |
+
t : tuple of ndarrays
|
| 66 |
+
Knots vectors.
|
| 67 |
+
c : ndarray
|
| 68 |
+
Coefficients of the tensor-product spline.
|
| 69 |
+
k : tuple of integers
|
| 70 |
+
Degrees for each dimension.
|
| 71 |
+
extrapolate : bool, optional
|
| 72 |
+
Whether to extrapolate or return nans for out-of-bounds inputs.
|
| 73 |
+
Defaults to true.
|
| 74 |
+
|
| 75 |
+
Methods
|
| 76 |
+
-------
|
| 77 |
+
__call__
|
| 78 |
+
derivative
|
| 79 |
+
design_matrix
|
| 80 |
+
|
| 81 |
+
See Also
|
| 82 |
+
--------
|
| 83 |
+
BSpline : a one-dimensional B-spline object
|
| 84 |
+
NdPPoly : an N-dimensional piecewise tensor product polynomial
|
| 85 |
+
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
# generic type compatibility with scipy-stubs
|
| 89 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 90 |
+
|
| 91 |
+
def __init__(self, t, c, k, *, extrapolate=None):
|
| 92 |
+
self._k, self._indices_k1d, (self._t, self._len_t) = _preprocess_inputs(k, t)
|
| 93 |
+
|
| 94 |
+
self._asarray = array_namespace(c, *t).asarray
|
| 95 |
+
|
| 96 |
+
if extrapolate is None:
|
| 97 |
+
extrapolate = True
|
| 98 |
+
self.extrapolate = bool(extrapolate)
|
| 99 |
+
|
| 100 |
+
self._c = np.asarray(c)
|
| 101 |
+
|
| 102 |
+
ndim = self._t.shape[0] # == len(self.t)
|
| 103 |
+
if self._c.ndim < ndim:
|
| 104 |
+
raise ValueError(f"Coefficients must be at least {ndim}-dimensional.")
|
| 105 |
+
|
| 106 |
+
for d in range(ndim):
|
| 107 |
+
td = self.t[d]
|
| 108 |
+
kd = self.k[d]
|
| 109 |
+
n = td.shape[0] - kd - 1
|
| 110 |
+
|
| 111 |
+
if self._c.shape[d] != n:
|
| 112 |
+
raise ValueError(f"Knots, coefficients and degree in dimension"
|
| 113 |
+
f" {d} are inconsistent:"
|
| 114 |
+
f" got {self._c.shape[d]} coefficients for"
|
| 115 |
+
f" {len(td)} knots, need at least {n} for"
|
| 116 |
+
f" k={k}.")
|
| 117 |
+
|
| 118 |
+
dt = _get_dtype(self._c.dtype)
|
| 119 |
+
self._c = np.ascontiguousarray(self._c, dtype=dt)
|
| 120 |
+
|
| 121 |
+
@property
|
| 122 |
+
def k(self):
|
| 123 |
+
return tuple(self._k)
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def t(self):
|
| 127 |
+
# repack the knots into a tuple
|
| 128 |
+
return tuple(
|
| 129 |
+
self._asarray(self._t[d, :self._len_t[d]]) for d in range(self._t.shape[0])
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
@property
|
| 133 |
+
def c(self):
|
| 134 |
+
return self._asarray(self._c)
|
| 135 |
+
|
| 136 |
+
def __call__(self, xi, *, nu=None, extrapolate=None):
|
| 137 |
+
"""Evaluate the tensor product b-spline at ``xi``.
|
| 138 |
+
|
| 139 |
+
Parameters
|
| 140 |
+
----------
|
| 141 |
+
xi : array_like, shape(..., ndim)
|
| 142 |
+
The coordinates to evaluate the interpolator at.
|
| 143 |
+
This can be a list or tuple of ndim-dimensional points
|
| 144 |
+
or an array with the shape (num_points, ndim).
|
| 145 |
+
nu : sequence of length ``ndim``, optional
|
| 146 |
+
Orders of derivatives to evaluate. Each must be non-negative.
|
| 147 |
+
Defaults to the zeroth derivivative.
|
| 148 |
+
extrapolate : bool, optional
|
| 149 |
+
Whether to exrapolate based on first and last intervals in each
|
| 150 |
+
dimension, or return `nan`. Default is to ``self.extrapolate``.
|
| 151 |
+
|
| 152 |
+
Returns
|
| 153 |
+
-------
|
| 154 |
+
values : ndarray, shape ``xi.shape[:-1] + self.c.shape[ndim:]``
|
| 155 |
+
Interpolated values at ``xi``
|
| 156 |
+
"""
|
| 157 |
+
ndim = self._t.shape[0] # == len(self.t)
|
| 158 |
+
|
| 159 |
+
if extrapolate is None:
|
| 160 |
+
extrapolate = self.extrapolate
|
| 161 |
+
extrapolate = bool(extrapolate)
|
| 162 |
+
|
| 163 |
+
if nu is None:
|
| 164 |
+
nu = np.zeros((ndim,), dtype=np.int64)
|
| 165 |
+
else:
|
| 166 |
+
nu = np.asarray(nu, dtype=np.int64)
|
| 167 |
+
if nu.ndim != 1 or nu.shape[0] != ndim:
|
| 168 |
+
raise ValueError(
|
| 169 |
+
f"invalid number of derivative orders {nu = } for "
|
| 170 |
+
f"ndim = {len(self.t)}.")
|
| 171 |
+
if any(nu < 0):
|
| 172 |
+
raise ValueError(f"derivatives must be positive, got {nu = }")
|
| 173 |
+
|
| 174 |
+
# prepare xi : shape (..., m1, ..., md) -> (1, m1, ..., md)
|
| 175 |
+
xi = np.asarray(xi, dtype=float)
|
| 176 |
+
xi_shape = xi.shape
|
| 177 |
+
xi = xi.reshape(-1, xi_shape[-1])
|
| 178 |
+
xi = np.ascontiguousarray(xi)
|
| 179 |
+
|
| 180 |
+
if xi_shape[-1] != ndim:
|
| 181 |
+
raise ValueError(f"Shapes: xi.shape={xi_shape} and ndim={ndim}")
|
| 182 |
+
|
| 183 |
+
# complex -> double
|
| 184 |
+
was_complex = self._c.dtype.kind == 'c'
|
| 185 |
+
cc = self._c
|
| 186 |
+
if was_complex and self._c.ndim == ndim:
|
| 187 |
+
# make sure that core dimensions are intact, and complex->float
|
| 188 |
+
# size doubling only adds a trailing dimension
|
| 189 |
+
cc = self._c[..., None]
|
| 190 |
+
cc = cc.view(float)
|
| 191 |
+
|
| 192 |
+
# prepare the coefficients: flatten the trailing dimensions
|
| 193 |
+
c1 = cc.reshape(cc.shape[:ndim] + (-1,))
|
| 194 |
+
c1r = c1.ravel()
|
| 195 |
+
|
| 196 |
+
# replacement for np.ravel_multi_index for indexing of `c1`:
|
| 197 |
+
_strides_c1 = np.asarray([s // c1.dtype.itemsize
|
| 198 |
+
for s in c1.strides], dtype=np.int64)
|
| 199 |
+
|
| 200 |
+
num_c_tr = c1.shape[-1] # # of trailing coefficients
|
| 201 |
+
out = _dierckx.evaluate_ndbspline(xi,
|
| 202 |
+
self._t,
|
| 203 |
+
self._len_t,
|
| 204 |
+
self._k,
|
| 205 |
+
nu,
|
| 206 |
+
extrapolate,
|
| 207 |
+
c1r,
|
| 208 |
+
num_c_tr,
|
| 209 |
+
_strides_c1,
|
| 210 |
+
self._indices_k1d,
|
| 211 |
+
)
|
| 212 |
+
out = out.view(self._c.dtype)
|
| 213 |
+
out = out.reshape(xi_shape[:-1] + self._c.shape[ndim:])
|
| 214 |
+
return self._asarray(out)
|
| 215 |
+
|
| 216 |
+
@classmethod
|
| 217 |
+
def design_matrix(cls, xvals, t, k, extrapolate=True):
|
| 218 |
+
"""Construct the design matrix as a CSR format sparse array.
|
| 219 |
+
|
| 220 |
+
Parameters
|
| 221 |
+
----------
|
| 222 |
+
xvals : ndarray, shape(npts, ndim)
|
| 223 |
+
Data points. ``xvals[j, :]`` gives the ``j``-th data point as an
|
| 224 |
+
``ndim``-dimensional array.
|
| 225 |
+
t : tuple of 1D ndarrays, length-ndim
|
| 226 |
+
Knot vectors in directions 1, 2, ... ndim,
|
| 227 |
+
k : int
|
| 228 |
+
B-spline degree.
|
| 229 |
+
extrapolate : bool, optional
|
| 230 |
+
Whether to extrapolate out-of-bounds values of raise a `ValueError`
|
| 231 |
+
|
| 232 |
+
Returns
|
| 233 |
+
-------
|
| 234 |
+
design_matrix : a CSR array
|
| 235 |
+
Each row of the design matrix corresponds to a value in `xvals` and
|
| 236 |
+
contains values of b-spline basis elements which are non-zero
|
| 237 |
+
at this value.
|
| 238 |
+
|
| 239 |
+
"""
|
| 240 |
+
xvals = np.asarray(xvals, dtype=float)
|
| 241 |
+
ndim = xvals.shape[-1]
|
| 242 |
+
if len(t) != ndim:
|
| 243 |
+
raise ValueError(
|
| 244 |
+
f"Data and knots are inconsistent: len(t) = {len(t)} for "
|
| 245 |
+
f" {ndim = }."
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
# tabulate the flat indices for iterating over the (k+1)**ndim subarray
|
| 249 |
+
k, _indices_k1d, (_t, len_t) = _preprocess_inputs(k, t)
|
| 250 |
+
|
| 251 |
+
# Precompute the shape and strides of the 'coefficients array'.
|
| 252 |
+
# This would have been the NdBSpline coefficients; in the present context
|
| 253 |
+
# this is a helper to compute the indices into the colocation matrix.
|
| 254 |
+
c_shape = tuple(len_t[d] - k[d] - 1 for d in range(ndim))
|
| 255 |
+
|
| 256 |
+
# The strides of the coeffs array: the computation is equivalent to
|
| 257 |
+
# >>> cstrides = [s // 8 for s in np.empty(c_shape).strides]
|
| 258 |
+
cs = c_shape[1:] + (1,)
|
| 259 |
+
cstrides = np.cumprod(cs[::-1], dtype=np.int64)[::-1].copy()
|
| 260 |
+
|
| 261 |
+
# heavy lifting happens here
|
| 262 |
+
data, indices, indptr = _dierckx._coloc_nd(xvals,
|
| 263 |
+
_t, len_t, k, _indices_k1d, cstrides)
|
| 264 |
+
|
| 265 |
+
return csr_array((data, indices, indptr))
|
| 266 |
+
|
| 267 |
+
def _bspline_derivative_along_axis(self, c, t, k, axis, nu=1):
|
| 268 |
+
# Move the selected axis to front
|
| 269 |
+
c = np.moveaxis(c, axis, 0)
|
| 270 |
+
n = c.shape[0]
|
| 271 |
+
trailing_shape = c.shape[1:]
|
| 272 |
+
c_flat = c.reshape(n, -1)
|
| 273 |
+
|
| 274 |
+
new_c_list = []
|
| 275 |
+
new_t = None
|
| 276 |
+
|
| 277 |
+
for i in range(c_flat.shape[1]):
|
| 278 |
+
if k >= nu:
|
| 279 |
+
b = BSpline.construct_fast(t, c_flat[:, i], k)
|
| 280 |
+
db = b.derivative(nu)
|
| 281 |
+
# truncate coefficients to match new knot/degree size
|
| 282 |
+
db.c = db.c[:len(db.t) - db.k - 1]
|
| 283 |
+
else:
|
| 284 |
+
db = BSpline.construct_fast(t, np.zeros(len(t) - 1), 0)
|
| 285 |
+
|
| 286 |
+
if new_t is None:
|
| 287 |
+
new_t = db.t
|
| 288 |
+
|
| 289 |
+
new_c_list.append(db.c)
|
| 290 |
+
|
| 291 |
+
new_c = np.stack(new_c_list, axis=1).reshape(
|
| 292 |
+
(len(new_c_list[0]),) + trailing_shape)
|
| 293 |
+
new_c = np.moveaxis(new_c, 0, axis)
|
| 294 |
+
|
| 295 |
+
return new_c, new_t
|
| 296 |
+
|
| 297 |
+
def derivative(self, nu):
|
| 298 |
+
"""
|
| 299 |
+
Construct a new NdBSpline representing the partial derivative.
|
| 300 |
+
|
| 301 |
+
Parameters
|
| 302 |
+
----------
|
| 303 |
+
nu : array_like of shape (ndim,)
|
| 304 |
+
Orders of the partial derivatives to compute along each dimension.
|
| 305 |
+
|
| 306 |
+
Returns
|
| 307 |
+
-------
|
| 308 |
+
NdBSpline
|
| 309 |
+
A new NdBSpline representing the partial derivative of the original spline.
|
| 310 |
+
|
| 311 |
+
"""
|
| 312 |
+
nu_arr = np.asarray(nu, dtype=np.int64)
|
| 313 |
+
ndim = len(self.t)
|
| 314 |
+
|
| 315 |
+
if nu_arr.ndim != 1 or nu_arr.shape[0] != ndim:
|
| 316 |
+
raise ValueError(
|
| 317 |
+
f"invalid number of derivative orders {nu = } for "
|
| 318 |
+
f"ndim = {len(self.t)}.")
|
| 319 |
+
|
| 320 |
+
if any(nu_arr < 0):
|
| 321 |
+
raise ValueError(f"derivative orders must be positive, got {nu = }")
|
| 322 |
+
|
| 323 |
+
# extract t and c as numpy arrays
|
| 324 |
+
t_new = [self._t[d, :self._len_t[d]] for d in range(self._t.shape[0])]
|
| 325 |
+
k_new = list(self.k)
|
| 326 |
+
c_new = self._c.copy()
|
| 327 |
+
|
| 328 |
+
for axis, n in enumerate(nu_arr):
|
| 329 |
+
if n == 0:
|
| 330 |
+
continue
|
| 331 |
+
|
| 332 |
+
c_new, t_new[axis] = self._bspline_derivative_along_axis(
|
| 333 |
+
c_new, t_new[axis], k_new[axis], axis, nu=n
|
| 334 |
+
)
|
| 335 |
+
k_new[axis] = max(k_new[axis] - n, 0)
|
| 336 |
+
|
| 337 |
+
return NdBSpline(tuple(self._asarray(t) for t in t_new),
|
| 338 |
+
self._asarray(c_new),
|
| 339 |
+
tuple(k_new),
|
| 340 |
+
extrapolate=self.extrapolate
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
def _preprocess_inputs(k, t_tpl):
|
| 344 |
+
"""Helpers: validate and preprocess NdBSpline inputs.
|
| 345 |
+
|
| 346 |
+
Parameters
|
| 347 |
+
----------
|
| 348 |
+
k : int or tuple
|
| 349 |
+
Spline orders
|
| 350 |
+
t_tpl : tuple or array-likes
|
| 351 |
+
Knots.
|
| 352 |
+
"""
|
| 353 |
+
# 1. Make sure t_tpl is a tuple
|
| 354 |
+
if not isinstance(t_tpl, tuple):
|
| 355 |
+
raise ValueError(f"Expect `t` to be a tuple of array-likes. "
|
| 356 |
+
f"Got {t_tpl} instead."
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
# 2. Make ``k`` a tuple of integers
|
| 360 |
+
ndim = len(t_tpl)
|
| 361 |
+
try:
|
| 362 |
+
len(k)
|
| 363 |
+
except TypeError:
|
| 364 |
+
# make k a tuple
|
| 365 |
+
k = (k,)*ndim
|
| 366 |
+
|
| 367 |
+
k = np.asarray([operator.index(ki) for ki in k], dtype=np.int64)
|
| 368 |
+
|
| 369 |
+
if len(k) != ndim:
|
| 370 |
+
raise ValueError(f"len(t) = {len(t_tpl)} != {len(k) = }.")
|
| 371 |
+
|
| 372 |
+
# 3. Validate inputs
|
| 373 |
+
ndim = len(t_tpl)
|
| 374 |
+
for d in range(ndim):
|
| 375 |
+
td = np.asarray(t_tpl[d])
|
| 376 |
+
kd = k[d]
|
| 377 |
+
n = td.shape[0] - kd - 1
|
| 378 |
+
if kd < 0:
|
| 379 |
+
raise ValueError(f"Spline degree in dimension {d} cannot be"
|
| 380 |
+
f" negative.")
|
| 381 |
+
if td.ndim != 1:
|
| 382 |
+
raise ValueError(f"Knot vector in dimension {d} must be"
|
| 383 |
+
f" one-dimensional.")
|
| 384 |
+
if n < kd + 1:
|
| 385 |
+
raise ValueError(f"Need at least {2*kd + 2} knots for degree"
|
| 386 |
+
f" {kd} in dimension {d}.")
|
| 387 |
+
if (np.diff(td) < 0).any():
|
| 388 |
+
raise ValueError(f"Knots in dimension {d} must be in a"
|
| 389 |
+
f" non-decreasing order.")
|
| 390 |
+
if len(np.unique(td[kd:n + 1])) < 2:
|
| 391 |
+
raise ValueError(f"Need at least two internal knots in"
|
| 392 |
+
f" dimension {d}.")
|
| 393 |
+
if not np.isfinite(td).all():
|
| 394 |
+
raise ValueError(f"Knots in dimension {d} should not have"
|
| 395 |
+
f" nans or infs.")
|
| 396 |
+
|
| 397 |
+
# 4. tabulate the flat indices for iterating over the (k+1)**ndim subarray
|
| 398 |
+
# non-zero b-spline elements
|
| 399 |
+
shape = tuple(kd + 1 for kd in k)
|
| 400 |
+
indices = np.unravel_index(np.arange(prod(shape)), shape)
|
| 401 |
+
_indices_k1d = np.asarray(indices, dtype=np.int64).T.copy()
|
| 402 |
+
|
| 403 |
+
# 5. pack the knots into a single array:
|
| 404 |
+
# ([1, 2, 3, 4], [5, 6], (7, 8, 9)) -->
|
| 405 |
+
# array([[1, 2, 3, 4],
|
| 406 |
+
# [5, 6, nan, nan],
|
| 407 |
+
# [7, 8, 9, nan]])
|
| 408 |
+
t_tpl = [np.asarray(t) for t in t_tpl]
|
| 409 |
+
ndim = len(t_tpl)
|
| 410 |
+
len_t = [len(ti) for ti in t_tpl]
|
| 411 |
+
_t = np.empty((ndim, max(len_t)), dtype=float)
|
| 412 |
+
_t.fill(np.nan)
|
| 413 |
+
for d in range(ndim):
|
| 414 |
+
_t[d, :len(t_tpl[d])] = t_tpl[d]
|
| 415 |
+
len_t = np.asarray(len_t, dtype=np.int64)
|
| 416 |
+
|
| 417 |
+
return k, _indices_k1d, (_t, len_t)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _iter_solve(a, b, solver=ssl.gcrotmk, **solver_args):
|
| 421 |
+
# work around iterative solvers not accepting multiple r.h.s.
|
| 422 |
+
|
| 423 |
+
# also work around a.dtype == float64 and b.dtype == complex128
|
| 424 |
+
# cf https://github.com/scipy/scipy/issues/19644
|
| 425 |
+
if np.issubdtype(b.dtype, np.complexfloating):
|
| 426 |
+
real = _iter_solve(a, b.real, solver, **solver_args)
|
| 427 |
+
imag = _iter_solve(a, b.imag, solver, **solver_args)
|
| 428 |
+
return real + 1j*imag
|
| 429 |
+
|
| 430 |
+
if b.ndim == 2 and b.shape[1] !=1:
|
| 431 |
+
res = np.empty_like(b)
|
| 432 |
+
for j in range(b.shape[1]):
|
| 433 |
+
res[:, j], info = solver(a, b[:, j], **solver_args)
|
| 434 |
+
if info != 0:
|
| 435 |
+
raise ValueError(f"{solver = } returns {info =} for column {j}.")
|
| 436 |
+
return res
|
| 437 |
+
else:
|
| 438 |
+
res, info = solver(a, b, **solver_args)
|
| 439 |
+
if info != 0:
|
| 440 |
+
raise ValueError(f"{solver = } returns {info = }.")
|
| 441 |
+
return res
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def make_ndbspl(points, values, k=3, *, solver=ssl.gcrotmk, **solver_args):
|
| 445 |
+
"""Construct an interpolating NdBspline.
|
| 446 |
+
|
| 447 |
+
Parameters
|
| 448 |
+
----------
|
| 449 |
+
points : tuple of ndarrays of float, with shapes (m1,), ... (mN,)
|
| 450 |
+
The points defining the regular grid in N dimensions. The points in
|
| 451 |
+
each dimension (i.e. every element of the `points` tuple) must be
|
| 452 |
+
strictly ascending or descending.
|
| 453 |
+
values : ndarray of float, shape (m1, ..., mN, ...)
|
| 454 |
+
The data on the regular grid in n dimensions.
|
| 455 |
+
k : int, optional
|
| 456 |
+
The spline degree. Must be odd. Default is cubic, k=3
|
| 457 |
+
solver : a `scipy.sparse.linalg` solver (iterative or direct), optional.
|
| 458 |
+
An iterative solver from `scipy.sparse.linalg` or a direct one,
|
| 459 |
+
`sparse.sparse.linalg.spsolve`.
|
| 460 |
+
Used to solve the sparse linear system
|
| 461 |
+
``design_matrix @ coefficients = rhs`` for the coefficients.
|
| 462 |
+
Default is `scipy.sparse.linalg.gcrotmk`
|
| 463 |
+
solver_args : dict, optional
|
| 464 |
+
Additional arguments for the solver. The call signature is
|
| 465 |
+
``solver(csr_array, rhs_vector, **solver_args)``
|
| 466 |
+
|
| 467 |
+
Returns
|
| 468 |
+
-------
|
| 469 |
+
spl : NdBSpline object
|
| 470 |
+
|
| 471 |
+
Notes
|
| 472 |
+
-----
|
| 473 |
+
Boundary conditions are not-a-knot in all dimensions.
|
| 474 |
+
"""
|
| 475 |
+
ndim = len(points)
|
| 476 |
+
xi_shape = tuple(len(x) for x in points)
|
| 477 |
+
|
| 478 |
+
try:
|
| 479 |
+
len(k)
|
| 480 |
+
except TypeError:
|
| 481 |
+
# make k a tuple
|
| 482 |
+
k = (k,)*ndim
|
| 483 |
+
|
| 484 |
+
for d, point in enumerate(points):
|
| 485 |
+
numpts = len(np.atleast_1d(point))
|
| 486 |
+
if numpts <= k[d]:
|
| 487 |
+
raise ValueError(f"There are {numpts} points in dimension {d},"
|
| 488 |
+
f" but order {k[d]} requires at least "
|
| 489 |
+
f" {k[d]+1} points per dimension.")
|
| 490 |
+
|
| 491 |
+
t = tuple(_not_a_knot(np.asarray(points[d], dtype=float), k[d])
|
| 492 |
+
for d in range(ndim))
|
| 493 |
+
xvals = np.asarray([xv for xv in itertools.product(*points)], dtype=float)
|
| 494 |
+
|
| 495 |
+
# construct the colocation matrix
|
| 496 |
+
matr = NdBSpline.design_matrix(xvals, t, k)
|
| 497 |
+
|
| 498 |
+
# Remove zeros from the sparse matrix
|
| 499 |
+
# If k=1, then solve() doesn't take long enough for this to help
|
| 500 |
+
if k[0] >= 3:
|
| 501 |
+
matr.eliminate_zeros()
|
| 502 |
+
|
| 503 |
+
# Solve for the coefficients given `values`.
|
| 504 |
+
# Trailing dimensions: first ndim dimensions are data, the rest are batch
|
| 505 |
+
# dimensions, so stack `values` into a 2D array for `spsolve` to undestand.
|
| 506 |
+
v_shape = values.shape
|
| 507 |
+
vals_shape = (prod(v_shape[:ndim]), prod(v_shape[ndim:]))
|
| 508 |
+
vals = values.reshape(vals_shape)
|
| 509 |
+
|
| 510 |
+
if solver != ssl.spsolve:
|
| 511 |
+
solver = functools.partial(_iter_solve, solver=solver)
|
| 512 |
+
if "atol" not in solver_args:
|
| 513 |
+
# avoid a DeprecationWarning, grumble grumble
|
| 514 |
+
solver_args["atol"] = 1e-6
|
| 515 |
+
|
| 516 |
+
coef = solver(matr, vals, **solver_args)
|
| 517 |
+
coef = coef.reshape(xi_shape + v_shape[ndim:])
|
| 518 |
+
return NdBSpline(t, coef, k)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_ndgriddata.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Convenience interface to N-D interpolation
|
| 3 |
+
|
| 4 |
+
.. versionadded:: 0.9
|
| 5 |
+
|
| 6 |
+
"""
|
| 7 |
+
import numpy as np
|
| 8 |
+
from ._interpnd import (LinearNDInterpolator, NDInterpolatorBase,
|
| 9 |
+
CloughTocher2DInterpolator, _ndim_coords_from_arrays)
|
| 10 |
+
from scipy.spatial import cKDTree
|
| 11 |
+
|
| 12 |
+
__all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator',
|
| 13 |
+
'CloughTocher2DInterpolator']
|
| 14 |
+
|
| 15 |
+
#------------------------------------------------------------------------------
|
| 16 |
+
# Nearest-neighbor interpolation
|
| 17 |
+
#------------------------------------------------------------------------------
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class NearestNDInterpolator(NDInterpolatorBase):
|
| 21 |
+
"""Nearest-neighbor interpolator in N > 1 dimensions.
|
| 22 |
+
|
| 23 |
+
Methods
|
| 24 |
+
-------
|
| 25 |
+
__call__
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
x : (npoints, ndims) 2-D ndarray of floats
|
| 30 |
+
Data point coordinates.
|
| 31 |
+
y : (npoints, ...) N-D ndarray of float or complex
|
| 32 |
+
Data values. The length of `y` along the first axis must be equal to
|
| 33 |
+
the length of `x`.
|
| 34 |
+
rescale : boolean, optional
|
| 35 |
+
Rescale points to unit cube before performing interpolation.
|
| 36 |
+
This is useful if some of the input dimensions have
|
| 37 |
+
incommensurable units and differ by many orders of magnitude.
|
| 38 |
+
|
| 39 |
+
.. versionadded:: 0.14.0
|
| 40 |
+
tree_options : dict, optional
|
| 41 |
+
Options passed to the underlying ``cKDTree``.
|
| 42 |
+
|
| 43 |
+
.. versionadded:: 0.17.0
|
| 44 |
+
|
| 45 |
+
See Also
|
| 46 |
+
--------
|
| 47 |
+
griddata :
|
| 48 |
+
Interpolate unstructured D-D data.
|
| 49 |
+
LinearNDInterpolator :
|
| 50 |
+
Piecewise linear interpolator in N dimensions.
|
| 51 |
+
CloughTocher2DInterpolator :
|
| 52 |
+
Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
|
| 53 |
+
interpn : Interpolation on a regular grid or rectilinear grid.
|
| 54 |
+
RegularGridInterpolator : Interpolator on a regular or rectilinear grid
|
| 55 |
+
in arbitrary dimensions (`interpn` wraps this
|
| 56 |
+
class).
|
| 57 |
+
|
| 58 |
+
Notes
|
| 59 |
+
-----
|
| 60 |
+
Uses ``scipy.spatial.cKDTree``
|
| 61 |
+
|
| 62 |
+
.. note:: For data on a regular grid use `interpn` instead.
|
| 63 |
+
|
| 64 |
+
Examples
|
| 65 |
+
--------
|
| 66 |
+
We can interpolate values on a 2D plane:
|
| 67 |
+
|
| 68 |
+
>>> from scipy.interpolate import NearestNDInterpolator
|
| 69 |
+
>>> import numpy as np
|
| 70 |
+
>>> import matplotlib.pyplot as plt
|
| 71 |
+
>>> rng = np.random.default_rng()
|
| 72 |
+
>>> x = rng.random(10) - 0.5
|
| 73 |
+
>>> y = rng.random(10) - 0.5
|
| 74 |
+
>>> z = np.hypot(x, y)
|
| 75 |
+
>>> X = np.linspace(min(x), max(x))
|
| 76 |
+
>>> Y = np.linspace(min(y), max(y))
|
| 77 |
+
>>> X, Y = np.meshgrid(X, Y) # 2D grid for interpolation
|
| 78 |
+
>>> interp = NearestNDInterpolator(list(zip(x, y)), z)
|
| 79 |
+
>>> Z = interp(X, Y)
|
| 80 |
+
>>> plt.pcolormesh(X, Y, Z, shading='auto')
|
| 81 |
+
>>> plt.plot(x, y, "ok", label="input point")
|
| 82 |
+
>>> plt.legend()
|
| 83 |
+
>>> plt.colorbar()
|
| 84 |
+
>>> plt.axis("equal")
|
| 85 |
+
>>> plt.show()
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(self, x, y, rescale=False, tree_options=None):
|
| 90 |
+
NDInterpolatorBase.__init__(self, x, y, rescale=rescale,
|
| 91 |
+
need_contiguous=False,
|
| 92 |
+
need_values=False)
|
| 93 |
+
if tree_options is None:
|
| 94 |
+
tree_options = dict()
|
| 95 |
+
self.tree = cKDTree(self.points, **tree_options)
|
| 96 |
+
self.values = np.asarray(y)
|
| 97 |
+
|
| 98 |
+
def __call__(self, *args, **query_options):
|
| 99 |
+
"""
|
| 100 |
+
Evaluate interpolator at given points.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
x1, x2, ... xn : array-like of float
|
| 105 |
+
Points where to interpolate data at.
|
| 106 |
+
x1, x2, ... xn can be array-like of float with broadcastable shape.
|
| 107 |
+
or x1 can be array-like of float with shape ``(..., ndim)``
|
| 108 |
+
**query_options
|
| 109 |
+
This allows ``eps``, ``p``, ``distance_upper_bound``, and ``workers``
|
| 110 |
+
being passed to the cKDTree's query function to be explicitly set.
|
| 111 |
+
See `scipy.spatial.cKDTree.query` for an overview of the different options.
|
| 112 |
+
|
| 113 |
+
.. versionadded:: 1.12.0
|
| 114 |
+
|
| 115 |
+
"""
|
| 116 |
+
# For the sake of enabling subclassing, NDInterpolatorBase._set_xi performs
|
| 117 |
+
# some operations which are not required by NearestNDInterpolator.__call__,
|
| 118 |
+
# hence here we operate on xi directly, without calling a parent class function.
|
| 119 |
+
xi = _ndim_coords_from_arrays(args, ndim=self.points.shape[1])
|
| 120 |
+
xi = self._check_call_shape(xi)
|
| 121 |
+
xi = self._scale_x(xi)
|
| 122 |
+
|
| 123 |
+
# We need to handle two important cases:
|
| 124 |
+
# (1) the case where xi has trailing dimensions (..., ndim), and
|
| 125 |
+
# (2) the case where y has trailing dimensions
|
| 126 |
+
# We will first flatten xi to deal with case (1),
|
| 127 |
+
# do the computation in flattened array while retaining y's dimensionality,
|
| 128 |
+
# and then reshape the interpolated values back to match xi's shape.
|
| 129 |
+
|
| 130 |
+
# Flatten xi for the query
|
| 131 |
+
xi_flat = xi.reshape(-1, xi.shape[-1])
|
| 132 |
+
original_shape = xi.shape
|
| 133 |
+
flattened_shape = xi_flat.shape
|
| 134 |
+
|
| 135 |
+
# if distance_upper_bound is set to not be infinite,
|
| 136 |
+
# then we need to consider the case where cKDtree
|
| 137 |
+
# does not find any points within distance_upper_bound to return.
|
| 138 |
+
# It marks those points as having infinte distance, which is what will be used
|
| 139 |
+
# below to mask the array and return only the points that were deemed
|
| 140 |
+
# to have a close enough neighbor to return something useful.
|
| 141 |
+
dist, i = self.tree.query(xi_flat, **query_options)
|
| 142 |
+
valid_mask = np.isfinite(dist)
|
| 143 |
+
|
| 144 |
+
# create a holder interp_values array and fill with nans.
|
| 145 |
+
if self.values.ndim > 1:
|
| 146 |
+
interp_shape = flattened_shape[:-1] + self.values.shape[1:]
|
| 147 |
+
else:
|
| 148 |
+
interp_shape = flattened_shape[:-1]
|
| 149 |
+
|
| 150 |
+
if np.issubdtype(self.values.dtype, np.complexfloating):
|
| 151 |
+
interp_values = np.full(interp_shape, np.nan, dtype=self.values.dtype)
|
| 152 |
+
else:
|
| 153 |
+
interp_values = np.full(interp_shape, np.nan)
|
| 154 |
+
|
| 155 |
+
interp_values[valid_mask] = self.values[i[valid_mask], ...]
|
| 156 |
+
|
| 157 |
+
if self.values.ndim > 1:
|
| 158 |
+
new_shape = original_shape[:-1] + self.values.shape[1:]
|
| 159 |
+
else:
|
| 160 |
+
new_shape = original_shape[:-1]
|
| 161 |
+
interp_values = interp_values.reshape(new_shape)
|
| 162 |
+
|
| 163 |
+
return interp_values
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
#------------------------------------------------------------------------------
|
| 167 |
+
# Convenience interface function
|
| 168 |
+
#------------------------------------------------------------------------------
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def griddata(points, values, xi, method='linear', fill_value=np.nan,
|
| 172 |
+
rescale=False):
|
| 173 |
+
"""
|
| 174 |
+
Convenience function for interpolating unstructured data in multiple dimensions.
|
| 175 |
+
|
| 176 |
+
Parameters
|
| 177 |
+
----------
|
| 178 |
+
points : 2-D ndarray of floats with shape (n, D), or length D tuple of 1-D ndarrays with shape (n,).
|
| 179 |
+
Data point coordinates.
|
| 180 |
+
values : ndarray of float or complex, shape (n,)
|
| 181 |
+
Data values.
|
| 182 |
+
xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape.
|
| 183 |
+
Points at which to interpolate data.
|
| 184 |
+
method : {'linear', 'nearest', 'cubic'}, optional
|
| 185 |
+
Method of interpolation. One of
|
| 186 |
+
|
| 187 |
+
``nearest``
|
| 188 |
+
return the value at the data point closest to
|
| 189 |
+
the point of interpolation. See `NearestNDInterpolator` for
|
| 190 |
+
more details.
|
| 191 |
+
|
| 192 |
+
``linear``
|
| 193 |
+
tessellate the input point set to N-D
|
| 194 |
+
simplices, and interpolate linearly on each simplex. See
|
| 195 |
+
`LinearNDInterpolator` for more details.
|
| 196 |
+
|
| 197 |
+
``cubic`` (1-D)
|
| 198 |
+
return the value determined from a cubic
|
| 199 |
+
spline.
|
| 200 |
+
|
| 201 |
+
``cubic`` (2-D)
|
| 202 |
+
return the value determined from a
|
| 203 |
+
piecewise cubic, continuously differentiable (C1), and
|
| 204 |
+
approximately curvature-minimizing polynomial surface. See
|
| 205 |
+
`CloughTocher2DInterpolator` for more details.
|
| 206 |
+
fill_value : float, optional
|
| 207 |
+
Value used to fill in for requested points outside of the
|
| 208 |
+
convex hull of the input points. If not provided, then the
|
| 209 |
+
default is ``nan``. This option has no effect for the
|
| 210 |
+
'nearest' method.
|
| 211 |
+
rescale : bool, optional
|
| 212 |
+
Rescale points to unit cube before performing interpolation.
|
| 213 |
+
This is useful if some of the input dimensions have
|
| 214 |
+
incommensurable units and differ by many orders of magnitude.
|
| 215 |
+
|
| 216 |
+
.. versionadded:: 0.14.0
|
| 217 |
+
|
| 218 |
+
Returns
|
| 219 |
+
-------
|
| 220 |
+
ndarray
|
| 221 |
+
Array of interpolated values.
|
| 222 |
+
|
| 223 |
+
See Also
|
| 224 |
+
--------
|
| 225 |
+
LinearNDInterpolator :
|
| 226 |
+
Piecewise linear interpolator in N dimensions.
|
| 227 |
+
NearestNDInterpolator :
|
| 228 |
+
Nearest-neighbor interpolator in N dimensions.
|
| 229 |
+
CloughTocher2DInterpolator :
|
| 230 |
+
Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
|
| 231 |
+
interpn : Interpolation on a regular grid or rectilinear grid.
|
| 232 |
+
RegularGridInterpolator : Interpolator on a regular or rectilinear grid
|
| 233 |
+
in arbitrary dimensions (`interpn` wraps this
|
| 234 |
+
class).
|
| 235 |
+
|
| 236 |
+
Notes
|
| 237 |
+
-----
|
| 238 |
+
|
| 239 |
+
.. versionadded:: 0.9
|
| 240 |
+
|
| 241 |
+
.. note:: For data on a regular grid use `interpn` instead.
|
| 242 |
+
|
| 243 |
+
Examples
|
| 244 |
+
--------
|
| 245 |
+
|
| 246 |
+
Suppose we want to interpolate the 2-D function
|
| 247 |
+
|
| 248 |
+
>>> import numpy as np
|
| 249 |
+
>>> def func(x, y):
|
| 250 |
+
... return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
|
| 251 |
+
|
| 252 |
+
on a grid in [0, 1]x[0, 1]
|
| 253 |
+
|
| 254 |
+
>>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
|
| 255 |
+
|
| 256 |
+
but we only know its values at 1000 data points:
|
| 257 |
+
|
| 258 |
+
>>> rng = np.random.default_rng()
|
| 259 |
+
>>> points = rng.random((1000, 2))
|
| 260 |
+
>>> values = func(points[:,0], points[:,1])
|
| 261 |
+
|
| 262 |
+
This can be done with `griddata` -- below we try out all of the
|
| 263 |
+
interpolation methods:
|
| 264 |
+
|
| 265 |
+
>>> from scipy.interpolate import griddata
|
| 266 |
+
>>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
|
| 267 |
+
>>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
|
| 268 |
+
>>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')
|
| 269 |
+
|
| 270 |
+
One can see that the exact result is reproduced by all of the
|
| 271 |
+
methods to some degree, but for this smooth function the piecewise
|
| 272 |
+
cubic interpolant gives the best results:
|
| 273 |
+
|
| 274 |
+
>>> import matplotlib.pyplot as plt
|
| 275 |
+
>>> plt.subplot(221)
|
| 276 |
+
>>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
|
| 277 |
+
>>> plt.plot(points[:,0], points[:,1], 'k.', ms=1)
|
| 278 |
+
>>> plt.title('Original')
|
| 279 |
+
>>> plt.subplot(222)
|
| 280 |
+
>>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
|
| 281 |
+
>>> plt.title('Nearest')
|
| 282 |
+
>>> plt.subplot(223)
|
| 283 |
+
>>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
|
| 284 |
+
>>> plt.title('Linear')
|
| 285 |
+
>>> plt.subplot(224)
|
| 286 |
+
>>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
|
| 287 |
+
>>> plt.title('Cubic')
|
| 288 |
+
>>> plt.gcf().set_size_inches(6, 6)
|
| 289 |
+
>>> plt.show()
|
| 290 |
+
|
| 291 |
+
""" # numpy/numpydoc#87 # noqa: E501
|
| 292 |
+
|
| 293 |
+
points = _ndim_coords_from_arrays(points)
|
| 294 |
+
|
| 295 |
+
if points.ndim < 2:
|
| 296 |
+
ndim = points.ndim
|
| 297 |
+
else:
|
| 298 |
+
ndim = points.shape[-1]
|
| 299 |
+
|
| 300 |
+
if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
|
| 301 |
+
from ._interpolate import interp1d
|
| 302 |
+
points = points.ravel()
|
| 303 |
+
if isinstance(xi, tuple):
|
| 304 |
+
if len(xi) != 1:
|
| 305 |
+
raise ValueError("invalid number of dimensions in xi")
|
| 306 |
+
xi, = xi
|
| 307 |
+
# Sort points/values together, necessary as input for interp1d
|
| 308 |
+
idx = np.argsort(points)
|
| 309 |
+
points = points[idx]
|
| 310 |
+
values = values[idx]
|
| 311 |
+
if method == 'nearest':
|
| 312 |
+
fill_value = 'extrapolate'
|
| 313 |
+
ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
|
| 314 |
+
fill_value=fill_value)
|
| 315 |
+
return ip(xi)
|
| 316 |
+
elif method == 'nearest':
|
| 317 |
+
ip = NearestNDInterpolator(points, values, rescale=rescale)
|
| 318 |
+
return ip(xi)
|
| 319 |
+
elif method == 'linear':
|
| 320 |
+
ip = LinearNDInterpolator(points, values, fill_value=fill_value,
|
| 321 |
+
rescale=rescale)
|
| 322 |
+
return ip(xi)
|
| 323 |
+
elif method == 'cubic' and ndim == 2:
|
| 324 |
+
ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,
|
| 325 |
+
rescale=rescale)
|
| 326 |
+
return ip(xi)
|
| 327 |
+
else:
|
| 328 |
+
raise ValueError(
|
| 329 |
+
f"Unknown interpolation method {method!r} for {ndim} dimensional data"
|
| 330 |
+
)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_pade.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy import zeros, asarray, eye, poly1d, hstack, r_
|
| 2 |
+
from scipy import linalg
|
| 3 |
+
|
| 4 |
+
__all__ = ["pade"]
|
| 5 |
+
|
| 6 |
+
def pade(an, m, n=None):
|
| 7 |
+
"""
|
| 8 |
+
Return Pade approximation to a polynomial as the ratio of two polynomials.
|
| 9 |
+
|
| 10 |
+
Parameters
|
| 11 |
+
----------
|
| 12 |
+
an : (N,) array_like
|
| 13 |
+
Taylor series coefficients.
|
| 14 |
+
m : int
|
| 15 |
+
The order of the returned approximating polynomial `q`.
|
| 16 |
+
n : int, optional
|
| 17 |
+
The order of the returned approximating polynomial `p`. By default,
|
| 18 |
+
the order is ``len(an)-1-m``.
|
| 19 |
+
|
| 20 |
+
Returns
|
| 21 |
+
-------
|
| 22 |
+
p, q : Polynomial class
|
| 23 |
+
The Pade approximation of the polynomial defined by `an` is
|
| 24 |
+
``p(x)/q(x)``.
|
| 25 |
+
|
| 26 |
+
Examples
|
| 27 |
+
--------
|
| 28 |
+
>>> import numpy as np
|
| 29 |
+
>>> from scipy.interpolate import pade
|
| 30 |
+
>>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0]
|
| 31 |
+
>>> p, q = pade(e_exp, 2)
|
| 32 |
+
|
| 33 |
+
>>> e_exp.reverse()
|
| 34 |
+
>>> e_poly = np.poly1d(e_exp)
|
| 35 |
+
|
| 36 |
+
Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)``
|
| 37 |
+
|
| 38 |
+
>>> e_poly(1)
|
| 39 |
+
2.7166666666666668
|
| 40 |
+
|
| 41 |
+
>>> p(1)/q(1)
|
| 42 |
+
2.7179487179487181
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
an = asarray(an)
|
| 46 |
+
if n is None:
|
| 47 |
+
n = len(an) - 1 - m
|
| 48 |
+
if n < 0:
|
| 49 |
+
raise ValueError("Order of q <m> must be smaller than len(an)-1.")
|
| 50 |
+
if n < 0:
|
| 51 |
+
raise ValueError("Order of p <n> must be greater than 0.")
|
| 52 |
+
N = m + n
|
| 53 |
+
if N > len(an)-1:
|
| 54 |
+
raise ValueError("Order of q+p <m+n> must be smaller than len(an).")
|
| 55 |
+
an = an[:N+1]
|
| 56 |
+
Akj = eye(N+1, n+1, dtype=an.dtype)
|
| 57 |
+
Bkj = zeros((N+1, m), dtype=an.dtype)
|
| 58 |
+
for row in range(1, m+1):
|
| 59 |
+
Bkj[row,:row] = -(an[:row])[::-1]
|
| 60 |
+
for row in range(m+1, N+1):
|
| 61 |
+
Bkj[row,:] = -(an[row-m:row])[::-1]
|
| 62 |
+
C = hstack((Akj, Bkj))
|
| 63 |
+
pq = linalg.solve(C, an)
|
| 64 |
+
p = pq[:n+1]
|
| 65 |
+
q = r_[1.0, pq[n+1:]]
|
| 66 |
+
return poly1d(p[::-1]), poly1d(q[::-1])
|
| 67 |
+
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_polyint.py
ADDED
|
@@ -0,0 +1,1029 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from types import GenericAlias
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy.special import factorial
|
| 6 |
+
from scipy._lib._util import (_asarray_validated, float_factorial, check_random_state,
|
| 7 |
+
_transition_to_rng)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = ["KroghInterpolator", "krogh_interpolate",
|
| 11 |
+
"BarycentricInterpolator", "barycentric_interpolate",
|
| 12 |
+
"approximate_taylor_polynomial"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _isscalar(x):
|
| 16 |
+
"""Check whether x is if a scalar type, or 0-dim"""
|
| 17 |
+
return np.isscalar(x) or hasattr(x, 'shape') and x.shape == ()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class _Interpolator1D:
|
| 21 |
+
"""
|
| 22 |
+
Common features in univariate interpolation
|
| 23 |
+
|
| 24 |
+
Deal with input data type and interpolation axis rolling. The
|
| 25 |
+
actual interpolator can assume the y-data is of shape (n, r) where
|
| 26 |
+
`n` is the number of x-points, and `r` the number of variables,
|
| 27 |
+
and use self.dtype as the y-data type.
|
| 28 |
+
|
| 29 |
+
Attributes
|
| 30 |
+
----------
|
| 31 |
+
_y_axis
|
| 32 |
+
Axis along which the interpolation goes in the original array
|
| 33 |
+
_y_extra_shape
|
| 34 |
+
Additional trailing shape of the input arrays, excluding
|
| 35 |
+
the interpolation axis.
|
| 36 |
+
dtype
|
| 37 |
+
Dtype of the y-data arrays. Can be set via _set_dtype, which
|
| 38 |
+
forces it to be float or complex.
|
| 39 |
+
|
| 40 |
+
Methods
|
| 41 |
+
-------
|
| 42 |
+
__call__
|
| 43 |
+
_prepare_x
|
| 44 |
+
_finish_y
|
| 45 |
+
_reshape_yi
|
| 46 |
+
_set_yi
|
| 47 |
+
_set_dtype
|
| 48 |
+
_evaluate
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
__slots__ = ('_y_axis', '_y_extra_shape', 'dtype')
|
| 53 |
+
|
| 54 |
+
# generic type compatibility with scipy-stubs
|
| 55 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 56 |
+
|
| 57 |
+
def __init__(self, xi=None, yi=None, axis=None):
|
| 58 |
+
self._y_axis = axis
|
| 59 |
+
self._y_extra_shape = None
|
| 60 |
+
self.dtype = None
|
| 61 |
+
if yi is not None:
|
| 62 |
+
self._set_yi(yi, xi=xi, axis=axis)
|
| 63 |
+
|
| 64 |
+
def __call__(self, x):
|
| 65 |
+
"""
|
| 66 |
+
Evaluate the interpolant
|
| 67 |
+
|
| 68 |
+
Parameters
|
| 69 |
+
----------
|
| 70 |
+
x : array_like
|
| 71 |
+
Point or points at which to evaluate the interpolant.
|
| 72 |
+
|
| 73 |
+
Returns
|
| 74 |
+
-------
|
| 75 |
+
y : array_like
|
| 76 |
+
Interpolated values. Shape is determined by replacing
|
| 77 |
+
the interpolation axis in the original array with the shape of `x`.
|
| 78 |
+
|
| 79 |
+
Notes
|
| 80 |
+
-----
|
| 81 |
+
Input values `x` must be convertible to `float` values like `int`
|
| 82 |
+
or `float`.
|
| 83 |
+
|
| 84 |
+
"""
|
| 85 |
+
x, x_shape = self._prepare_x(x)
|
| 86 |
+
y = self._evaluate(x)
|
| 87 |
+
return self._finish_y(y, x_shape)
|
| 88 |
+
|
| 89 |
+
def _evaluate(self, x):
|
| 90 |
+
"""
|
| 91 |
+
Actually evaluate the value of the interpolator.
|
| 92 |
+
"""
|
| 93 |
+
raise NotImplementedError()
|
| 94 |
+
|
| 95 |
+
def _prepare_x(self, x):
|
| 96 |
+
"""Reshape input x array to 1-D"""
|
| 97 |
+
x = _asarray_validated(x, check_finite=False, as_inexact=True)
|
| 98 |
+
x_shape = x.shape
|
| 99 |
+
return x.ravel(), x_shape
|
| 100 |
+
|
| 101 |
+
def _finish_y(self, y, x_shape):
|
| 102 |
+
"""Reshape interpolated y back to an N-D array similar to initial y"""
|
| 103 |
+
y = y.reshape(x_shape + self._y_extra_shape)
|
| 104 |
+
if self._y_axis != 0 and x_shape != ():
|
| 105 |
+
nx = len(x_shape)
|
| 106 |
+
ny = len(self._y_extra_shape)
|
| 107 |
+
s = (list(range(nx, nx + self._y_axis))
|
| 108 |
+
+ list(range(nx)) + list(range(nx+self._y_axis, nx+ny)))
|
| 109 |
+
y = y.transpose(s)
|
| 110 |
+
return y
|
| 111 |
+
|
| 112 |
+
def _reshape_yi(self, yi, check=False):
|
| 113 |
+
yi = np.moveaxis(np.asarray(yi), self._y_axis, 0)
|
| 114 |
+
if check and yi.shape[1:] != self._y_extra_shape:
|
| 115 |
+
ok_shape = (f"{self._y_extra_shape[-self._y_axis:]!r} + (N,) + "
|
| 116 |
+
f"{self._y_extra_shape[:-self._y_axis]!r}")
|
| 117 |
+
raise ValueError(f"Data must be of shape {ok_shape}")
|
| 118 |
+
return yi.reshape((yi.shape[0], -1))
|
| 119 |
+
|
| 120 |
+
def _set_yi(self, yi, xi=None, axis=None):
|
| 121 |
+
if axis is None:
|
| 122 |
+
axis = self._y_axis
|
| 123 |
+
if axis is None:
|
| 124 |
+
raise ValueError("no interpolation axis specified")
|
| 125 |
+
|
| 126 |
+
yi = np.asarray(yi)
|
| 127 |
+
|
| 128 |
+
shape = yi.shape
|
| 129 |
+
if shape == ():
|
| 130 |
+
shape = (1,)
|
| 131 |
+
if xi is not None and shape[axis] != len(xi):
|
| 132 |
+
raise ValueError("x and y arrays must be equal in length along "
|
| 133 |
+
"interpolation axis.")
|
| 134 |
+
|
| 135 |
+
self._y_axis = (axis % yi.ndim)
|
| 136 |
+
self._y_extra_shape = yi.shape[:self._y_axis] + yi.shape[self._y_axis+1:]
|
| 137 |
+
self.dtype = None
|
| 138 |
+
self._set_dtype(yi.dtype)
|
| 139 |
+
|
| 140 |
+
def _set_dtype(self, dtype, union=False):
|
| 141 |
+
if np.issubdtype(dtype, np.complexfloating) \
|
| 142 |
+
or np.issubdtype(self.dtype, np.complexfloating):
|
| 143 |
+
self.dtype = np.complex128
|
| 144 |
+
else:
|
| 145 |
+
if not union or self.dtype != np.complex128:
|
| 146 |
+
self.dtype = np.float64
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class _Interpolator1DWithDerivatives(_Interpolator1D):
|
| 150 |
+
def derivatives(self, x, der=None):
|
| 151 |
+
"""
|
| 152 |
+
Evaluate several derivatives of the polynomial at the point `x`
|
| 153 |
+
|
| 154 |
+
Produce an array of derivatives evaluated at the point `x`.
|
| 155 |
+
|
| 156 |
+
Parameters
|
| 157 |
+
----------
|
| 158 |
+
x : array_like
|
| 159 |
+
Point or points at which to evaluate the derivatives
|
| 160 |
+
der : int or list or None, optional
|
| 161 |
+
How many derivatives to evaluate, or None for all potentially
|
| 162 |
+
nonzero derivatives (that is, a number equal to the number
|
| 163 |
+
of points), or a list of derivatives to evaluate. This number
|
| 164 |
+
includes the function value as the '0th' derivative.
|
| 165 |
+
|
| 166 |
+
Returns
|
| 167 |
+
-------
|
| 168 |
+
d : ndarray
|
| 169 |
+
Array with derivatives; ``d[j]`` contains the jth derivative.
|
| 170 |
+
Shape of ``d[j]`` is determined by replacing the interpolation
|
| 171 |
+
axis in the original array with the shape of `x`.
|
| 172 |
+
|
| 173 |
+
Examples
|
| 174 |
+
--------
|
| 175 |
+
>>> from scipy.interpolate import KroghInterpolator
|
| 176 |
+
>>> KroghInterpolator([0,0,0],[1,2,3]).derivatives(0)
|
| 177 |
+
array([1.0,2.0,3.0])
|
| 178 |
+
>>> KroghInterpolator([0,0,0],[1,2,3]).derivatives([0,0])
|
| 179 |
+
array([[1.0,1.0],
|
| 180 |
+
[2.0,2.0],
|
| 181 |
+
[3.0,3.0]])
|
| 182 |
+
|
| 183 |
+
"""
|
| 184 |
+
x, x_shape = self._prepare_x(x)
|
| 185 |
+
y = self._evaluate_derivatives(x, der)
|
| 186 |
+
|
| 187 |
+
y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)
|
| 188 |
+
if self._y_axis != 0 and x_shape != ():
|
| 189 |
+
nx = len(x_shape)
|
| 190 |
+
ny = len(self._y_extra_shape)
|
| 191 |
+
s = ([0] + list(range(nx+1, nx + self._y_axis+1))
|
| 192 |
+
+ list(range(1, nx+1)) +
|
| 193 |
+
list(range(nx+1+self._y_axis, nx+ny+1)))
|
| 194 |
+
y = y.transpose(s)
|
| 195 |
+
return y
|
| 196 |
+
|
| 197 |
+
def derivative(self, x, der=1):
|
| 198 |
+
"""
|
| 199 |
+
Evaluate a single derivative of the polynomial at the point `x`.
|
| 200 |
+
|
| 201 |
+
Parameters
|
| 202 |
+
----------
|
| 203 |
+
x : array_like
|
| 204 |
+
Point or points at which to evaluate the derivatives
|
| 205 |
+
|
| 206 |
+
der : integer, optional
|
| 207 |
+
Which derivative to evaluate (default: first derivative).
|
| 208 |
+
This number includes the function value as 0th derivative.
|
| 209 |
+
|
| 210 |
+
Returns
|
| 211 |
+
-------
|
| 212 |
+
d : ndarray
|
| 213 |
+
Derivative interpolated at the x-points. Shape of `d` is
|
| 214 |
+
determined by replacing the interpolation axis in the
|
| 215 |
+
original array with the shape of `x`.
|
| 216 |
+
|
| 217 |
+
Notes
|
| 218 |
+
-----
|
| 219 |
+
This may be computed by evaluating all derivatives up to the desired
|
| 220 |
+
one (using self.derivatives()) and then discarding the rest.
|
| 221 |
+
|
| 222 |
+
"""
|
| 223 |
+
x, x_shape = self._prepare_x(x)
|
| 224 |
+
y = self._evaluate_derivatives(x, der+1)
|
| 225 |
+
return self._finish_y(y[der], x_shape)
|
| 226 |
+
|
| 227 |
+
def _evaluate_derivatives(self, x, der=None):
|
| 228 |
+
"""
|
| 229 |
+
Actually evaluate the derivatives.
|
| 230 |
+
|
| 231 |
+
Parameters
|
| 232 |
+
----------
|
| 233 |
+
x : array_like
|
| 234 |
+
1D array of points at which to evaluate the derivatives
|
| 235 |
+
der : integer, optional
|
| 236 |
+
The number of derivatives to evaluate, from 'order 0' (der=1)
|
| 237 |
+
to order der-1. If omitted, return all possibly-non-zero
|
| 238 |
+
derivatives, ie 0 to order n-1.
|
| 239 |
+
|
| 240 |
+
Returns
|
| 241 |
+
-------
|
| 242 |
+
d : ndarray
|
| 243 |
+
Array of shape ``(der, x.size, self.yi.shape[1])`` containing
|
| 244 |
+
the derivatives from 0 to der-1
|
| 245 |
+
"""
|
| 246 |
+
raise NotImplementedError()
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class KroghInterpolator(_Interpolator1DWithDerivatives):
|
| 250 |
+
"""Krogh interpolator (C∞ smooth).
|
| 251 |
+
|
| 252 |
+
The polynomial passes through all the pairs ``(xi, yi)``. One may
|
| 253 |
+
additionally specify a number of derivatives at each point `xi`;
|
| 254 |
+
this is done by repeating the value `xi` and specifying the
|
| 255 |
+
derivatives as successive `yi` values.
|
| 256 |
+
|
| 257 |
+
Allows evaluation of the polynomial and all its derivatives.
|
| 258 |
+
For reasons of numerical stability, this function does not compute
|
| 259 |
+
the coefficients of the polynomial, although they can be obtained
|
| 260 |
+
by evaluating all the derivatives.
|
| 261 |
+
|
| 262 |
+
Parameters
|
| 263 |
+
----------
|
| 264 |
+
xi : array_like, shape (npoints, )
|
| 265 |
+
Known x-coordinates. Must be sorted in increasing order.
|
| 266 |
+
yi : array_like, shape (..., npoints, ...)
|
| 267 |
+
Known y-coordinates. When an xi occurs two or more times in
|
| 268 |
+
a row, the corresponding yi's represent derivative values. The length of `yi`
|
| 269 |
+
along the interpolation axis must be equal to the length of `xi`. Use the
|
| 270 |
+
`axis` parameter to select the correct axis.
|
| 271 |
+
axis : int, optional
|
| 272 |
+
Axis in the `yi` array corresponding to the x-coordinate values. Defaults to
|
| 273 |
+
``axis=0``.
|
| 274 |
+
|
| 275 |
+
Notes
|
| 276 |
+
-----
|
| 277 |
+
Be aware that the algorithms implemented here are not necessarily
|
| 278 |
+
the most numerically stable known. Moreover, even in a world of
|
| 279 |
+
exact computation, unless the x coordinates are chosen very
|
| 280 |
+
carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
|
| 281 |
+
polynomial interpolation itself is a very ill-conditioned process
|
| 282 |
+
due to the Runge phenomenon. In general, even with well-chosen
|
| 283 |
+
x values, degrees higher than about thirty cause problems with
|
| 284 |
+
numerical instability in this code.
|
| 285 |
+
|
| 286 |
+
Based on [1]_.
|
| 287 |
+
|
| 288 |
+
References
|
| 289 |
+
----------
|
| 290 |
+
.. [1] Krogh, "Efficient Algorithms for Polynomial Interpolation
|
| 291 |
+
and Numerical Differentiation", 1970.
|
| 292 |
+
|
| 293 |
+
Examples
|
| 294 |
+
--------
|
| 295 |
+
To produce a polynomial that is zero at 0 and 1 and has
|
| 296 |
+
derivative 2 at 0, call
|
| 297 |
+
|
| 298 |
+
>>> from scipy.interpolate import KroghInterpolator
|
| 299 |
+
>>> KroghInterpolator([0,0,1],[0,2,0])
|
| 300 |
+
|
| 301 |
+
This constructs the quadratic :math:`2x^2-2x`. The derivative condition
|
| 302 |
+
is indicated by the repeated zero in the `xi` array; the corresponding
|
| 303 |
+
yi values are 0, the function value, and 2, the derivative value.
|
| 304 |
+
|
| 305 |
+
For another example, given `xi`, `yi`, and a derivative `ypi` for each
|
| 306 |
+
point, appropriate arrays can be constructed as:
|
| 307 |
+
|
| 308 |
+
>>> import numpy as np
|
| 309 |
+
>>> rng = np.random.default_rng()
|
| 310 |
+
>>> xi = np.linspace(0, 1, 5)
|
| 311 |
+
>>> yi, ypi = rng.random((2, 5))
|
| 312 |
+
>>> xi_k, yi_k = np.repeat(xi, 2), np.ravel(np.dstack((yi,ypi)))
|
| 313 |
+
>>> KroghInterpolator(xi_k, yi_k)
|
| 314 |
+
|
| 315 |
+
To produce a vector-valued polynomial, supply a higher-dimensional
|
| 316 |
+
array for `yi`:
|
| 317 |
+
|
| 318 |
+
>>> KroghInterpolator([0,1],[[2,3],[4,5]])
|
| 319 |
+
|
| 320 |
+
This constructs a linear polynomial giving (2,3) at 0 and (4,5) at 1.
|
| 321 |
+
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
def __init__(self, xi, yi, axis=0):
|
| 325 |
+
super().__init__(xi, yi, axis)
|
| 326 |
+
|
| 327 |
+
self.xi = np.asarray(xi)
|
| 328 |
+
self.yi = self._reshape_yi(yi)
|
| 329 |
+
self.n, self.r = self.yi.shape
|
| 330 |
+
|
| 331 |
+
if (deg := self.xi.size) > 30:
|
| 332 |
+
warnings.warn(f"{deg} degrees provided, degrees higher than about"
|
| 333 |
+
" thirty cause problems with numerical instability "
|
| 334 |
+
"with 'KroghInterpolator'", stacklevel=2)
|
| 335 |
+
|
| 336 |
+
c = np.zeros((self.n+1, self.r), dtype=self.dtype)
|
| 337 |
+
c[0] = self.yi[0]
|
| 338 |
+
Vk = np.zeros((self.n, self.r), dtype=self.dtype)
|
| 339 |
+
for k in range(1, self.n):
|
| 340 |
+
s = 0
|
| 341 |
+
while s <= k and xi[k-s] == xi[k]:
|
| 342 |
+
s += 1
|
| 343 |
+
s -= 1
|
| 344 |
+
Vk[0] = self.yi[k]/float_factorial(s)
|
| 345 |
+
for i in range(k-s):
|
| 346 |
+
if xi[i] == xi[k]:
|
| 347 |
+
raise ValueError("Elements of `xi` can't be equal.")
|
| 348 |
+
if s == 0:
|
| 349 |
+
Vk[i+1] = (c[i]-Vk[i])/(xi[i]-xi[k])
|
| 350 |
+
else:
|
| 351 |
+
Vk[i+1] = (Vk[i+1]-Vk[i])/(xi[i]-xi[k])
|
| 352 |
+
c[k] = Vk[k-s]
|
| 353 |
+
self.c = c
|
| 354 |
+
|
| 355 |
+
def _evaluate(self, x):
|
| 356 |
+
pi = 1
|
| 357 |
+
p = np.zeros((len(x), self.r), dtype=self.dtype)
|
| 358 |
+
p += self.c[0,np.newaxis,:]
|
| 359 |
+
for k in range(1, self.n):
|
| 360 |
+
w = x - self.xi[k-1]
|
| 361 |
+
pi = w*pi
|
| 362 |
+
p += pi[:,np.newaxis] * self.c[k]
|
| 363 |
+
return p
|
| 364 |
+
|
| 365 |
+
def _evaluate_derivatives(self, x, der=None):
|
| 366 |
+
n = self.n
|
| 367 |
+
r = self.r
|
| 368 |
+
|
| 369 |
+
if der is None:
|
| 370 |
+
der = self.n
|
| 371 |
+
|
| 372 |
+
pi = np.zeros((n, len(x)))
|
| 373 |
+
w = np.zeros((n, len(x)))
|
| 374 |
+
pi[0] = 1
|
| 375 |
+
p = np.zeros((len(x), self.r), dtype=self.dtype)
|
| 376 |
+
p += self.c[0, np.newaxis, :]
|
| 377 |
+
|
| 378 |
+
for k in range(1, n):
|
| 379 |
+
w[k-1] = x - self.xi[k-1]
|
| 380 |
+
pi[k] = w[k-1] * pi[k-1]
|
| 381 |
+
p += pi[k, :, np.newaxis] * self.c[k]
|
| 382 |
+
|
| 383 |
+
cn = np.zeros((max(der, n+1), len(x), r), dtype=self.dtype)
|
| 384 |
+
cn[:n+1, :, :] += self.c[:n+1, np.newaxis, :]
|
| 385 |
+
cn[0] = p
|
| 386 |
+
for k in range(1, n):
|
| 387 |
+
for i in range(1, n-k+1):
|
| 388 |
+
pi[i] = w[k+i-1]*pi[i-1] + pi[i]
|
| 389 |
+
cn[k] = cn[k] + pi[i, :, np.newaxis]*cn[k+i]
|
| 390 |
+
cn[k] *= float_factorial(k)
|
| 391 |
+
|
| 392 |
+
cn[n, :, :] = 0
|
| 393 |
+
return cn[:der]
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def krogh_interpolate(xi, yi, x, der=0, axis=0):
|
| 397 |
+
"""Convenience function for Krogh interpolation.
|
| 398 |
+
|
| 399 |
+
See `KroghInterpolator` for more details.
|
| 400 |
+
|
| 401 |
+
Parameters
|
| 402 |
+
----------
|
| 403 |
+
xi : array_like
|
| 404 |
+
Interpolation points (known x-coordinates).
|
| 405 |
+
yi : array_like
|
| 406 |
+
Known y-coordinates, of shape ``(xi.size, R)``. Interpreted as
|
| 407 |
+
vectors of length R, or scalars if R=1.
|
| 408 |
+
x : array_like
|
| 409 |
+
Point or points at which to evaluate the derivatives.
|
| 410 |
+
der : int or list or None, optional
|
| 411 |
+
How many derivatives to evaluate, or None for all potentially
|
| 412 |
+
nonzero derivatives (that is, a number equal to the number
|
| 413 |
+
of points), or a list of derivatives to evaluate. This number
|
| 414 |
+
includes the function value as the '0th' derivative.
|
| 415 |
+
axis : int, optional
|
| 416 |
+
Axis in the `yi` array corresponding to the x-coordinate values.
|
| 417 |
+
|
| 418 |
+
Returns
|
| 419 |
+
-------
|
| 420 |
+
d : ndarray
|
| 421 |
+
If the interpolator's values are R-D then the
|
| 422 |
+
returned array will be the number of derivatives by N by R.
|
| 423 |
+
If `x` is a scalar, the middle dimension will be dropped; if
|
| 424 |
+
the `yi` are scalars then the last dimension will be dropped.
|
| 425 |
+
|
| 426 |
+
See Also
|
| 427 |
+
--------
|
| 428 |
+
KroghInterpolator : Krogh interpolator
|
| 429 |
+
|
| 430 |
+
Notes
|
| 431 |
+
-----
|
| 432 |
+
Construction of the interpolating polynomial is a relatively expensive
|
| 433 |
+
process. If you want to evaluate it repeatedly consider using the class
|
| 434 |
+
KroghInterpolator (which is what this function uses).
|
| 435 |
+
|
| 436 |
+
Examples
|
| 437 |
+
--------
|
| 438 |
+
We can interpolate 2D observed data using Krogh interpolation:
|
| 439 |
+
|
| 440 |
+
>>> import numpy as np
|
| 441 |
+
>>> import matplotlib.pyplot as plt
|
| 442 |
+
>>> from scipy.interpolate import krogh_interpolate
|
| 443 |
+
>>> x_observed = np.linspace(0.0, 10.0, 11)
|
| 444 |
+
>>> y_observed = np.sin(x_observed)
|
| 445 |
+
>>> x = np.linspace(min(x_observed), max(x_observed), num=100)
|
| 446 |
+
>>> y = krogh_interpolate(x_observed, y_observed, x)
|
| 447 |
+
>>> plt.plot(x_observed, y_observed, "o", label="observation")
|
| 448 |
+
>>> plt.plot(x, y, label="krogh interpolation")
|
| 449 |
+
>>> plt.legend()
|
| 450 |
+
>>> plt.show()
|
| 451 |
+
"""
|
| 452 |
+
|
| 453 |
+
P = KroghInterpolator(xi, yi, axis=axis)
|
| 454 |
+
if der == 0:
|
| 455 |
+
return P(x)
|
| 456 |
+
elif _isscalar(der):
|
| 457 |
+
return P.derivative(x, der=der)
|
| 458 |
+
else:
|
| 459 |
+
return P.derivatives(x, der=np.amax(der)+1)[der]
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def approximate_taylor_polynomial(f,x,degree,scale,order=None):
|
| 463 |
+
"""
|
| 464 |
+
Estimate the Taylor polynomial of f at x by polynomial fitting.
|
| 465 |
+
|
| 466 |
+
Parameters
|
| 467 |
+
----------
|
| 468 |
+
f : callable
|
| 469 |
+
The function whose Taylor polynomial is sought. Should accept
|
| 470 |
+
a vector of `x` values.
|
| 471 |
+
x : scalar
|
| 472 |
+
The point at which the polynomial is to be evaluated.
|
| 473 |
+
degree : int
|
| 474 |
+
The degree of the Taylor polynomial
|
| 475 |
+
scale : scalar
|
| 476 |
+
The width of the interval to use to evaluate the Taylor polynomial.
|
| 477 |
+
Function values spread over a range this wide are used to fit the
|
| 478 |
+
polynomial. Must be chosen carefully.
|
| 479 |
+
order : int or None, optional
|
| 480 |
+
The order of the polynomial to be used in the fitting; `f` will be
|
| 481 |
+
evaluated ``order+1`` times. If None, use `degree`.
|
| 482 |
+
|
| 483 |
+
Returns
|
| 484 |
+
-------
|
| 485 |
+
p : poly1d instance
|
| 486 |
+
The Taylor polynomial (translated to the origin, so that
|
| 487 |
+
for example p(0)=f(x)).
|
| 488 |
+
|
| 489 |
+
Notes
|
| 490 |
+
-----
|
| 491 |
+
The appropriate choice of "scale" is a trade-off; too large and the
|
| 492 |
+
function differs from its Taylor polynomial too much to get a good
|
| 493 |
+
answer, too small and round-off errors overwhelm the higher-order terms.
|
| 494 |
+
The algorithm used becomes numerically unstable around order 30 even
|
| 495 |
+
under ideal circumstances.
|
| 496 |
+
|
| 497 |
+
Choosing order somewhat larger than degree may improve the higher-order
|
| 498 |
+
terms.
|
| 499 |
+
|
| 500 |
+
Examples
|
| 501 |
+
--------
|
| 502 |
+
We can calculate Taylor approximation polynomials of sin function with
|
| 503 |
+
various degrees:
|
| 504 |
+
|
| 505 |
+
>>> import numpy as np
|
| 506 |
+
>>> import matplotlib.pyplot as plt
|
| 507 |
+
>>> from scipy.interpolate import approximate_taylor_polynomial
|
| 508 |
+
>>> x = np.linspace(-10.0, 10.0, num=100)
|
| 509 |
+
>>> plt.plot(x, np.sin(x), label="sin curve")
|
| 510 |
+
>>> for degree in np.arange(1, 15, step=2):
|
| 511 |
+
... sin_taylor = approximate_taylor_polynomial(np.sin, 0, degree, 1,
|
| 512 |
+
... order=degree + 2)
|
| 513 |
+
... plt.plot(x, sin_taylor(x), label=f"degree={degree}")
|
| 514 |
+
>>> plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left',
|
| 515 |
+
... borderaxespad=0.0, shadow=True)
|
| 516 |
+
>>> plt.tight_layout()
|
| 517 |
+
>>> plt.axis([-10, 10, -10, 10])
|
| 518 |
+
>>> plt.show()
|
| 519 |
+
|
| 520 |
+
"""
|
| 521 |
+
if order is None:
|
| 522 |
+
order = degree
|
| 523 |
+
|
| 524 |
+
n = order+1
|
| 525 |
+
# Choose n points that cluster near the endpoints of the interval in
|
| 526 |
+
# a way that avoids the Runge phenomenon. Ensure, by including the
|
| 527 |
+
# endpoint or not as appropriate, that one point always falls at x
|
| 528 |
+
# exactly.
|
| 529 |
+
xs = scale*np.cos(np.linspace(0,np.pi,n,endpoint=n % 1)) + x
|
| 530 |
+
|
| 531 |
+
P = KroghInterpolator(xs, f(xs))
|
| 532 |
+
d = P.derivatives(x,der=degree+1)
|
| 533 |
+
|
| 534 |
+
return np.poly1d((d/factorial(np.arange(degree+1)))[::-1])
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class BarycentricInterpolator(_Interpolator1DWithDerivatives):
|
| 538 |
+
r"""Barycentric (Lagrange with improved stability) interpolator (C∞ smooth).
|
| 539 |
+
|
| 540 |
+
Constructs a polynomial that passes through a given set of points.
|
| 541 |
+
Allows evaluation of the polynomial and all its derivatives,
|
| 542 |
+
efficient changing of the y-values to be interpolated,
|
| 543 |
+
and updating by adding more x- and y-values. For numerical stability, a barycentric
|
| 544 |
+
representation is used rather than computing the coefficients of the polynomial
|
| 545 |
+
directly.
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
Parameters
|
| 549 |
+
----------
|
| 550 |
+
xi : array_like, shape (npoints, )
|
| 551 |
+
1-D array of x-coordinates of the points the polynomial
|
| 552 |
+
should pass through
|
| 553 |
+
yi : array_like, shape (..., npoints, ...), optional
|
| 554 |
+
N-D array of y-coordinates of the points the polynomial should pass through.
|
| 555 |
+
If None, the y values will be supplied later via the `set_y` method.
|
| 556 |
+
The length of `yi` along the interpolation axis must be equal to the length
|
| 557 |
+
of `xi`. Use the ``axis`` parameter to select correct axis.
|
| 558 |
+
axis : int, optional
|
| 559 |
+
Axis in the yi array corresponding to the x-coordinate values. Defaults
|
| 560 |
+
to ``axis=0``.
|
| 561 |
+
wi : array_like, optional
|
| 562 |
+
The barycentric weights for the chosen interpolation points `xi`.
|
| 563 |
+
If absent or None, the weights will be computed from `xi` (default).
|
| 564 |
+
This allows for the reuse of the weights `wi` if several interpolants
|
| 565 |
+
are being calculated using the same nodes `xi`, without re-computation. This
|
| 566 |
+
also allows for computing the weights explicitly for some choices of
|
| 567 |
+
`xi` (see notes).
|
| 568 |
+
rng : {None, int, `numpy.random.Generator`}, optional
|
| 569 |
+
If `rng` is passed by keyword, types other than `numpy.random.Generator` are
|
| 570 |
+
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
|
| 571 |
+
If `rng` is already a ``Generator`` instance, then the provided instance is
|
| 572 |
+
used. Specify `rng` for repeatable interpolation.
|
| 573 |
+
|
| 574 |
+
If this argument `random_state` is passed by keyword,
|
| 575 |
+
legacy behavior for the argument `random_state` applies:
|
| 576 |
+
|
| 577 |
+
- If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
|
| 578 |
+
singleton is used.
|
| 579 |
+
- If `random_state` is an int, a new ``RandomState`` instance is used,
|
| 580 |
+
seeded with `random_state`.
|
| 581 |
+
- If `random_state` is already a ``Generator`` or ``RandomState`` instance then
|
| 582 |
+
that instance is used.
|
| 583 |
+
|
| 584 |
+
.. versionchanged:: 1.15.0
|
| 585 |
+
As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
|
| 586 |
+
transition from use of `numpy.random.RandomState` to
|
| 587 |
+
`numpy.random.Generator` this keyword was changed from `random_state` to `rng`.
|
| 588 |
+
For an interim period, both keywords will continue to work (only specify
|
| 589 |
+
one of them). After the interim period using the `random_state` keyword will emit
|
| 590 |
+
warnings. The behavior of the `random_state` and `rng` keywords is outlined above.
|
| 591 |
+
|
| 592 |
+
Notes
|
| 593 |
+
-----
|
| 594 |
+
This method is a variant of Lagrange polynomial interpolation [1]_ based on [2]_.
|
| 595 |
+
Instead of using Lagrange's or Newton's formula, the polynomial is represented by
|
| 596 |
+
the barycentric formula
|
| 597 |
+
|
| 598 |
+
.. math::
|
| 599 |
+
|
| 600 |
+
p(x) =
|
| 601 |
+
\frac{\sum_{i=1}^m\ w_i y_i / (x - x_i)}{\sum_{i=1}^m w_i / (x - x_i)},
|
| 602 |
+
|
| 603 |
+
where :math:`w_i` are the barycentric weights computed with the general formula
|
| 604 |
+
|
| 605 |
+
.. math::
|
| 606 |
+
|
| 607 |
+
w_i = \left( \prod_{k \neq i} x_i - x_k \right)^{-1}.
|
| 608 |
+
|
| 609 |
+
This is the same barycentric form used by `AAA` and `FloaterHormannInterpolator`.
|
| 610 |
+
However, in contrast, the weights :math:`w_i` are defined such that
|
| 611 |
+
:math:`p(x)` is a polynomial rather than a rational function.
|
| 612 |
+
|
| 613 |
+
The barycentric representation avoids many of the problems associated with
|
| 614 |
+
polynomial interpolation caused by floating-point arithmetic. However, it does not
|
| 615 |
+
avoid issues that are intrinsic to polynomial interpolation. Namely, if the
|
| 616 |
+
x-coordinates are equally spaced, then the weights can be computed explicitly using
|
| 617 |
+
the formula from [2]_
|
| 618 |
+
|
| 619 |
+
.. math::
|
| 620 |
+
|
| 621 |
+
w_i = (-1)^i {n \choose i},
|
| 622 |
+
|
| 623 |
+
where :math:`n` is the number of x-coordinates. As noted in [2]_, this means that
|
| 624 |
+
for large :math:`n` the weights vary by exponentially large factors, leading to the
|
| 625 |
+
Runge phenomenon.
|
| 626 |
+
|
| 627 |
+
To avoid this ill-conditioning, the x-coordinates should be clustered at the
|
| 628 |
+
endpoints of the interval. An excellent choice of points on the interval
|
| 629 |
+
:math:`[a,b]` are Chebyshev points of the second kind
|
| 630 |
+
|
| 631 |
+
.. math::
|
| 632 |
+
|
| 633 |
+
x_i = \frac{a + b}{2} + \frac{a - b}{2}\cos(i\pi/n).
|
| 634 |
+
|
| 635 |
+
in which case the weights can be computed explicitly as
|
| 636 |
+
|
| 637 |
+
.. math::
|
| 638 |
+
|
| 639 |
+
w_i = \begin{cases}
|
| 640 |
+
(-1)^i/2 & i = 0,n \\
|
| 641 |
+
(-1)^i & \text{otherwise}
|
| 642 |
+
\end{cases}.
|
| 643 |
+
|
| 644 |
+
See [2]_ for more infomation. Note that for large :math:`n`, computing the weights
|
| 645 |
+
explicitly (see examples) will be faster than the generic formula.
|
| 646 |
+
|
| 647 |
+
References
|
| 648 |
+
----------
|
| 649 |
+
.. [1] https://en.wikipedia.org/wiki/Lagrange_polynomial
|
| 650 |
+
.. [2] Jean-Paul Berrut and Lloyd N. Trefethen, "Barycentric Lagrange
|
| 651 |
+
Interpolation", SIAM Review 2004 46:3, 501-517
|
| 652 |
+
:doi:`10.1137/S0036144502417715`
|
| 653 |
+
|
| 654 |
+
Examples
|
| 655 |
+
--------
|
| 656 |
+
To produce a quintic barycentric interpolant approximating the function
|
| 657 |
+
:math:`\sin x`, and its first four derivatives, using six randomly-spaced
|
| 658 |
+
nodes in :math:`(0, \pi/2)`:
|
| 659 |
+
|
| 660 |
+
>>> import numpy as np
|
| 661 |
+
>>> import matplotlib.pyplot as plt
|
| 662 |
+
>>> from scipy.interpolate import BarycentricInterpolator
|
| 663 |
+
>>> rng = np.random.default_rng()
|
| 664 |
+
>>> xi = rng.random(6) * np.pi/2
|
| 665 |
+
>>> f, f_d1, f_d2, f_d3, f_d4 = np.sin, np.cos, lambda x: -np.sin(x), lambda x: -np.cos(x), np.sin
|
| 666 |
+
>>> P = BarycentricInterpolator(xi, f(xi), random_state=rng)
|
| 667 |
+
>>> fig, axs = plt.subplots(5, 1, sharex=True, layout='constrained', figsize=(7,10))
|
| 668 |
+
>>> x = np.linspace(0, np.pi, 100)
|
| 669 |
+
>>> axs[0].plot(x, P(x), 'r:', x, f(x), 'k--', xi, f(xi), 'xk')
|
| 670 |
+
>>> axs[1].plot(x, P.derivative(x), 'r:', x, f_d1(x), 'k--', xi, f_d1(xi), 'xk')
|
| 671 |
+
>>> axs[2].plot(x, P.derivative(x, 2), 'r:', x, f_d2(x), 'k--', xi, f_d2(xi), 'xk')
|
| 672 |
+
>>> axs[3].plot(x, P.derivative(x, 3), 'r:', x, f_d3(x), 'k--', xi, f_d3(xi), 'xk')
|
| 673 |
+
>>> axs[4].plot(x, P.derivative(x, 4), 'r:', x, f_d4(x), 'k--', xi, f_d4(xi), 'xk')
|
| 674 |
+
>>> axs[0].set_xlim(0, np.pi)
|
| 675 |
+
>>> axs[4].set_xlabel(r"$x$")
|
| 676 |
+
>>> axs[4].set_xticks([i * np.pi / 4 for i in range(5)],
|
| 677 |
+
... ["0", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$", r"$\frac{3\pi}{4}$", r"$\pi$"])
|
| 678 |
+
>>> for ax, label in zip(axs, ("$f(x)$", "$f'(x)$", "$f''(x)$", "$f^{(3)}(x)$", "$f^{(4)}(x)$")):
|
| 679 |
+
... ax.set_ylabel(label)
|
| 680 |
+
>>> labels = ['Interpolation nodes', 'True function $f$', 'Barycentric interpolation']
|
| 681 |
+
>>> axs[0].legend(axs[0].get_lines()[::-1], labels, bbox_to_anchor=(0., 1.02, 1., .102),
|
| 682 |
+
... loc='lower left', ncols=3, mode="expand", borderaxespad=0., frameon=False)
|
| 683 |
+
>>> plt.show()
|
| 684 |
+
|
| 685 |
+
Next, we show how using Chebyshev points of the second kind avoids the
|
| 686 |
+
Runge phenomenon. In this example, we also compute the weights explicitly.
|
| 687 |
+
|
| 688 |
+
>>> n = 20
|
| 689 |
+
>>> def f(x): return np.abs(x) + 0.5*x - x**2
|
| 690 |
+
>>> i = np.arange(n)
|
| 691 |
+
>>> x_cheb = np.cos(i*np.pi/(n - 1)) # Chebyshev points on [-1, 1]
|
| 692 |
+
>>> w_i_cheb = (-1.)**i # Explicit formula for weights of Chebyshev points
|
| 693 |
+
>>> w_i_cheb[[0, -1]] /= 2
|
| 694 |
+
>>> p_cheb = BarycentricInterpolator(x_cheb, f(x_cheb), wi=w_i_cheb)
|
| 695 |
+
>>> x_equi = np.linspace(-1, 1, n)
|
| 696 |
+
>>> p_equi = BarycentricInterpolator(x_equi, f(x_equi))
|
| 697 |
+
>>> xx = np.linspace(-1, 1, 1000)
|
| 698 |
+
>>> fig, ax = plt.subplots()
|
| 699 |
+
>>> ax.plot(xx, f(xx), label="Original Function")
|
| 700 |
+
>>> ax.plot(xx, p_cheb(xx), "--", label="Chebshev Points")
|
| 701 |
+
>>> ax.plot(xx, p_equi(xx), "--", label="Equally Spaced Points")
|
| 702 |
+
>>> ax.set(xlabel="$x$", ylabel="$f(x)$", xlim=[-1, 1])
|
| 703 |
+
>>> ax.legend()
|
| 704 |
+
>>> plt.show()
|
| 705 |
+
|
| 706 |
+
""" # numpy/numpydoc#87 # noqa: E501
|
| 707 |
+
|
| 708 |
+
@_transition_to_rng("random_state", replace_doc=False)
|
| 709 |
+
def __init__(self, xi, yi=None, axis=0, *, wi=None, rng=None):
|
| 710 |
+
super().__init__(xi, yi, axis)
|
| 711 |
+
|
| 712 |
+
rng = check_random_state(rng)
|
| 713 |
+
|
| 714 |
+
self.xi = np.asarray(xi, dtype=np.float64)
|
| 715 |
+
self.set_yi(yi)
|
| 716 |
+
self.n = len(self.xi)
|
| 717 |
+
|
| 718 |
+
# cache derivative object to avoid re-computing the weights with every call.
|
| 719 |
+
self._diff_cij = None
|
| 720 |
+
|
| 721 |
+
if wi is not None:
|
| 722 |
+
self.wi = wi
|
| 723 |
+
else:
|
| 724 |
+
# See page 510 of Berrut and Trefethen 2004 for an explanation of the
|
| 725 |
+
# capacity scaling and the suggestion of using a random permutation of
|
| 726 |
+
# the input factors.
|
| 727 |
+
# At the moment, the permutation is not performed for xi that are
|
| 728 |
+
# appended later through the add_xi interface. It's not clear to me how
|
| 729 |
+
# to implement that and it seems that most situations that require
|
| 730 |
+
# these numerical stability improvements will be able to provide all
|
| 731 |
+
# the points to the constructor.
|
| 732 |
+
self._inv_capacity = 4.0 / (np.max(self.xi) - np.min(self.xi))
|
| 733 |
+
permute = rng.permutation(self.n, )
|
| 734 |
+
inv_permute = np.zeros(self.n, dtype=np.int32)
|
| 735 |
+
inv_permute[permute] = np.arange(self.n)
|
| 736 |
+
self.wi = np.zeros(self.n)
|
| 737 |
+
|
| 738 |
+
for i in range(self.n):
|
| 739 |
+
dist = self._inv_capacity * (self.xi[i] - self.xi[permute])
|
| 740 |
+
dist[inv_permute[i]] = 1.0
|
| 741 |
+
prod = np.prod(dist)
|
| 742 |
+
if prod == 0.0:
|
| 743 |
+
raise ValueError("Interpolation points xi must be"
|
| 744 |
+
" distinct.")
|
| 745 |
+
self.wi[i] = 1.0 / prod
|
| 746 |
+
|
| 747 |
+
def set_yi(self, yi, axis=None):
|
| 748 |
+
"""
|
| 749 |
+
Update the y values to be interpolated
|
| 750 |
+
|
| 751 |
+
The barycentric interpolation algorithm requires the calculation
|
| 752 |
+
of weights, but these depend only on the `xi`. The `yi` can be changed
|
| 753 |
+
at any time.
|
| 754 |
+
|
| 755 |
+
Parameters
|
| 756 |
+
----------
|
| 757 |
+
yi : array_like
|
| 758 |
+
The y-coordinates of the points the polynomial will pass through.
|
| 759 |
+
If None, the y values must be supplied later.
|
| 760 |
+
axis : int, optional
|
| 761 |
+
Axis in the `yi` array corresponding to the x-coordinate values.
|
| 762 |
+
|
| 763 |
+
"""
|
| 764 |
+
if yi is None:
|
| 765 |
+
self.yi = None
|
| 766 |
+
return
|
| 767 |
+
self._set_yi(yi, xi=self.xi, axis=axis)
|
| 768 |
+
self.yi = self._reshape_yi(yi)
|
| 769 |
+
self.n, self.r = self.yi.shape
|
| 770 |
+
self._diff_baryint = None
|
| 771 |
+
|
| 772 |
+
def add_xi(self, xi, yi=None):
|
| 773 |
+
"""
|
| 774 |
+
Add more x values to the set to be interpolated
|
| 775 |
+
|
| 776 |
+
The barycentric interpolation algorithm allows easy updating by
|
| 777 |
+
adding more points for the polynomial to pass through.
|
| 778 |
+
|
| 779 |
+
Parameters
|
| 780 |
+
----------
|
| 781 |
+
xi : array_like
|
| 782 |
+
The x coordinates of the points that the polynomial should pass
|
| 783 |
+
through.
|
| 784 |
+
yi : array_like, optional
|
| 785 |
+
The y coordinates of the points the polynomial should pass through.
|
| 786 |
+
Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is
|
| 787 |
+
vector-valued.
|
| 788 |
+
If `yi` is not given, the y values will be supplied later. `yi`
|
| 789 |
+
should be given if and only if the interpolator has y values
|
| 790 |
+
specified.
|
| 791 |
+
|
| 792 |
+
Notes
|
| 793 |
+
-----
|
| 794 |
+
The new points added by `add_xi` are not randomly permuted
|
| 795 |
+
so there is potential for numerical instability,
|
| 796 |
+
especially for a large number of points. If this
|
| 797 |
+
happens, please reconstruct interpolation from scratch instead.
|
| 798 |
+
"""
|
| 799 |
+
if yi is not None:
|
| 800 |
+
if self.yi is None:
|
| 801 |
+
raise ValueError("No previous yi value to update!")
|
| 802 |
+
yi = self._reshape_yi(yi, check=True)
|
| 803 |
+
self.yi = np.vstack((self.yi,yi))
|
| 804 |
+
else:
|
| 805 |
+
if self.yi is not None:
|
| 806 |
+
raise ValueError("No update to yi provided!")
|
| 807 |
+
old_n = self.n
|
| 808 |
+
self.xi = np.concatenate((self.xi,xi))
|
| 809 |
+
self.n = len(self.xi)
|
| 810 |
+
self.wi **= -1
|
| 811 |
+
old_wi = self.wi
|
| 812 |
+
self.wi = np.zeros(self.n)
|
| 813 |
+
self.wi[:old_n] = old_wi
|
| 814 |
+
for j in range(old_n, self.n):
|
| 815 |
+
self.wi[:j] *= self._inv_capacity * (self.xi[j]-self.xi[:j])
|
| 816 |
+
self.wi[j] = np.multiply.reduce(
|
| 817 |
+
self._inv_capacity * (self.xi[:j]-self.xi[j])
|
| 818 |
+
)
|
| 819 |
+
self.wi **= -1
|
| 820 |
+
self._diff_cij = None
|
| 821 |
+
self._diff_baryint = None
|
| 822 |
+
|
| 823 |
+
def __call__(self, x):
|
| 824 |
+
"""Evaluate the interpolating polynomial at the points x
|
| 825 |
+
|
| 826 |
+
Parameters
|
| 827 |
+
----------
|
| 828 |
+
x : array_like
|
| 829 |
+
Point or points at which to evaluate the interpolant.
|
| 830 |
+
|
| 831 |
+
Returns
|
| 832 |
+
-------
|
| 833 |
+
y : array_like
|
| 834 |
+
Interpolated values. Shape is determined by replacing
|
| 835 |
+
the interpolation axis in the original array with the shape of `x`.
|
| 836 |
+
|
| 837 |
+
Notes
|
| 838 |
+
-----
|
| 839 |
+
Currently the code computes an outer product between `x` and the
|
| 840 |
+
weights, that is, it constructs an intermediate array of size
|
| 841 |
+
``(N, len(x))``, where N is the degree of the polynomial.
|
| 842 |
+
"""
|
| 843 |
+
return _Interpolator1D.__call__(self, x)
|
| 844 |
+
|
| 845 |
+
def _evaluate(self, x):
|
| 846 |
+
if x.size == 0:
|
| 847 |
+
p = np.zeros((0, self.r), dtype=self.dtype)
|
| 848 |
+
else:
|
| 849 |
+
c = x[..., np.newaxis] - self.xi
|
| 850 |
+
z = c == 0
|
| 851 |
+
c[z] = 1
|
| 852 |
+
c = self.wi / c
|
| 853 |
+
with np.errstate(divide='ignore'):
|
| 854 |
+
p = np.dot(c, self.yi) / np.sum(c, axis=-1)[..., np.newaxis]
|
| 855 |
+
# Now fix where x==some xi
|
| 856 |
+
r = np.nonzero(z)
|
| 857 |
+
if len(r) == 1: # evaluation at a scalar
|
| 858 |
+
if len(r[0]) > 0: # equals one of the points
|
| 859 |
+
p = self.yi[r[0][0]]
|
| 860 |
+
else:
|
| 861 |
+
p[r[:-1]] = self.yi[r[-1]]
|
| 862 |
+
return p
|
| 863 |
+
|
| 864 |
+
def derivative(self, x, der=1):
|
| 865 |
+
"""
|
| 866 |
+
Evaluate a single derivative of the polynomial at the point x.
|
| 867 |
+
|
| 868 |
+
Parameters
|
| 869 |
+
----------
|
| 870 |
+
x : array_like
|
| 871 |
+
Point or points at which to evaluate the derivatives
|
| 872 |
+
der : integer, optional
|
| 873 |
+
Which derivative to evaluate (default: first derivative).
|
| 874 |
+
This number includes the function value as 0th derivative.
|
| 875 |
+
|
| 876 |
+
Returns
|
| 877 |
+
-------
|
| 878 |
+
d : ndarray
|
| 879 |
+
Derivative interpolated at the x-points. Shape of `d` is
|
| 880 |
+
determined by replacing the interpolation axis in the
|
| 881 |
+
original array with the shape of `x`.
|
| 882 |
+
"""
|
| 883 |
+
x, x_shape = self._prepare_x(x)
|
| 884 |
+
y = self._evaluate_derivatives(x, der+1, all_lower=False)
|
| 885 |
+
return self._finish_y(y, x_shape)
|
| 886 |
+
|
| 887 |
+
def _evaluate_derivatives(self, x, der=None, all_lower=True):
|
| 888 |
+
# NB: der here is not the order of the highest derivative;
|
| 889 |
+
# instead, it is the size of the derivatives matrix that
|
| 890 |
+
# would be returned with all_lower=True, including the
|
| 891 |
+
# '0th' derivative (the undifferentiated function).
|
| 892 |
+
# E.g. to evaluate the 5th derivative alone, call
|
| 893 |
+
# _evaluate_derivatives(x, der=6, all_lower=False).
|
| 894 |
+
|
| 895 |
+
if (not all_lower) and (x.size == 0 or self.r == 0):
|
| 896 |
+
return np.zeros((0, self.r), dtype=self.dtype)
|
| 897 |
+
|
| 898 |
+
if (not all_lower) and der == 1:
|
| 899 |
+
return self._evaluate(x)
|
| 900 |
+
|
| 901 |
+
if (not all_lower) and (der > self.n):
|
| 902 |
+
return np.zeros((len(x), self.r), dtype=self.dtype)
|
| 903 |
+
|
| 904 |
+
if der is None:
|
| 905 |
+
der = self.n
|
| 906 |
+
|
| 907 |
+
if all_lower and (x.size == 0 or self.r == 0):
|
| 908 |
+
return np.zeros((der, len(x), self.r), dtype=self.dtype)
|
| 909 |
+
|
| 910 |
+
if self._diff_cij is None:
|
| 911 |
+
# c[i,j] = xi[i] - xi[j]
|
| 912 |
+
c = self.xi[:, np.newaxis] - self.xi
|
| 913 |
+
|
| 914 |
+
# avoid division by 0 (diagonal entries are so far zero by construction)
|
| 915 |
+
np.fill_diagonal(c, 1)
|
| 916 |
+
|
| 917 |
+
# c[i,j] = (w[j] / w[i]) / (xi[i] - xi[j]) (equation 9.4)
|
| 918 |
+
c = self.wi/ (c * self.wi[..., np.newaxis])
|
| 919 |
+
|
| 920 |
+
# fill in correct diagonal entries: each column sums to 0
|
| 921 |
+
np.fill_diagonal(c, 0)
|
| 922 |
+
|
| 923 |
+
# calculate diagonal
|
| 924 |
+
# c[j,j] = -sum_{i != j} c[i,j] (equation 9.5)
|
| 925 |
+
d = -c.sum(axis=1)
|
| 926 |
+
# c[i,j] = l_j(x_i)
|
| 927 |
+
np.fill_diagonal(c, d)
|
| 928 |
+
|
| 929 |
+
self._diff_cij = c
|
| 930 |
+
|
| 931 |
+
if self._diff_baryint is None:
|
| 932 |
+
# initialise and cache derivative interpolator and cijs;
|
| 933 |
+
# reuse weights wi (which depend only on interpolation points xi),
|
| 934 |
+
# to avoid unnecessary re-computation
|
| 935 |
+
self._diff_baryint = BarycentricInterpolator(xi=self.xi,
|
| 936 |
+
yi=self._diff_cij @ self.yi,
|
| 937 |
+
wi=self.wi)
|
| 938 |
+
self._diff_baryint._diff_cij = self._diff_cij
|
| 939 |
+
|
| 940 |
+
if all_lower:
|
| 941 |
+
# assemble matrix of derivatives from order 0 to order der-1,
|
| 942 |
+
# in the format required by _Interpolator1DWithDerivatives.
|
| 943 |
+
cn = np.zeros((der, len(x), self.r), dtype=self.dtype)
|
| 944 |
+
for d in range(der):
|
| 945 |
+
cn[d, :, :] = self._evaluate_derivatives(x, d+1, all_lower=False)
|
| 946 |
+
return cn
|
| 947 |
+
|
| 948 |
+
# recursively evaluate only the derivative requested
|
| 949 |
+
return self._diff_baryint._evaluate_derivatives(x, der-1, all_lower=False)
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
def barycentric_interpolate(xi, yi, x, axis=0, *, der=0, rng=None):
|
| 953 |
+
"""Convenience function for barycentric interpolation.
|
| 954 |
+
|
| 955 |
+
Constructs a polynomial that passes through a given set of points,
|
| 956 |
+
then evaluates the polynomial. For reasons of numerical stability,
|
| 957 |
+
this function does not compute the coefficients of the polynomial.
|
| 958 |
+
|
| 959 |
+
This function uses a "barycentric interpolation" method that treats
|
| 960 |
+
the problem as a special case of rational function interpolation.
|
| 961 |
+
This algorithm is quite stable, numerically, but even in a world of
|
| 962 |
+
exact computation, unless the `x` coordinates are chosen very
|
| 963 |
+
carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
|
| 964 |
+
polynomial interpolation itself is a very ill-conditioned process
|
| 965 |
+
due to the Runge phenomenon.
|
| 966 |
+
|
| 967 |
+
Parameters
|
| 968 |
+
----------
|
| 969 |
+
xi : array_like
|
| 970 |
+
1-D array of x coordinates of the points the polynomial should
|
| 971 |
+
pass through
|
| 972 |
+
yi : array_like
|
| 973 |
+
The y coordinates of the points the polynomial should pass through.
|
| 974 |
+
x : scalar or array_like
|
| 975 |
+
Point or points at which to evaluate the interpolant.
|
| 976 |
+
axis : int, optional
|
| 977 |
+
Axis in the `yi` array corresponding to the x-coordinate values.
|
| 978 |
+
der : int or list or None, optional
|
| 979 |
+
How many derivatives to evaluate, or None for all potentially
|
| 980 |
+
nonzero derivatives (that is, a number equal to the number
|
| 981 |
+
of points), or a list of derivatives to evaluate. This number
|
| 982 |
+
includes the function value as the '0th' derivative.
|
| 983 |
+
rng : `numpy.random.Generator`, optional
|
| 984 |
+
Pseudorandom number generator state. When `rng` is None, a new
|
| 985 |
+
`numpy.random.Generator` is created using entropy from the
|
| 986 |
+
operating system. Types other than `numpy.random.Generator` are
|
| 987 |
+
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
|
| 988 |
+
|
| 989 |
+
Returns
|
| 990 |
+
-------
|
| 991 |
+
y : scalar or array_like
|
| 992 |
+
Interpolated values. Shape is determined by replacing
|
| 993 |
+
the interpolation axis in the original array with the shape of `x`.
|
| 994 |
+
|
| 995 |
+
See Also
|
| 996 |
+
--------
|
| 997 |
+
BarycentricInterpolator : Barycentric interpolator
|
| 998 |
+
|
| 999 |
+
Notes
|
| 1000 |
+
-----
|
| 1001 |
+
Construction of the interpolation weights is a relatively slow process.
|
| 1002 |
+
If you want to call this many times with the same xi (but possibly
|
| 1003 |
+
varying yi or x) you should use the class `BarycentricInterpolator`.
|
| 1004 |
+
This is what this function uses internally.
|
| 1005 |
+
|
| 1006 |
+
Examples
|
| 1007 |
+
--------
|
| 1008 |
+
We can interpolate 2D observed data using barycentric interpolation:
|
| 1009 |
+
|
| 1010 |
+
>>> import numpy as np
|
| 1011 |
+
>>> import matplotlib.pyplot as plt
|
| 1012 |
+
>>> from scipy.interpolate import barycentric_interpolate
|
| 1013 |
+
>>> x_observed = np.linspace(0.0, 10.0, 11)
|
| 1014 |
+
>>> y_observed = np.sin(x_observed)
|
| 1015 |
+
>>> x = np.linspace(min(x_observed), max(x_observed), num=100)
|
| 1016 |
+
>>> y = barycentric_interpolate(x_observed, y_observed, x)
|
| 1017 |
+
>>> plt.plot(x_observed, y_observed, "o", label="observation")
|
| 1018 |
+
>>> plt.plot(x, y, label="barycentric interpolation")
|
| 1019 |
+
>>> plt.legend()
|
| 1020 |
+
>>> plt.show()
|
| 1021 |
+
|
| 1022 |
+
"""
|
| 1023 |
+
P = BarycentricInterpolator(xi, yi, axis=axis, rng=rng)
|
| 1024 |
+
if der == 0:
|
| 1025 |
+
return P(x)
|
| 1026 |
+
elif _isscalar(der):
|
| 1027 |
+
return P.derivative(x, der=der)
|
| 1028 |
+
else:
|
| 1029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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""rbf - Radial basis functions for interpolation/smoothing scattered N-D data.
|
| 2 |
+
|
| 3 |
+
Written by John Travers <jtravs@gmail.com>, February 2007
|
| 4 |
+
Based closely on Matlab code by Alex Chirokov
|
| 5 |
+
Additional, large, improvements by Robert Hetland
|
| 6 |
+
Some additional alterations by Travis Oliphant
|
| 7 |
+
Interpolation with multi-dimensional target domain by Josua Sassen
|
| 8 |
+
|
| 9 |
+
Permission to use, modify, and distribute this software is given under the
|
| 10 |
+
terms of the SciPy (BSD style) license. See LICENSE.txt that came with
|
| 11 |
+
this distribution for specifics.
|
| 12 |
+
|
| 13 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
| 14 |
+
|
| 15 |
+
Copyright (c) 2006-2007, Robert Hetland <hetland@tamu.edu>
|
| 16 |
+
Copyright (c) 2007, John Travers <jtravs@gmail.com>
|
| 17 |
+
|
| 18 |
+
Redistribution and use in source and binary forms, with or without
|
| 19 |
+
modification, are permitted provided that the following conditions are
|
| 20 |
+
met:
|
| 21 |
+
|
| 22 |
+
* Redistributions of source code must retain the above copyright
|
| 23 |
+
notice, this list of conditions and the following disclaimer.
|
| 24 |
+
|
| 25 |
+
* Redistributions in binary form must reproduce the above
|
| 26 |
+
copyright notice, this list of conditions and the following
|
| 27 |
+
disclaimer in the documentation and/or other materials provided
|
| 28 |
+
with the distribution.
|
| 29 |
+
|
| 30 |
+
* Neither the name of Robert Hetland nor the names of any
|
| 31 |
+
contributors may be used to endorse or promote products derived
|
| 32 |
+
from this software without specific prior written permission.
|
| 33 |
+
|
| 34 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 35 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 36 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 37 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 38 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 39 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 40 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 41 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 42 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 43 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 44 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 45 |
+
"""
|
| 46 |
+
import numpy as np
|
| 47 |
+
|
| 48 |
+
from scipy import linalg
|
| 49 |
+
from scipy.special import xlogy
|
| 50 |
+
from scipy.spatial.distance import cdist, pdist, squareform
|
| 51 |
+
from scipy._lib._array_api import xp_capabilities
|
| 52 |
+
|
| 53 |
+
__all__ = ['Rbf']
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@xp_capabilities(out_of_scope=True)
|
| 57 |
+
class Rbf:
|
| 58 |
+
"""
|
| 59 |
+
Rbf(*args, **kwargs)
|
| 60 |
+
|
| 61 |
+
Class for radial basis function interpolation of functions from
|
| 62 |
+
N-D scattered data to an M-D domain (legacy).
|
| 63 |
+
|
| 64 |
+
.. legacy:: class
|
| 65 |
+
|
| 66 |
+
`Rbf` is legacy code, for new usage please use `RBFInterpolator`
|
| 67 |
+
instead.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
*args : arrays
|
| 72 |
+
x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes
|
| 73 |
+
and d is the array of values at the nodes
|
| 74 |
+
function : str or callable, optional
|
| 75 |
+
The radial basis function, based on the radius, r, given by the norm
|
| 76 |
+
(default is Euclidean distance); the default is 'multiquadric'::
|
| 77 |
+
|
| 78 |
+
'multiquadric': sqrt((r/self.epsilon)**2 + 1)
|
| 79 |
+
'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1)
|
| 80 |
+
'gaussian': exp(-(r/self.epsilon)**2)
|
| 81 |
+
'linear': r
|
| 82 |
+
'cubic': r**3
|
| 83 |
+
'quintic': r**5
|
| 84 |
+
'thin_plate': r**2 * log(r)
|
| 85 |
+
|
| 86 |
+
If callable, then it must take 2 arguments (self, r). The epsilon
|
| 87 |
+
parameter will be available as self.epsilon. Other keyword
|
| 88 |
+
arguments passed in will be available as well.
|
| 89 |
+
|
| 90 |
+
epsilon : float, optional
|
| 91 |
+
Adjustable constant for gaussian or multiquadrics functions
|
| 92 |
+
- defaults to approximate average distance between nodes (which is
|
| 93 |
+
a good start).
|
| 94 |
+
smooth : float, optional
|
| 95 |
+
Values greater than zero increase the smoothness of the
|
| 96 |
+
approximation. 0 is for interpolation (default), the function will
|
| 97 |
+
always go through the nodal points in this case.
|
| 98 |
+
norm : str, callable, optional
|
| 99 |
+
A function that returns the 'distance' between two points, with
|
| 100 |
+
inputs as arrays of positions (x, y, z, ...), and an output as an
|
| 101 |
+
array of distance. E.g., the default: 'euclidean', such that the result
|
| 102 |
+
is a matrix of the distances from each point in ``x1`` to each point in
|
| 103 |
+
``x2``. For more options, see documentation of
|
| 104 |
+
`scipy.spatial.distances.cdist`.
|
| 105 |
+
mode : str, optional
|
| 106 |
+
Mode of the interpolation, can be '1-D' (default) or 'N-D'. When it is
|
| 107 |
+
'1-D' the data `d` will be considered as 1-D and flattened
|
| 108 |
+
internally. When it is 'N-D' the data `d` is assumed to be an array of
|
| 109 |
+
shape (n_samples, m), where m is the dimension of the target domain.
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
Attributes
|
| 113 |
+
----------
|
| 114 |
+
N : int
|
| 115 |
+
The number of data points (as determined by the input arrays).
|
| 116 |
+
di : ndarray
|
| 117 |
+
The 1-D array of data values at each of the data coordinates `xi`.
|
| 118 |
+
xi : ndarray
|
| 119 |
+
The 2-D array of data coordinates.
|
| 120 |
+
function : str or callable
|
| 121 |
+
The radial basis function. See description under Parameters.
|
| 122 |
+
epsilon : float
|
| 123 |
+
Parameter used by gaussian or multiquadrics functions. See Parameters.
|
| 124 |
+
smooth : float
|
| 125 |
+
Smoothing parameter. See description under Parameters.
|
| 126 |
+
norm : str or callable
|
| 127 |
+
The distance function. See description under Parameters.
|
| 128 |
+
mode : str
|
| 129 |
+
Mode of the interpolation. See description under Parameters.
|
| 130 |
+
nodes : ndarray
|
| 131 |
+
A 1-D array of node values for the interpolation.
|
| 132 |
+
A : internal property, do not use
|
| 133 |
+
|
| 134 |
+
See Also
|
| 135 |
+
--------
|
| 136 |
+
RBFInterpolator
|
| 137 |
+
|
| 138 |
+
Examples
|
| 139 |
+
--------
|
| 140 |
+
>>> import numpy as np
|
| 141 |
+
>>> from scipy.interpolate import Rbf
|
| 142 |
+
>>> rng = np.random.default_rng()
|
| 143 |
+
>>> x, y, z, d = rng.random((4, 50))
|
| 144 |
+
>>> rbfi = Rbf(x, y, z, d) # radial basis function interpolator instance
|
| 145 |
+
>>> xi = yi = zi = np.linspace(0, 1, 20)
|
| 146 |
+
>>> di = rbfi(xi, yi, zi) # interpolated values
|
| 147 |
+
>>> di.shape
|
| 148 |
+
(20,)
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
# Available radial basis functions that can be selected as strings;
|
| 152 |
+
# they all start with _h_ (self._init_function relies on that)
|
| 153 |
+
def _h_multiquadric(self, r):
|
| 154 |
+
return np.sqrt((1.0/self.epsilon*r)**2 + 1)
|
| 155 |
+
|
| 156 |
+
def _h_inverse_multiquadric(self, r):
|
| 157 |
+
return 1.0/np.sqrt((1.0/self.epsilon*r)**2 + 1)
|
| 158 |
+
|
| 159 |
+
def _h_gaussian(self, r):
|
| 160 |
+
return np.exp(-(1.0/self.epsilon*r)**2)
|
| 161 |
+
|
| 162 |
+
def _h_linear(self, r):
|
| 163 |
+
return r
|
| 164 |
+
|
| 165 |
+
def _h_cubic(self, r):
|
| 166 |
+
return r**3
|
| 167 |
+
|
| 168 |
+
def _h_quintic(self, r):
|
| 169 |
+
return r**5
|
| 170 |
+
|
| 171 |
+
def _h_thin_plate(self, r):
|
| 172 |
+
return xlogy(r**2, r)
|
| 173 |
+
|
| 174 |
+
# Setup self._function and do smoke test on initial r
|
| 175 |
+
def _init_function(self, r):
|
| 176 |
+
if isinstance(self.function, str):
|
| 177 |
+
self.function = self.function.lower()
|
| 178 |
+
_mapped = {'inverse': 'inverse_multiquadric',
|
| 179 |
+
'inverse multiquadric': 'inverse_multiquadric',
|
| 180 |
+
'thin-plate': 'thin_plate'}
|
| 181 |
+
if self.function in _mapped:
|
| 182 |
+
self.function = _mapped[self.function]
|
| 183 |
+
|
| 184 |
+
func_name = "_h_" + self.function
|
| 185 |
+
if hasattr(self, func_name):
|
| 186 |
+
self._function = getattr(self, func_name)
|
| 187 |
+
else:
|
| 188 |
+
functionlist = [x[3:] for x in dir(self)
|
| 189 |
+
if x.startswith('_h_')]
|
| 190 |
+
raise ValueError("function must be a callable or one of " +
|
| 191 |
+
", ".join(functionlist))
|
| 192 |
+
self._function = getattr(self, "_h_"+self.function)
|
| 193 |
+
elif callable(self.function):
|
| 194 |
+
allow_one = False
|
| 195 |
+
if hasattr(self.function, 'func_code') or \
|
| 196 |
+
hasattr(self.function, '__code__'):
|
| 197 |
+
val = self.function
|
| 198 |
+
allow_one = True
|
| 199 |
+
elif hasattr(self.function, "__call__"):
|
| 200 |
+
val = self.function.__call__.__func__
|
| 201 |
+
else:
|
| 202 |
+
raise ValueError("Cannot determine number of arguments to "
|
| 203 |
+
"function")
|
| 204 |
+
|
| 205 |
+
argcount = val.__code__.co_argcount
|
| 206 |
+
if allow_one and argcount == 1:
|
| 207 |
+
self._function = self.function
|
| 208 |
+
elif argcount == 2:
|
| 209 |
+
self._function = self.function.__get__(self, Rbf)
|
| 210 |
+
else:
|
| 211 |
+
raise ValueError("Function argument must take 1 or 2 "
|
| 212 |
+
"arguments.")
|
| 213 |
+
|
| 214 |
+
a0 = self._function(r)
|
| 215 |
+
if a0.shape != r.shape:
|
| 216 |
+
raise ValueError("Callable must take array and return array of "
|
| 217 |
+
"the same shape")
|
| 218 |
+
return a0
|
| 219 |
+
|
| 220 |
+
def __init__(self, *args, **kwargs):
|
| 221 |
+
# `args` can be a variable number of arrays; we flatten them and store
|
| 222 |
+
# them as a single 2-D array `xi` of shape (n_args-1, array_size),
|
| 223 |
+
# plus a 1-D array `di` for the values.
|
| 224 |
+
# All arrays must have the same number of elements
|
| 225 |
+
self.xi = np.asarray([np.asarray(a, dtype=np.float64).flatten()
|
| 226 |
+
for a in args[:-1]])
|
| 227 |
+
self.N = self.xi.shape[-1]
|
| 228 |
+
|
| 229 |
+
self.mode = kwargs.pop('mode', '1-D')
|
| 230 |
+
|
| 231 |
+
if self.mode == '1-D':
|
| 232 |
+
self.di = np.asarray(args[-1]).flatten()
|
| 233 |
+
self._target_dim = 1
|
| 234 |
+
elif self.mode == 'N-D':
|
| 235 |
+
self.di = np.asarray(args[-1])
|
| 236 |
+
self._target_dim = self.di.shape[-1]
|
| 237 |
+
else:
|
| 238 |
+
raise ValueError("Mode has to be 1-D or N-D.")
|
| 239 |
+
|
| 240 |
+
if not all([x.size == self.di.shape[0] for x in self.xi]):
|
| 241 |
+
raise ValueError("All arrays must be equal length.")
|
| 242 |
+
|
| 243 |
+
self.norm = kwargs.pop('norm', 'euclidean')
|
| 244 |
+
self.epsilon = kwargs.pop('epsilon', None)
|
| 245 |
+
if self.epsilon is None:
|
| 246 |
+
# default epsilon is the "the average distance between nodes" based
|
| 247 |
+
# on a bounding hypercube
|
| 248 |
+
ximax = np.amax(self.xi, axis=1)
|
| 249 |
+
ximin = np.amin(self.xi, axis=1)
|
| 250 |
+
edges = ximax - ximin
|
| 251 |
+
edges = edges[np.nonzero(edges)]
|
| 252 |
+
self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size)
|
| 253 |
+
|
| 254 |
+
self.smooth = kwargs.pop('smooth', 0.0)
|
| 255 |
+
self.function = kwargs.pop('function', 'multiquadric')
|
| 256 |
+
|
| 257 |
+
# attach anything left in kwargs to self for use by any user-callable
|
| 258 |
+
# function or to save on the object returned.
|
| 259 |
+
for item, value in kwargs.items():
|
| 260 |
+
setattr(self, item, value)
|
| 261 |
+
|
| 262 |
+
# Compute weights
|
| 263 |
+
if self._target_dim > 1: # If we have more than one target dimension,
|
| 264 |
+
# we first factorize the matrix
|
| 265 |
+
self.nodes = np.zeros((self.N, self._target_dim), dtype=self.di.dtype)
|
| 266 |
+
lu, piv = linalg.lu_factor(self.A)
|
| 267 |
+
for i in range(self._target_dim):
|
| 268 |
+
self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i])
|
| 269 |
+
else:
|
| 270 |
+
self.nodes = linalg.solve(self.A, self.di)
|
| 271 |
+
|
| 272 |
+
@property
|
| 273 |
+
def A(self):
|
| 274 |
+
# this only exists for backwards compatibility: self.A was available
|
| 275 |
+
# and, at least technically, public.
|
| 276 |
+
r = squareform(pdist(self.xi.T, self.norm)) # Pairwise norm
|
| 277 |
+
return self._init_function(r) - np.eye(self.N)*self.smooth
|
| 278 |
+
|
| 279 |
+
def _call_norm(self, x1, x2):
|
| 280 |
+
return cdist(x1.T, x2.T, self.norm)
|
| 281 |
+
|
| 282 |
+
def __call__(self, *args):
|
| 283 |
+
args = [np.asarray(x) for x in args]
|
| 284 |
+
if not all([x.shape == y.shape for x in args for y in args]):
|
| 285 |
+
raise ValueError("Array lengths must be equal")
|
| 286 |
+
if self._target_dim > 1:
|
| 287 |
+
shp = args[0].shape + (self._target_dim,)
|
| 288 |
+
else:
|
| 289 |
+
shp = args[0].shape
|
| 290 |
+
xa = np.asarray([a.flatten() for a in args], dtype=np.float64)
|
| 291 |
+
r = self._call_norm(xa, self.xi)
|
| 292 |
+
return np.dot(self._function(r), self.nodes).reshape(shp)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_rbfinterp_common.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Impl routines common for all backends
|
| 2 |
+
from itertools import combinations_with_replacement
|
| 3 |
+
from math import comb
|
| 4 |
+
|
| 5 |
+
def _monomial_powers_impl(ndim, degree):
|
| 6 |
+
"""Return the powers for each monomial in a polynomial.
|
| 7 |
+
|
| 8 |
+
Parameters
|
| 9 |
+
----------
|
| 10 |
+
ndim : int
|
| 11 |
+
Number of variables in the polynomial.
|
| 12 |
+
degree : int
|
| 13 |
+
Degree of the polynomial.
|
| 14 |
+
|
| 15 |
+
Returns
|
| 16 |
+
-------
|
| 17 |
+
(nmonos, ndim) int ndarray
|
| 18 |
+
Array where each row contains the powers for each variable in a
|
| 19 |
+
monomial.
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
nmonos = comb(degree + ndim, ndim)
|
| 23 |
+
out = [[0]*ndim for _ in range(nmonos)]
|
| 24 |
+
count = 0
|
| 25 |
+
for deg in range(degree + 1):
|
| 26 |
+
for mono in combinations_with_replacement(range(ndim), deg):
|
| 27 |
+
# `mono` is a tuple of variables in the current monomial with
|
| 28 |
+
# multiplicity indicating power (e.g., (0, 1, 1) represents x*y**2)
|
| 29 |
+
for var in mono:
|
| 30 |
+
out[count][var] += 1
|
| 31 |
+
count += 1
|
| 32 |
+
return out
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/_rbfinterp_xp.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
'Generic' Array API backend for RBF interpolation.
|
| 3 |
+
|
| 4 |
+
The general logic is this: `_rbfinterp.py` implements the user API and calls
|
| 5 |
+
into either `_rbfinterp_np` (the "numpy backend"), or `_rbfinterp_xp` (the
|
| 6 |
+
"generic backend".
|
| 7 |
+
|
| 8 |
+
The numpy backend offloads performance-critical computations to the
|
| 9 |
+
pythran-compiled `_rbfinterp_pythran` extension. This way, the call chain is
|
| 10 |
+
|
| 11 |
+
_rbfinterp.py <-- _rbfinterp_np.py <-- _rbfinterp_pythran.py
|
| 12 |
+
|
| 13 |
+
The "generic" backend here is a drop-in replacement of the API of
|
| 14 |
+
`_rbfinterp_np.py` for use in `_rbfinterp.py` with non-numpy arrays.
|
| 15 |
+
|
| 16 |
+
The implementation closely follows `_rbfinterp_np + _rbfinterp_pythran`, with
|
| 17 |
+
the following differences:
|
| 18 |
+
|
| 19 |
+
- We used vectorized code not explicit loops in `_build_system` and
|
| 20 |
+
`_build_evaluation_coefficients`; this is more torch/jax friendly;
|
| 21 |
+
- RBF kernels are also "vectorized" and not scalar: they receive an
|
| 22 |
+
array of norms not a single norm;
|
| 23 |
+
- RBF kernels accept an extra xp= argument;
|
| 24 |
+
|
| 25 |
+
In general, we would prefer less code duplication. The main blocker ATM is
|
| 26 |
+
that pythran cannot compile functions with an xp= argument where xp is numpy.
|
| 27 |
+
"""
|
| 28 |
+
from numpy.linalg import LinAlgError
|
| 29 |
+
from ._rbfinterp_common import _monomial_powers_impl
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _monomial_powers(ndim, degree, xp):
|
| 33 |
+
out = _monomial_powers_impl(ndim, degree)
|
| 34 |
+
out = xp.asarray(out)
|
| 35 |
+
if out.shape[0] == 0:
|
| 36 |
+
out = xp.reshape(out, (0, ndim))
|
| 37 |
+
return out
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _build_and_solve_system(y, d, smoothing, kernel, epsilon, powers, xp):
|
| 41 |
+
"""Build and solve the RBF interpolation system of equations.
|
| 42 |
+
|
| 43 |
+
Parameters
|
| 44 |
+
----------
|
| 45 |
+
y : (P, N) float ndarray
|
| 46 |
+
Data point coordinates.
|
| 47 |
+
d : (P, S) float ndarray
|
| 48 |
+
Data values at `y`.
|
| 49 |
+
smoothing : (P,) float ndarray
|
| 50 |
+
Smoothing parameter for each data point.
|
| 51 |
+
kernel : str
|
| 52 |
+
Name of the RBF.
|
| 53 |
+
epsilon : float
|
| 54 |
+
Shape parameter.
|
| 55 |
+
powers : (R, N) int ndarray
|
| 56 |
+
The exponents for each monomial in the polynomial.
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
-------
|
| 60 |
+
coeffs : (P + R, S) float ndarray
|
| 61 |
+
Coefficients for each RBF and monomial.
|
| 62 |
+
shift : (N,) float ndarray
|
| 63 |
+
Domain shift used to create the polynomial matrix.
|
| 64 |
+
scale : (N,) float ndarray
|
| 65 |
+
Domain scaling used to create the polynomial matrix.
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
lhs, rhs, shift, scale = _build_system(
|
| 69 |
+
y, d, smoothing, kernel, epsilon, powers, xp
|
| 70 |
+
)
|
| 71 |
+
try:
|
| 72 |
+
coeffs = xp.linalg.solve(lhs, rhs)
|
| 73 |
+
except Exception:
|
| 74 |
+
# Best-effort attempt to emit a helpful message.
|
| 75 |
+
# `_rbfinterp_np` backend gives better diagnostics; it is hard to
|
| 76 |
+
# match it in a backend-agnostic way: e.g. jax emits no error at all,
|
| 77 |
+
# and instead returns an array of nans for a singular `lhs`.
|
| 78 |
+
msg = "Singular matrix"
|
| 79 |
+
nmonos = powers.shape[0]
|
| 80 |
+
if nmonos > 0:
|
| 81 |
+
pmat = polynomial_matrix((y - shift)/scale, powers, xp=xp)
|
| 82 |
+
rank = xp.linalg.matrix_rank(pmat)
|
| 83 |
+
if rank < nmonos:
|
| 84 |
+
msg = (
|
| 85 |
+
"Singular matrix. The matrix of monomials evaluated at "
|
| 86 |
+
"the data point coordinates does not have full column "
|
| 87 |
+
f"rank ({rank}/{nmonos})."
|
| 88 |
+
)
|
| 89 |
+
raise LinAlgError(msg)
|
| 90 |
+
|
| 91 |
+
return shift, scale, coeffs
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def linear(r, xp):
|
| 95 |
+
return -r
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def thin_plate_spline(r, xp):
|
| 99 |
+
# NB: changed w.r.t. pythran, vectorized
|
| 100 |
+
return xp.where(r == 0, 0, r**2 * xp.log(r))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def cubic(r, xp):
|
| 104 |
+
return r**3
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def quintic(r, xp):
|
| 108 |
+
return -r**5
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def multiquadric(r, xp):
|
| 112 |
+
return -xp.sqrt(r**2 + 1)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def inverse_multiquadric(r, xp):
|
| 116 |
+
return 1.0 / xp.sqrt(r**2 + 1.0)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def inverse_quadratic(r, xp):
|
| 120 |
+
return 1.0 / (r**2 + 1.0)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def gaussian(r, xp):
|
| 124 |
+
return xp.exp(-r**2)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
NAME_TO_FUNC = {
|
| 128 |
+
"linear": linear,
|
| 129 |
+
"thin_plate_spline": thin_plate_spline,
|
| 130 |
+
"cubic": cubic,
|
| 131 |
+
"quintic": quintic,
|
| 132 |
+
"multiquadric": multiquadric,
|
| 133 |
+
"inverse_multiquadric": inverse_multiquadric,
|
| 134 |
+
"inverse_quadratic": inverse_quadratic,
|
| 135 |
+
"gaussian": gaussian
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def kernel_matrix(x, kernel_func, xp):
|
| 140 |
+
"""Evaluate RBFs, with centers at `x`, at `x`."""
|
| 141 |
+
return kernel_func(
|
| 142 |
+
xp.linalg.vector_norm(x[None, :, :] - x[:, None, :], axis=-1), xp
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def polynomial_matrix(x, powers, xp):
|
| 147 |
+
"""Evaluate monomials, with exponents from `powers`, at `x`."""
|
| 148 |
+
return xp.prod(x[:, None, :] ** powers, axis=-1)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _build_system(y, d, smoothing, kernel, epsilon, powers, xp):
|
| 152 |
+
"""Build the system used to solve for the RBF interpolant coefficients.
|
| 153 |
+
|
| 154 |
+
Parameters
|
| 155 |
+
----------
|
| 156 |
+
y : (P, N) float ndarray
|
| 157 |
+
Data point coordinates.
|
| 158 |
+
d : (P, S) float ndarray
|
| 159 |
+
Data values at `y`.
|
| 160 |
+
smoothing : (P,) float ndarray
|
| 161 |
+
Smoothing parameter for each data point.
|
| 162 |
+
kernel : str
|
| 163 |
+
Name of the RBF.
|
| 164 |
+
epsilon : float
|
| 165 |
+
Shape parameter.
|
| 166 |
+
powers : (R, N) int ndarray
|
| 167 |
+
The exponents for each monomial in the polynomial.
|
| 168 |
+
|
| 169 |
+
Returns
|
| 170 |
+
-------
|
| 171 |
+
lhs : (P + R, P + R) float ndarray
|
| 172 |
+
Left-hand side matrix.
|
| 173 |
+
rhs : (P + R, S) float ndarray
|
| 174 |
+
Right-hand side matrix.
|
| 175 |
+
shift : (N,) float ndarray
|
| 176 |
+
Domain shift used to create the polynomial matrix.
|
| 177 |
+
scale : (N,) float ndarray
|
| 178 |
+
Domain scaling used to create the polynomial matrix.
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
s = d.shape[1]
|
| 182 |
+
r = powers.shape[0]
|
| 183 |
+
kernel_func = NAME_TO_FUNC[kernel]
|
| 184 |
+
|
| 185 |
+
# Shift and scale the polynomial domain to be between -1 and 1
|
| 186 |
+
mins = xp.min(y, axis=0)
|
| 187 |
+
maxs = xp.max(y, axis=0)
|
| 188 |
+
shift = (maxs + mins)/2
|
| 189 |
+
scale = (maxs - mins)/2
|
| 190 |
+
# The scale may be zero if there is a single point or all the points have
|
| 191 |
+
# the same value for some dimension. Avoid division by zero by replacing
|
| 192 |
+
# zeros with ones.
|
| 193 |
+
scale = xp.where(scale == 0.0, 1.0, scale)
|
| 194 |
+
|
| 195 |
+
yeps = y*epsilon
|
| 196 |
+
yhat = (y - shift)/scale
|
| 197 |
+
|
| 198 |
+
out_kernels = kernel_matrix(yeps, kernel_func, xp)
|
| 199 |
+
out_poly = polynomial_matrix(yhat, powers, xp)
|
| 200 |
+
|
| 201 |
+
lhs = xp.concat(
|
| 202 |
+
[
|
| 203 |
+
xp.concat((out_kernels, out_poly), axis=1),
|
| 204 |
+
xp.concat((out_poly.T, xp.zeros((r, r))), axis=1)
|
| 205 |
+
]
|
| 206 |
+
, axis=0) + xp.diag(xp.concat([smoothing, xp.zeros(r)]))
|
| 207 |
+
|
| 208 |
+
rhs = xp.concat([d, xp.zeros((r, s))], axis=0)
|
| 209 |
+
|
| 210 |
+
return lhs, rhs, shift, scale
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _build_evaluation_coefficients(
|
| 214 |
+
x, y, kernel, epsilon, powers, shift, scale, xp
|
| 215 |
+
):
|
| 216 |
+
"""Construct the coefficients needed to evaluate
|
| 217 |
+
the RBF.
|
| 218 |
+
|
| 219 |
+
Parameters
|
| 220 |
+
----------
|
| 221 |
+
x : (Q, N) float ndarray
|
| 222 |
+
Evaluation point coordinates.
|
| 223 |
+
y : (P, N) float ndarray
|
| 224 |
+
Data point coordinates.
|
| 225 |
+
kernel : str
|
| 226 |
+
Name of the RBF.
|
| 227 |
+
epsilon : float
|
| 228 |
+
Shape parameter.
|
| 229 |
+
powers : (R, N) int ndarray
|
| 230 |
+
The exponents for each monomial in the polynomial.
|
| 231 |
+
shift : (N,) float ndarray
|
| 232 |
+
Shifts the polynomial domain for numerical stability.
|
| 233 |
+
scale : (N,) float ndarray
|
| 234 |
+
Scales the polynomial domain for numerical stability.
|
| 235 |
+
|
| 236 |
+
Returns
|
| 237 |
+
-------
|
| 238 |
+
(Q, P + R) float ndarray
|
| 239 |
+
|
| 240 |
+
"""
|
| 241 |
+
kernel_func = NAME_TO_FUNC[kernel]
|
| 242 |
+
|
| 243 |
+
yeps = y*epsilon
|
| 244 |
+
xeps = x*epsilon
|
| 245 |
+
xhat = (x - shift)/scale
|
| 246 |
+
|
| 247 |
+
# NB: changed w.r.t. pythran
|
| 248 |
+
vec = xp.concat(
|
| 249 |
+
[
|
| 250 |
+
kernel_func(
|
| 251 |
+
xp.linalg.vector_norm(
|
| 252 |
+
xeps[:, None, :] - yeps[None, :, :], axis=-1
|
| 253 |
+
), xp
|
| 254 |
+
),
|
| 255 |
+
xp.prod(xhat[:, None, :] ** powers, axis=-1)
|
| 256 |
+
], axis=-1
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
return vec
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def compute_interpolation(x, y, kernel, epsilon, powers, shift, scale, coeffs, xp):
|
| 263 |
+
vec = _build_evaluation_coefficients(
|
| 264 |
+
x, y, kernel, epsilon, powers, shift, scale, xp
|
| 265 |
+
)
|
| 266 |
+
return vec @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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = ['RegularGridInterpolator', 'interpn']
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
from types import GenericAlias
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
import scipy.sparse.linalg as ssl
|
| 9 |
+
from scipy._lib._array_api import array_namespace, xp_capabilities
|
| 10 |
+
from scipy._lib.array_api_compat import is_array_api_obj
|
| 11 |
+
|
| 12 |
+
from ._interpnd import _ndim_coords_from_arrays
|
| 13 |
+
from ._cubic import PchipInterpolator
|
| 14 |
+
from ._rgi_cython import evaluate_linear_2d, find_indices
|
| 15 |
+
from ._bsplines import make_interp_spline
|
| 16 |
+
from ._fitpack2 import RectBivariateSpline
|
| 17 |
+
from ._ndbspline import make_ndbspl
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _check_points(points):
|
| 21 |
+
descending_dimensions = []
|
| 22 |
+
grid = []
|
| 23 |
+
for i, p in enumerate(points):
|
| 24 |
+
# early make points float
|
| 25 |
+
# see https://github.com/scipy/scipy/pull/17230
|
| 26 |
+
p = np.asarray(p, dtype=float)
|
| 27 |
+
if not np.all(p[1:] > p[:-1]):
|
| 28 |
+
if np.all(p[1:] < p[:-1]):
|
| 29 |
+
# input is descending, so make it ascending
|
| 30 |
+
descending_dimensions.append(i)
|
| 31 |
+
p = np.flip(p)
|
| 32 |
+
else:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
f"The points in dimension {i} must be strictly ascending or "
|
| 35 |
+
f"descending"
|
| 36 |
+
)
|
| 37 |
+
# see https://github.com/scipy/scipy/issues/17716
|
| 38 |
+
p = np.ascontiguousarray(p)
|
| 39 |
+
grid.append(p)
|
| 40 |
+
return tuple(grid), tuple(descending_dimensions)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _check_dimensionality(points, values):
|
| 44 |
+
if len(points) > values.ndim:
|
| 45 |
+
raise ValueError(
|
| 46 |
+
f"There are {len(points)} point arrays, but values has "
|
| 47 |
+
f"{values.ndim} dimensions"
|
| 48 |
+
)
|
| 49 |
+
for i, p in enumerate(points):
|
| 50 |
+
if not np.asarray(p).ndim == 1:
|
| 51 |
+
raise ValueError(f"The points in dimension {i} must be 1-dimensional")
|
| 52 |
+
if not values.shape[i] == len(p):
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"There are {len(p)} points and {values.shape[i]} values in "
|
| 55 |
+
f"dimension {i}"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@xp_capabilities(
|
| 60 |
+
cpu_only=True, jax_jit=False,
|
| 61 |
+
skip_backends=[
|
| 62 |
+
("dask.array",
|
| 63 |
+
"https://github.com/data-apis/array-api-extra/issues/488")
|
| 64 |
+
]
|
| 65 |
+
)
|
| 66 |
+
class RegularGridInterpolator:
|
| 67 |
+
"""Interpolator of specified order on a rectilinear grid in N ≥ 1 dimensions.
|
| 68 |
+
|
| 69 |
+
The data must be defined on a rectilinear grid; that is, a rectangular
|
| 70 |
+
grid with even or uneven spacing. Linear, nearest-neighbor, spline
|
| 71 |
+
interpolations are supported. After setting up the interpolator object,
|
| 72 |
+
the interpolation method may be chosen at each evaluation.
|
| 73 |
+
|
| 74 |
+
Parameters
|
| 75 |
+
----------
|
| 76 |
+
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
|
| 77 |
+
The points defining the regular grid in n dimensions. The points in
|
| 78 |
+
each dimension (i.e. every elements of the points tuple) must be
|
| 79 |
+
strictly ascending or descending.
|
| 80 |
+
|
| 81 |
+
values : array_like, shape (m1, ..., mn, ...)
|
| 82 |
+
The data on the regular grid in n dimensions. Complex data is
|
| 83 |
+
accepted.
|
| 84 |
+
|
| 85 |
+
method : str, optional
|
| 86 |
+
The method of interpolation to perform. Supported are "linear",
|
| 87 |
+
"nearest", "slinear", "cubic", "quintic" and "pchip". This
|
| 88 |
+
parameter will become the default for the object's ``__call__``
|
| 89 |
+
method. Default is "linear".
|
| 90 |
+
|
| 91 |
+
bounds_error : bool, optional
|
| 92 |
+
If True, when interpolated values are requested outside of the
|
| 93 |
+
domain of the input data, a ValueError is raised.
|
| 94 |
+
If False, then `fill_value` is used.
|
| 95 |
+
Default is True.
|
| 96 |
+
|
| 97 |
+
fill_value : float or None, optional
|
| 98 |
+
The value to use for points outside of the interpolation domain.
|
| 99 |
+
If None, values outside the domain are extrapolated.
|
| 100 |
+
Default is ``np.nan``.
|
| 101 |
+
|
| 102 |
+
solver : callable, optional
|
| 103 |
+
Only used for methods "slinear", "cubic" and "quintic".
|
| 104 |
+
Sparse linear algebra solver for construction of the NdBSpline instance.
|
| 105 |
+
Default is the iterative solver `scipy.sparse.linalg.gcrotmk`.
|
| 106 |
+
|
| 107 |
+
.. versionadded:: 1.13
|
| 108 |
+
|
| 109 |
+
solver_args: dict, optional
|
| 110 |
+
Additional arguments to pass to `solver`, if any.
|
| 111 |
+
|
| 112 |
+
.. versionadded:: 1.13
|
| 113 |
+
|
| 114 |
+
Methods
|
| 115 |
+
-------
|
| 116 |
+
__call__
|
| 117 |
+
|
| 118 |
+
Attributes
|
| 119 |
+
----------
|
| 120 |
+
grid : tuple of ndarrays
|
| 121 |
+
The points defining the regular grid in n dimensions.
|
| 122 |
+
This tuple defines the full grid via
|
| 123 |
+
``np.meshgrid(*grid, indexing='ij')``
|
| 124 |
+
values : ndarray
|
| 125 |
+
Data values at the grid.
|
| 126 |
+
method : str
|
| 127 |
+
Interpolation method.
|
| 128 |
+
fill_value : float or ``None``
|
| 129 |
+
Use this value for out-of-bounds arguments to `__call__`.
|
| 130 |
+
bounds_error : bool
|
| 131 |
+
If ``True``, out-of-bounds argument raise a ``ValueError``.
|
| 132 |
+
|
| 133 |
+
Notes
|
| 134 |
+
-----
|
| 135 |
+
Contrary to `LinearNDInterpolator` and `NearestNDInterpolator`, this class
|
| 136 |
+
avoids expensive triangulation of the input data by taking advantage of the
|
| 137 |
+
regular grid structure.
|
| 138 |
+
|
| 139 |
+
In other words, this class assumes that the data is defined on a
|
| 140 |
+
*rectilinear* grid.
|
| 141 |
+
|
| 142 |
+
.. versionadded:: 0.14
|
| 143 |
+
|
| 144 |
+
The 'slinear'(k=1), 'cubic'(k=3), and 'quintic'(k=5) methods are
|
| 145 |
+
tensor-product spline interpolators, where `k` is the spline degree,
|
| 146 |
+
If any dimension has fewer points than `k` + 1, an error will be raised.
|
| 147 |
+
|
| 148 |
+
.. versionadded:: 1.9
|
| 149 |
+
|
| 150 |
+
If the input data is such that dimensions have incommensurate
|
| 151 |
+
units and differ by many orders of magnitude, the interpolant may have
|
| 152 |
+
numerical artifacts. Consider rescaling the data before interpolating.
|
| 153 |
+
|
| 154 |
+
**Choosing a solver for spline methods**
|
| 155 |
+
|
| 156 |
+
Spline methods, "slinear", "cubic" and "quintic" involve solving a
|
| 157 |
+
large sparse linear system at instantiation time. Depending on data,
|
| 158 |
+
the default solver may or may not be adequate. When it is not, you may
|
| 159 |
+
need to experiment with an optional `solver` argument, where you may
|
| 160 |
+
choose between the direct solver (`scipy.sparse.linalg.spsolve`) or
|
| 161 |
+
iterative solvers from `scipy.sparse.linalg`. You may need to supply
|
| 162 |
+
additional parameters via the optional `solver_args` parameter (for instance,
|
| 163 |
+
you may supply the starting value or target tolerance). See the
|
| 164 |
+
`scipy.sparse.linalg` documentation for the full list of available options.
|
| 165 |
+
|
| 166 |
+
Alternatively, you may instead use the legacy methods, "slinear_legacy",
|
| 167 |
+
"cubic_legacy" and "quintic_legacy". These methods allow faster construction
|
| 168 |
+
but evaluations will be much slower.
|
| 169 |
+
|
| 170 |
+
**Rounding rule at half points with `nearest` method**
|
| 171 |
+
|
| 172 |
+
The rounding rule with the `nearest` method at half points is rounding *down*.
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
Examples
|
| 176 |
+
--------
|
| 177 |
+
**Evaluate a function on the points of a 3-D grid**
|
| 178 |
+
|
| 179 |
+
As a first example, we evaluate a simple example function on the points of
|
| 180 |
+
a 3-D grid:
|
| 181 |
+
|
| 182 |
+
>>> from scipy.interpolate import RegularGridInterpolator
|
| 183 |
+
>>> import numpy as np
|
| 184 |
+
>>> def f(x, y, z):
|
| 185 |
+
... return 2 * x**3 + 3 * y**2 - z
|
| 186 |
+
>>> x = np.linspace(1, 4, 11)
|
| 187 |
+
>>> y = np.linspace(4, 7, 22)
|
| 188 |
+
>>> z = np.linspace(7, 9, 33)
|
| 189 |
+
>>> xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True)
|
| 190 |
+
>>> data = f(xg, yg, zg)
|
| 191 |
+
|
| 192 |
+
``data`` is now a 3-D array with ``data[i, j, k] = f(x[i], y[j], z[k])``.
|
| 193 |
+
Next, define an interpolating function from this data:
|
| 194 |
+
|
| 195 |
+
>>> interp = RegularGridInterpolator((x, y, z), data)
|
| 196 |
+
|
| 197 |
+
Evaluate the interpolating function at the two points
|
| 198 |
+
``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``:
|
| 199 |
+
|
| 200 |
+
>>> pts = np.array([[2.1, 6.2, 8.3],
|
| 201 |
+
... [3.3, 5.2, 7.1]])
|
| 202 |
+
>>> interp(pts)
|
| 203 |
+
array([ 125.80469388, 146.30069388])
|
| 204 |
+
|
| 205 |
+
which is indeed a close approximation to
|
| 206 |
+
|
| 207 |
+
>>> f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)
|
| 208 |
+
(125.54200000000002, 145.894)
|
| 209 |
+
|
| 210 |
+
**Interpolate and extrapolate a 2D dataset**
|
| 211 |
+
|
| 212 |
+
As a second example, we interpolate and extrapolate a 2D data set:
|
| 213 |
+
|
| 214 |
+
>>> x, y = np.array([-2, 0, 4]), np.array([-2, 0, 2, 5])
|
| 215 |
+
>>> def ff(x, y):
|
| 216 |
+
... return x**2 + y**2
|
| 217 |
+
|
| 218 |
+
>>> xg, yg = np.meshgrid(x, y, indexing='ij')
|
| 219 |
+
>>> data = ff(xg, yg)
|
| 220 |
+
>>> interp = RegularGridInterpolator((x, y), data,
|
| 221 |
+
... bounds_error=False, fill_value=None)
|
| 222 |
+
|
| 223 |
+
>>> import matplotlib.pyplot as plt
|
| 224 |
+
>>> fig = plt.figure()
|
| 225 |
+
>>> ax = fig.add_subplot(projection='3d')
|
| 226 |
+
>>> ax.scatter(xg.ravel(), yg.ravel(), data.ravel(),
|
| 227 |
+
... s=60, c='k', label='data')
|
| 228 |
+
|
| 229 |
+
Evaluate and plot the interpolator on a finer grid
|
| 230 |
+
|
| 231 |
+
>>> xx = np.linspace(-4, 9, 31)
|
| 232 |
+
>>> yy = np.linspace(-4, 9, 31)
|
| 233 |
+
>>> X, Y = np.meshgrid(xx, yy, indexing='ij')
|
| 234 |
+
|
| 235 |
+
>>> # interpolator
|
| 236 |
+
>>> ax.plot_wireframe(X, Y, interp((X, Y)), rstride=3, cstride=3,
|
| 237 |
+
... alpha=0.4, color='m', label='linear interp')
|
| 238 |
+
|
| 239 |
+
>>> # ground truth
|
| 240 |
+
>>> ax.plot_wireframe(X, Y, ff(X, Y), rstride=3, cstride=3,
|
| 241 |
+
... alpha=0.4, label='ground truth')
|
| 242 |
+
>>> plt.legend()
|
| 243 |
+
>>> plt.show()
|
| 244 |
+
|
| 245 |
+
Other examples are given
|
| 246 |
+
:ref:`in the tutorial <tutorial-interpolate_regular_grid_interpolator>`.
|
| 247 |
+
|
| 248 |
+
See Also
|
| 249 |
+
--------
|
| 250 |
+
NearestNDInterpolator : Nearest neighbor interpolator on *unstructured*
|
| 251 |
+
data in N dimensions
|
| 252 |
+
|
| 253 |
+
LinearNDInterpolator : Piecewise linear interpolator on *unstructured* data
|
| 254 |
+
in N dimensions
|
| 255 |
+
|
| 256 |
+
interpn : a convenience function which wraps `RegularGridInterpolator`
|
| 257 |
+
|
| 258 |
+
scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
|
| 259 |
+
(suitable for e.g., N-D image resampling)
|
| 260 |
+
|
| 261 |
+
References
|
| 262 |
+
----------
|
| 263 |
+
.. [1] Python package *regulargrid* by Johannes Buchner, see
|
| 264 |
+
https://pypi.python.org/pypi/regulargrid/
|
| 265 |
+
.. [2] Wikipedia, "Trilinear interpolation",
|
| 266 |
+
https://en.wikipedia.org/wiki/Trilinear_interpolation
|
| 267 |
+
.. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear
|
| 268 |
+
and multilinear table interpolation in many dimensions." MATH.
|
| 269 |
+
COMPUT. 50.181 (1988): 189-196.
|
| 270 |
+
https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf
|
| 271 |
+
:doi:`10.1090/S0025-5718-1988-0917826-0`
|
| 272 |
+
|
| 273 |
+
"""
|
| 274 |
+
# this class is based on code originally programmed by Johannes Buchner,
|
| 275 |
+
# see https://github.com/JohannesBuchner/regulargrid
|
| 276 |
+
|
| 277 |
+
_SPLINE_DEGREE_MAP = {"slinear": 1, "cubic": 3, "quintic": 5, 'pchip': 3,
|
| 278 |
+
"slinear_legacy": 1, "cubic_legacy": 3, "quintic_legacy": 5,}
|
| 279 |
+
_SPLINE_METHODS_recursive = {"slinear_legacy", "cubic_legacy",
|
| 280 |
+
"quintic_legacy", "pchip"}
|
| 281 |
+
_SPLINE_METHODS_ndbspl = {"slinear", "cubic", "quintic"}
|
| 282 |
+
_SPLINE_METHODS = list(_SPLINE_DEGREE_MAP.keys())
|
| 283 |
+
_ALL_METHODS = ["linear", "nearest"] + _SPLINE_METHODS
|
| 284 |
+
|
| 285 |
+
# generic type compatibility with scipy-stubs
|
| 286 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 287 |
+
|
| 288 |
+
def __init__(self, points, values, method="linear", bounds_error=True,
|
| 289 |
+
fill_value=np.nan, *, solver=None, solver_args=None):
|
| 290 |
+
if method not in self._ALL_METHODS:
|
| 291 |
+
raise ValueError(f"Method '{method}' is not defined")
|
| 292 |
+
elif method in self._SPLINE_METHODS:
|
| 293 |
+
self._validate_grid_dimensions(points, method) # NB: uses np.atleast_1d
|
| 294 |
+
|
| 295 |
+
try:
|
| 296 |
+
xp = array_namespace(*points, values)
|
| 297 |
+
except Exception as e:
|
| 298 |
+
# either "duck-type" values or a user error?
|
| 299 |
+
xp = array_namespace(*points) # still forbid mixed namespaces in `points`
|
| 300 |
+
try:
|
| 301 |
+
xp_v = array_namespace(values)
|
| 302 |
+
except Exception:
|
| 303 |
+
# "duck-type" values indeed, continue with `xp` as the namespace
|
| 304 |
+
pass
|
| 305 |
+
else:
|
| 306 |
+
# both `points` and `values` are array API objects, check consistency
|
| 307 |
+
if xp_v != xp:
|
| 308 |
+
raise e
|
| 309 |
+
|
| 310 |
+
self._asarray = xp.asarray
|
| 311 |
+
self.method = method
|
| 312 |
+
self._spline = None
|
| 313 |
+
self.bounds_error = bounds_error
|
| 314 |
+
self._grid, self._descending_dimensions = _check_points(points)
|
| 315 |
+
self._values = self._check_values(values)
|
| 316 |
+
self._check_dimensionality(self._grid, self._values)
|
| 317 |
+
self.fill_value = self._check_fill_value(self._values, fill_value)
|
| 318 |
+
if self._descending_dimensions:
|
| 319 |
+
self._values = np.flip(values, axis=self._descending_dimensions)
|
| 320 |
+
if self.method == "pchip" and np.iscomplexobj(self._values):
|
| 321 |
+
msg = ("`PchipInterpolator` only works with real values. If you are trying "
|
| 322 |
+
"to use the real components of the passed array, use `np.real` on "
|
| 323 |
+
"the array before passing to `RegularGridInterpolator`.")
|
| 324 |
+
raise ValueError(msg)
|
| 325 |
+
if method in self._SPLINE_METHODS_ndbspl:
|
| 326 |
+
if solver_args is None:
|
| 327 |
+
solver_args = {}
|
| 328 |
+
self._spline = self._construct_spline(method, solver, **solver_args)
|
| 329 |
+
else:
|
| 330 |
+
if solver is not None or solver_args:
|
| 331 |
+
raise ValueError(
|
| 332 |
+
f"{method =} does not accept the 'solver' argument. Got "
|
| 333 |
+
f" {solver = } and with arguments {solver_args}."
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def _construct_spline(self, method, solver=None, **solver_args):
|
| 337 |
+
if solver is None:
|
| 338 |
+
solver = ssl.gcrotmk
|
| 339 |
+
spl = make_ndbspl(
|
| 340 |
+
self._grid, self._values, self._SPLINE_DEGREE_MAP[method],
|
| 341 |
+
solver=solver, **solver_args
|
| 342 |
+
)
|
| 343 |
+
return spl
|
| 344 |
+
|
| 345 |
+
def _check_dimensionality(self, grid, values):
|
| 346 |
+
_check_dimensionality(grid, values)
|
| 347 |
+
|
| 348 |
+
def _check_points(self, points):
|
| 349 |
+
return _check_points(points)
|
| 350 |
+
|
| 351 |
+
def _check_values(self, values):
|
| 352 |
+
if is_array_api_obj(values):
|
| 353 |
+
values = np.asarray(values)
|
| 354 |
+
|
| 355 |
+
if not hasattr(values, 'ndim'):
|
| 356 |
+
# allow reasonable duck-typed values
|
| 357 |
+
values = np.asarray(values)
|
| 358 |
+
|
| 359 |
+
if hasattr(values, 'dtype') and hasattr(values, 'astype'):
|
| 360 |
+
if not np.issubdtype(values.dtype, np.inexact):
|
| 361 |
+
values = values.astype(float)
|
| 362 |
+
|
| 363 |
+
return values
|
| 364 |
+
|
| 365 |
+
def _check_fill_value(self, values, fill_value):
|
| 366 |
+
if fill_value is not None:
|
| 367 |
+
fill_value_dtype = np.asarray(fill_value).dtype
|
| 368 |
+
if (hasattr(values, 'dtype') and not
|
| 369 |
+
np.can_cast(fill_value_dtype, values.dtype,
|
| 370 |
+
casting='same_kind')):
|
| 371 |
+
raise ValueError("fill_value must be either 'None' or "
|
| 372 |
+
"of a type compatible with values")
|
| 373 |
+
return fill_value
|
| 374 |
+
|
| 375 |
+
def __call__(self, xi, method=None, *, nu=None):
|
| 376 |
+
"""
|
| 377 |
+
Interpolation at coordinates.
|
| 378 |
+
|
| 379 |
+
Parameters
|
| 380 |
+
----------
|
| 381 |
+
xi : ndarray of shape (..., ndim)
|
| 382 |
+
The coordinates to evaluate the interpolator at.
|
| 383 |
+
|
| 384 |
+
method : str, optional
|
| 385 |
+
The method of interpolation to perform. Supported are "linear",
|
| 386 |
+
"nearest", "slinear", "cubic", "quintic" and "pchip". Default is
|
| 387 |
+
the method chosen when the interpolator was created.
|
| 388 |
+
|
| 389 |
+
nu : sequence of ints, length ndim, optional
|
| 390 |
+
If not None, the orders of the derivatives to evaluate.
|
| 391 |
+
Each entry must be non-negative.
|
| 392 |
+
Only allowed for methods "slinear", "cubic" and "quintic".
|
| 393 |
+
|
| 394 |
+
.. versionadded:: 1.13
|
| 395 |
+
|
| 396 |
+
Returns
|
| 397 |
+
-------
|
| 398 |
+
values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
|
| 399 |
+
Interpolated values at `xi`. See notes for behaviour when
|
| 400 |
+
``xi.ndim == 1``.
|
| 401 |
+
|
| 402 |
+
Notes
|
| 403 |
+
-----
|
| 404 |
+
In the case that ``xi.ndim == 1`` a new axis is inserted into
|
| 405 |
+
the 0 position of the returned array, values_x, so its shape is
|
| 406 |
+
instead ``(1,) + values.shape[ndim:]``.
|
| 407 |
+
|
| 408 |
+
Examples
|
| 409 |
+
--------
|
| 410 |
+
Here we define a nearest-neighbor interpolator of a simple function
|
| 411 |
+
|
| 412 |
+
>>> import numpy as np
|
| 413 |
+
>>> x, y = np.array([0, 1, 2]), np.array([1, 3, 7])
|
| 414 |
+
>>> def f(x, y):
|
| 415 |
+
... return x**2 + y**2
|
| 416 |
+
>>> data = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
|
| 417 |
+
>>> from scipy.interpolate import RegularGridInterpolator
|
| 418 |
+
>>> interp = RegularGridInterpolator((x, y), data, method='nearest')
|
| 419 |
+
|
| 420 |
+
By construction, the interpolator uses the nearest-neighbor
|
| 421 |
+
interpolation
|
| 422 |
+
|
| 423 |
+
>>> interp([[1.5, 1.3], [0.3, 4.5]])
|
| 424 |
+
array([2., 9.])
|
| 425 |
+
|
| 426 |
+
We can however evaluate the linear interpolant by overriding the
|
| 427 |
+
`method` parameter
|
| 428 |
+
|
| 429 |
+
>>> interp([[1.5, 1.3], [0.3, 4.5]], method='linear')
|
| 430 |
+
array([ 4.7, 24.3])
|
| 431 |
+
"""
|
| 432 |
+
_spline = self._spline
|
| 433 |
+
method = self.method if method is None else method
|
| 434 |
+
is_method_changed = self.method != method
|
| 435 |
+
if method not in self._ALL_METHODS:
|
| 436 |
+
raise ValueError(f"Method '{method}' is not defined")
|
| 437 |
+
if is_method_changed and method in self._SPLINE_METHODS_ndbspl:
|
| 438 |
+
_spline = self._construct_spline(method)
|
| 439 |
+
|
| 440 |
+
if nu is not None and method not in self._SPLINE_METHODS_ndbspl:
|
| 441 |
+
raise ValueError(
|
| 442 |
+
f"Can only compute derivatives for methods "
|
| 443 |
+
f"{self._SPLINE_METHODS_ndbspl}, got {method =}."
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
xi, xi_shape, ndim, nans, out_of_bounds = self._prepare_xi(xi)
|
| 447 |
+
|
| 448 |
+
if method == "linear":
|
| 449 |
+
indices, norm_distances = self._find_indices(xi.T)
|
| 450 |
+
if (ndim == 2 and hasattr(self._values, 'dtype') and
|
| 451 |
+
self._values.ndim == 2 and self._values.flags.writeable and
|
| 452 |
+
self._values.dtype in (np.float64, np.complex128) and
|
| 453 |
+
self._values.dtype.byteorder == '='):
|
| 454 |
+
# until cython supports const fused types, the fast path
|
| 455 |
+
# cannot support non-writeable values
|
| 456 |
+
# a fast path
|
| 457 |
+
out = np.empty(indices.shape[1], dtype=self._values.dtype)
|
| 458 |
+
result = evaluate_linear_2d(self._values,
|
| 459 |
+
indices,
|
| 460 |
+
norm_distances,
|
| 461 |
+
self._grid,
|
| 462 |
+
out)
|
| 463 |
+
else:
|
| 464 |
+
result = self._evaluate_linear(indices, norm_distances)
|
| 465 |
+
elif method == "nearest":
|
| 466 |
+
indices, norm_distances = self._find_indices(xi.T)
|
| 467 |
+
result = self._evaluate_nearest(indices, norm_distances)
|
| 468 |
+
elif method in self._SPLINE_METHODS:
|
| 469 |
+
if is_method_changed:
|
| 470 |
+
self._validate_grid_dimensions(self._grid, method)
|
| 471 |
+
if method in self._SPLINE_METHODS_recursive:
|
| 472 |
+
result = self._evaluate_spline(xi, method)
|
| 473 |
+
else:
|
| 474 |
+
result = _spline(xi, nu=nu)
|
| 475 |
+
|
| 476 |
+
if not self.bounds_error and self.fill_value is not None:
|
| 477 |
+
result[out_of_bounds] = self.fill_value
|
| 478 |
+
|
| 479 |
+
# f(nan) = nan, if any
|
| 480 |
+
if np.any(nans):
|
| 481 |
+
result[nans] = np.nan
|
| 482 |
+
return self._asarray(result.reshape(xi_shape[:-1] + self._values.shape[ndim:]))
|
| 483 |
+
|
| 484 |
+
@property
|
| 485 |
+
def grid(self):
|
| 486 |
+
return tuple(self._asarray(p) for p in self._grid)
|
| 487 |
+
|
| 488 |
+
@property
|
| 489 |
+
def values(self):
|
| 490 |
+
return self._asarray(self._values)
|
| 491 |
+
|
| 492 |
+
def _prepare_xi(self, xi):
|
| 493 |
+
ndim = len(self._grid)
|
| 494 |
+
xi = _ndim_coords_from_arrays(xi, ndim=ndim)
|
| 495 |
+
if xi.shape[-1] != ndim:
|
| 496 |
+
raise ValueError("The requested sample points xi have dimension "
|
| 497 |
+
f"{xi.shape[-1]} but this "
|
| 498 |
+
f"RegularGridInterpolator has dimension {ndim}")
|
| 499 |
+
|
| 500 |
+
xi_shape = xi.shape
|
| 501 |
+
xi = xi.reshape(-1, xi_shape[-1])
|
| 502 |
+
xi = np.asarray(xi, dtype=float)
|
| 503 |
+
|
| 504 |
+
# find nans in input
|
| 505 |
+
nans = np.any(np.isnan(xi), axis=-1)
|
| 506 |
+
|
| 507 |
+
if self.bounds_error:
|
| 508 |
+
for i, p in enumerate(xi.T):
|
| 509 |
+
if not np.logical_and(np.all(self._grid[i][0] <= p),
|
| 510 |
+
np.all(p <= self._grid[i][-1])):
|
| 511 |
+
raise ValueError(
|
| 512 |
+
f"One of the requested xi is out of bounds in dimension {i}"
|
| 513 |
+
)
|
| 514 |
+
out_of_bounds = None
|
| 515 |
+
else:
|
| 516 |
+
out_of_bounds = self._find_out_of_bounds(xi.T)
|
| 517 |
+
|
| 518 |
+
return xi, xi_shape, ndim, nans, out_of_bounds
|
| 519 |
+
|
| 520 |
+
def _evaluate_linear(self, indices, norm_distances):
|
| 521 |
+
# slice for broadcasting over trailing dimensions in self._values
|
| 522 |
+
vslice = (slice(None),) + (None,)*(self._values.ndim - len(indices))
|
| 523 |
+
|
| 524 |
+
# Compute shifting up front before zipping everything together
|
| 525 |
+
shift_norm_distances = [1 - yi for yi in norm_distances]
|
| 526 |
+
shift_indices = [i + 1 for i in indices]
|
| 527 |
+
|
| 528 |
+
# The formula for linear interpolation in 2d takes the form:
|
| 529 |
+
# values = self._values[(i0, i1)] * (1 - y0) * (1 - y1) + \
|
| 530 |
+
# self._values[(i0, i1 + 1)] * (1 - y0) * y1 + \
|
| 531 |
+
# self._values[(i0 + 1, i1)] * y0 * (1 - y1) + \
|
| 532 |
+
# self._values[(i0 + 1, i1 + 1)] * y0 * y1
|
| 533 |
+
# We pair i with 1 - yi (zipped1) and i + 1 with yi (zipped2)
|
| 534 |
+
zipped1 = zip(indices, shift_norm_distances)
|
| 535 |
+
zipped2 = zip(shift_indices, norm_distances)
|
| 536 |
+
|
| 537 |
+
# Take all products of zipped1 and zipped2 and iterate over them
|
| 538 |
+
# to get the terms in the above formula. This corresponds to iterating
|
| 539 |
+
# over the vertices of a hypercube.
|
| 540 |
+
hypercube = itertools.product(*zip(zipped1, zipped2))
|
| 541 |
+
value = np.array([0.])
|
| 542 |
+
for h in hypercube:
|
| 543 |
+
edge_indices, weights = zip(*h)
|
| 544 |
+
weight = np.array([1.])
|
| 545 |
+
for w in weights:
|
| 546 |
+
weight = weight * w
|
| 547 |
+
term = np.asarray(self._values[edge_indices]) * weight[vslice]
|
| 548 |
+
value = value + term # cannot use += because broadcasting
|
| 549 |
+
return value
|
| 550 |
+
|
| 551 |
+
def _evaluate_nearest(self, indices, norm_distances):
|
| 552 |
+
idx_res = [np.where(yi <= .5, i, i + 1)
|
| 553 |
+
for i, yi in zip(indices, norm_distances)]
|
| 554 |
+
return self._values[tuple(idx_res)]
|
| 555 |
+
|
| 556 |
+
def _validate_grid_dimensions(self, points, method):
|
| 557 |
+
k = self._SPLINE_DEGREE_MAP[method]
|
| 558 |
+
for i, point in enumerate(points):
|
| 559 |
+
ndim = len(np.atleast_1d(point))
|
| 560 |
+
if ndim <= k:
|
| 561 |
+
raise ValueError(f"There are {ndim} points in dimension {i},"
|
| 562 |
+
f" but method {method} requires at least "
|
| 563 |
+
f" {k+1} points per dimension.")
|
| 564 |
+
|
| 565 |
+
def _evaluate_spline(self, xi, method):
|
| 566 |
+
# ensure xi is 2D list of points to evaluate (`m` is the number of
|
| 567 |
+
# points and `n` is the number of interpolation dimensions,
|
| 568 |
+
# ``n == len(self._grid)``.)
|
| 569 |
+
if xi.ndim == 1:
|
| 570 |
+
xi = xi.reshape((1, xi.size))
|
| 571 |
+
m, n = xi.shape
|
| 572 |
+
|
| 573 |
+
# Reorder the axes: n-dimensional process iterates over the
|
| 574 |
+
# interpolation axes from the last axis downwards: E.g. for a 4D grid
|
| 575 |
+
# the order of axes is 3, 2, 1, 0. Each 1D interpolation works along
|
| 576 |
+
# the 0th axis of its argument array (for 1D routine it's its ``y``
|
| 577 |
+
# array). Thus permute the interpolation axes of `values` *and keep
|
| 578 |
+
# trailing dimensions trailing*.
|
| 579 |
+
axes = tuple(range(self._values.ndim))
|
| 580 |
+
axx = axes[:n][::-1] + axes[n:]
|
| 581 |
+
values = self._values.transpose(axx)
|
| 582 |
+
|
| 583 |
+
if method == 'pchip':
|
| 584 |
+
_eval_func = self._do_pchip
|
| 585 |
+
else:
|
| 586 |
+
_eval_func = self._do_spline_fit
|
| 587 |
+
k = self._SPLINE_DEGREE_MAP[method]
|
| 588 |
+
|
| 589 |
+
# Non-stationary procedure: difficult to vectorize this part entirely
|
| 590 |
+
# into numpy-level operations. Unfortunately this requires explicit
|
| 591 |
+
# looping over each point in xi.
|
| 592 |
+
|
| 593 |
+
# can at least vectorize the first pass across all points in the
|
| 594 |
+
# last variable of xi.
|
| 595 |
+
last_dim = n - 1
|
| 596 |
+
first_values = _eval_func(self._grid[last_dim],
|
| 597 |
+
values,
|
| 598 |
+
xi[:, last_dim],
|
| 599 |
+
k)
|
| 600 |
+
|
| 601 |
+
# the rest of the dimensions have to be on a per point-in-xi basis
|
| 602 |
+
shape = (m, *self._values.shape[n:])
|
| 603 |
+
result = np.empty(shape, dtype=self._values.dtype)
|
| 604 |
+
for j in range(m):
|
| 605 |
+
# Main process: Apply 1D interpolate in each dimension
|
| 606 |
+
# sequentially, starting with the last dimension.
|
| 607 |
+
# These are then "folded" into the next dimension in-place.
|
| 608 |
+
folded_values = first_values[j, ...]
|
| 609 |
+
for i in range(last_dim-1, -1, -1):
|
| 610 |
+
# Interpolate for each 1D from the last dimensions.
|
| 611 |
+
# This collapses each 1D sequence into a scalar.
|
| 612 |
+
folded_values = _eval_func(self._grid[i],
|
| 613 |
+
folded_values,
|
| 614 |
+
xi[j, i],
|
| 615 |
+
k)
|
| 616 |
+
result[j, ...] = folded_values
|
| 617 |
+
|
| 618 |
+
return result
|
| 619 |
+
|
| 620 |
+
@staticmethod
|
| 621 |
+
def _do_spline_fit(x, y, pt, k):
|
| 622 |
+
local_interp = make_interp_spline(x, y, k=k, axis=0)
|
| 623 |
+
values = local_interp(pt)
|
| 624 |
+
return values
|
| 625 |
+
|
| 626 |
+
@staticmethod
|
| 627 |
+
def _do_pchip(x, y, pt, k):
|
| 628 |
+
local_interp = PchipInterpolator(x, y, axis=0)
|
| 629 |
+
values = local_interp(pt)
|
| 630 |
+
return values
|
| 631 |
+
|
| 632 |
+
def _find_indices(self, xi):
|
| 633 |
+
return find_indices(self._grid, xi)
|
| 634 |
+
|
| 635 |
+
def _find_out_of_bounds(self, xi):
|
| 636 |
+
# check for out of bounds xi
|
| 637 |
+
out_of_bounds = np.zeros((xi.shape[1]), dtype=bool)
|
| 638 |
+
# iterate through dimensions
|
| 639 |
+
for x, grid in zip(xi, self._grid):
|
| 640 |
+
out_of_bounds += x < grid[0]
|
| 641 |
+
out_of_bounds += x > grid[-1]
|
| 642 |
+
return out_of_bounds
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def interpn(points, values, xi, method="linear", bounds_error=True,
|
| 646 |
+
fill_value=np.nan):
|
| 647 |
+
"""
|
| 648 |
+
Multidimensional interpolation on regular or rectilinear grids.
|
| 649 |
+
|
| 650 |
+
Strictly speaking, not all regular grids are supported - this function
|
| 651 |
+
works on *rectilinear* grids, that is, a rectangular grid with even or
|
| 652 |
+
uneven spacing.
|
| 653 |
+
|
| 654 |
+
Parameters
|
| 655 |
+
----------
|
| 656 |
+
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
|
| 657 |
+
The points defining the regular grid in n dimensions. The points in
|
| 658 |
+
each dimension (i.e. every elements of the points tuple) must be
|
| 659 |
+
strictly ascending or descending.
|
| 660 |
+
|
| 661 |
+
values : array_like, shape (m1, ..., mn, ...)
|
| 662 |
+
The data on the regular grid in n dimensions. Complex data is
|
| 663 |
+
accepted.
|
| 664 |
+
xi : ndarray of shape (..., ndim)
|
| 665 |
+
The coordinates to sample the gridded data at
|
| 666 |
+
|
| 667 |
+
method : str, optional
|
| 668 |
+
The method of interpolation to perform. Supported are "linear",
|
| 669 |
+
"nearest", "slinear", "cubic", "quintic", "pchip", and "splinef2d".
|
| 670 |
+
"splinef2d" is only supported for 2-dimensional data.
|
| 671 |
+
|
| 672 |
+
bounds_error : bool, optional
|
| 673 |
+
If True, when interpolated values are requested outside of the
|
| 674 |
+
domain of the input data, a ValueError is raised.
|
| 675 |
+
If False, then `fill_value` is used.
|
| 676 |
+
|
| 677 |
+
fill_value : number, optional
|
| 678 |
+
If provided, the value to use for points outside of the
|
| 679 |
+
interpolation domain. If None, values outside
|
| 680 |
+
the domain are extrapolated. Extrapolation is not supported by method
|
| 681 |
+
"splinef2d".
|
| 682 |
+
|
| 683 |
+
Returns
|
| 684 |
+
-------
|
| 685 |
+
values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
|
| 686 |
+
Interpolated values at `xi`. See notes for behaviour when
|
| 687 |
+
``xi.ndim == 1``.
|
| 688 |
+
|
| 689 |
+
See Also
|
| 690 |
+
--------
|
| 691 |
+
NearestNDInterpolator : Nearest neighbor interpolation on unstructured
|
| 692 |
+
data in N dimensions
|
| 693 |
+
LinearNDInterpolator : Piecewise linear interpolant on unstructured data
|
| 694 |
+
in N dimensions
|
| 695 |
+
RegularGridInterpolator : interpolation on a regular or rectilinear grid
|
| 696 |
+
in arbitrary dimensions (`interpn` wraps this
|
| 697 |
+
class).
|
| 698 |
+
RectBivariateSpline : Bivariate spline approximation over a rectangular mesh
|
| 699 |
+
scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
|
| 700 |
+
(suitable for e.g., N-D image resampling)
|
| 701 |
+
|
| 702 |
+
Notes
|
| 703 |
+
-----
|
| 704 |
+
|
| 705 |
+
.. versionadded:: 0.14
|
| 706 |
+
|
| 707 |
+
In the case that ``xi.ndim == 1`` a new axis is inserted into
|
| 708 |
+
the 0 position of the returned array, values_x, so its shape is
|
| 709 |
+
instead ``(1,) + values.shape[ndim:]``.
|
| 710 |
+
|
| 711 |
+
If the input data is such that input dimensions have incommensurate
|
| 712 |
+
units and differ by many orders of magnitude, the interpolant may have
|
| 713 |
+
numerical artifacts. Consider rescaling the data before interpolation.
|
| 714 |
+
|
| 715 |
+
Examples
|
| 716 |
+
--------
|
| 717 |
+
Evaluate a simple example function on the points of a regular 3-D grid:
|
| 718 |
+
|
| 719 |
+
>>> import numpy as np
|
| 720 |
+
>>> from scipy.interpolate import interpn
|
| 721 |
+
>>> def value_func_3d(x, y, z):
|
| 722 |
+
... return 2 * x + 3 * y - z
|
| 723 |
+
>>> x = np.linspace(0, 4, 5)
|
| 724 |
+
>>> y = np.linspace(0, 5, 6)
|
| 725 |
+
>>> z = np.linspace(0, 6, 7)
|
| 726 |
+
>>> points = (x, y, z)
|
| 727 |
+
>>> values = value_func_3d(*np.meshgrid(*points, indexing='ij'))
|
| 728 |
+
|
| 729 |
+
Evaluate the interpolating function at a point
|
| 730 |
+
|
| 731 |
+
>>> point = np.array([2.21, 3.12, 1.15])
|
| 732 |
+
>>> print(interpn(points, values, point))
|
| 733 |
+
[12.63]
|
| 734 |
+
|
| 735 |
+
Compare with value at point by function
|
| 736 |
+
|
| 737 |
+
>>> value_func_3d(*point)
|
| 738 |
+
12.63 # up to rounding
|
| 739 |
+
|
| 740 |
+
Since the function is linear, the interpolation is exact using linear method.
|
| 741 |
+
|
| 742 |
+
"""
|
| 743 |
+
# sanity check 'method' kwarg
|
| 744 |
+
if method not in ["linear", "nearest", "cubic", "quintic", "pchip",
|
| 745 |
+
"splinef2d", "slinear",
|
| 746 |
+
"slinear_legacy", "cubic_legacy", "quintic_legacy"]:
|
| 747 |
+
raise ValueError("interpn only understands the methods 'linear', "
|
| 748 |
+
"'nearest', 'slinear', 'cubic', 'quintic', 'pchip', "
|
| 749 |
+
f"and 'splinef2d'. You provided {method}.")
|
| 750 |
+
|
| 751 |
+
if not hasattr(values, 'ndim'):
|
| 752 |
+
values = np.asarray(values)
|
| 753 |
+
|
| 754 |
+
ndim = values.ndim
|
| 755 |
+
if ndim > 2 and method == "splinef2d":
|
| 756 |
+
raise ValueError("The method splinef2d can only be used for "
|
| 757 |
+
"2-dimensional input data")
|
| 758 |
+
if not bounds_error and fill_value is None and method == "splinef2d":
|
| 759 |
+
raise ValueError("The method splinef2d does not support extrapolation.")
|
| 760 |
+
|
| 761 |
+
# sanity check consistency of input dimensions
|
| 762 |
+
if len(points) > ndim:
|
| 763 |
+
raise ValueError(
|
| 764 |
+
f"There are {len(points)} point arrays, but values has {ndim} dimensions"
|
| 765 |
+
)
|
| 766 |
+
if len(points) != ndim and method == 'splinef2d':
|
| 767 |
+
raise ValueError("The method splinef2d can only be used for "
|
| 768 |
+
"scalar data with one point per coordinate")
|
| 769 |
+
|
| 770 |
+
grid, descending_dimensions = _check_points(points)
|
| 771 |
+
_check_dimensionality(grid, values)
|
| 772 |
+
|
| 773 |
+
# sanity check requested xi
|
| 774 |
+
xi = _ndim_coords_from_arrays(xi, ndim=len(grid))
|
| 775 |
+
if xi.shape[-1] != len(grid):
|
| 776 |
+
raise ValueError(
|
| 777 |
+
f"The requested sample points xi have dimension {xi.shape[-1]}, "
|
| 778 |
+
f"but this RegularGridInterpolator has dimension {len(grid)}"
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
if bounds_error:
|
| 782 |
+
for i, p in enumerate(xi.T):
|
| 783 |
+
if not np.logical_and(np.all(grid[i][0] <= p),
|
| 784 |
+
np.all(p <= grid[i][-1])):
|
| 785 |
+
raise ValueError(
|
| 786 |
+
f"One of the requested xi is out of bounds in dimension {i}"
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
# perform interpolation
|
| 790 |
+
if method in RegularGridInterpolator._ALL_METHODS:
|
| 791 |
+
interp = RegularGridInterpolator(points, values, method=method,
|
| 792 |
+
bounds_error=bounds_error,
|
| 793 |
+
fill_value=fill_value)
|
| 794 |
+
return interp(xi)
|
| 795 |
+
elif method == "splinef2d":
|
| 796 |
+
xi_shape = xi.shape
|
| 797 |
+
xi = xi.reshape(-1, xi.shape[-1])
|
| 798 |
+
|
| 799 |
+
# RectBivariateSpline doesn't support fill_value; we need to wrap here
|
| 800 |
+
idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1],
|
| 801 |
+
grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]),
|
| 802 |
+
axis=0)
|
| 803 |
+
result = np.empty_like(xi[:, 0])
|
| 804 |
+
|
| 805 |
+
# make a copy of values for RectBivariateSpline
|
| 806 |
+
interp = RectBivariateSpline(points[0], points[1], values[:])
|
| 807 |
+
result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1])
|
| 808 |
+
result[np.logical_not(idx_valid)] = fill_value
|
| 809 |
+
|
| 810 |
+
return result.reshape(xi_shape[:-1])
|
| 811 |
+
else:
|
| 812 |
+
raise ValueError(f"unknown {method = }")
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/dfitpack.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.interpolate` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'spalde',
|
| 10 |
+
'splder',
|
| 11 |
+
'splev',
|
| 12 |
+
'splint',
|
| 13 |
+
'sproot',
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def __dir__():
|
| 18 |
+
return __all__
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def __getattr__(name):
|
| 22 |
+
return _sub_module_deprecation(sub_package="interpolate", module="dfitpack",
|
| 23 |
+
private_modules=["_dfitpack"], all=__all__,
|
| 24 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/fitpack.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.interpolate` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'BSpline',
|
| 10 |
+
'bisplev',
|
| 11 |
+
'bisplrep',
|
| 12 |
+
'insert',
|
| 13 |
+
'spalde',
|
| 14 |
+
'splantider',
|
| 15 |
+
'splder',
|
| 16 |
+
'splev',
|
| 17 |
+
'splint',
|
| 18 |
+
'splprep',
|
| 19 |
+
'splrep',
|
| 20 |
+
'sproot',
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def __dir__():
|
| 25 |
+
return __all__
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def __getattr__(name):
|
| 29 |
+
return _sub_module_deprecation(sub_package="interpolate", module="fitpack",
|
| 30 |
+
private_modules=["_fitpack_py"], all=__all__,
|
| 31 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/fitpack2.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.interpolate` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'BivariateSpline',
|
| 10 |
+
'InterpolatedUnivariateSpline',
|
| 11 |
+
'LSQBivariateSpline',
|
| 12 |
+
'LSQSphereBivariateSpline',
|
| 13 |
+
'LSQUnivariateSpline',
|
| 14 |
+
'RectBivariateSpline',
|
| 15 |
+
'RectSphereBivariateSpline',
|
| 16 |
+
'SmoothBivariateSpline',
|
| 17 |
+
'SmoothSphereBivariateSpline',
|
| 18 |
+
'UnivariateSpline',
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def __dir__():
|
| 23 |
+
return __all__
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def __getattr__(name):
|
| 27 |
+
return _sub_module_deprecation(sub_package="interpolate", module="fitpack2",
|
| 28 |
+
private_modules=["_fitpack2"], all=__all__,
|
| 29 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/interpnd.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.interpolate` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'CloughTocher2DInterpolator',
|
| 10 |
+
'LinearNDInterpolator',
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __dir__():
|
| 15 |
+
return __all__
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name):
|
| 19 |
+
return _sub_module_deprecation(sub_package="interpolate", module="interpnd",
|
| 20 |
+
private_modules=["_interpnd"], all=__all__,
|
| 21 |
+
attribute=name, dep_version="1.17.0")
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/ndgriddata.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.interpolate` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'CloughTocher2DInterpolator',
|
| 10 |
+
'LinearNDInterpolator',
|
| 11 |
+
'NearestNDInterpolator',
|
| 12 |
+
'griddata',
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def __dir__():
|
| 17 |
+
return __all__
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def __getattr__(name):
|
| 21 |
+
return _sub_module_deprecation(sub_package="interpolate", module="ndgriddata",
|
| 22 |
+
private_modules=["_ndgriddata"], all=__all__,
|
| 23 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/interpolate/polyint.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.interpolate` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'BarycentricInterpolator',
|
| 10 |
+
'KroghInterpolator',
|
| 11 |
+
'approximate_taylor_polynomial',
|
| 12 |
+
'barycentric_interpolate',
|
| 13 |
+
'krogh_interpolate',
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def __dir__():
|
| 18 |
+
return __all__
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def __getattr__(name):
|
| 22 |
+
return _sub_module_deprecation(sub_package="interpolate", module="polyint",
|
| 23 |
+
private_modules=["_polyint"], all=__all__,
|
| 24 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/__init__.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
==================================
|
| 3 |
+
Input and output (:mod:`scipy.io`)
|
| 4 |
+
==================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.io
|
| 7 |
+
|
| 8 |
+
.. toctree::
|
| 9 |
+
:hidden:
|
| 10 |
+
|
| 11 |
+
io.matlab
|
| 12 |
+
|
| 13 |
+
SciPy has many modules, classes, and functions available to read data
|
| 14 |
+
from and write data to a variety of file formats.
|
| 15 |
+
|
| 16 |
+
.. seealso:: `NumPy IO routines <https://www.numpy.org/devdocs/reference/routines.io.html>`__
|
| 17 |
+
|
| 18 |
+
MATLAB® files
|
| 19 |
+
=============
|
| 20 |
+
|
| 21 |
+
.. autosummary::
|
| 22 |
+
:toctree: generated/
|
| 23 |
+
|
| 24 |
+
loadmat - Read a MATLAB style mat file (version 4 through 7.1)
|
| 25 |
+
savemat - Write a MATLAB style mat file (version 4 through 7.1)
|
| 26 |
+
whosmat - List contents of a MATLAB style mat file (version 4 through 7.1)
|
| 27 |
+
|
| 28 |
+
For low-level MATLAB reading and writing utilities, see `scipy.io.matlab`.
|
| 29 |
+
|
| 30 |
+
IDL® files
|
| 31 |
+
==========
|
| 32 |
+
|
| 33 |
+
.. autosummary::
|
| 34 |
+
:toctree: generated/
|
| 35 |
+
|
| 36 |
+
readsav - Read an IDL 'save' file
|
| 37 |
+
|
| 38 |
+
Matrix Market files
|
| 39 |
+
===================
|
| 40 |
+
|
| 41 |
+
.. autosummary::
|
| 42 |
+
:toctree: generated/
|
| 43 |
+
|
| 44 |
+
mminfo - Query matrix info from Matrix Market formatted file
|
| 45 |
+
mmread - Read matrix from Matrix Market formatted file
|
| 46 |
+
mmwrite - Write matrix to Matrix Market formatted file
|
| 47 |
+
|
| 48 |
+
Unformatted Fortran files
|
| 49 |
+
===============================
|
| 50 |
+
|
| 51 |
+
.. autosummary::
|
| 52 |
+
:toctree: generated/
|
| 53 |
+
|
| 54 |
+
FortranFile - A file object for unformatted sequential Fortran files
|
| 55 |
+
FortranEOFError - Exception indicating the end of a well-formed file
|
| 56 |
+
FortranFormattingError - Exception indicating an inappropriate end
|
| 57 |
+
|
| 58 |
+
Netcdf
|
| 59 |
+
======
|
| 60 |
+
|
| 61 |
+
.. autosummary::
|
| 62 |
+
:toctree: generated/
|
| 63 |
+
|
| 64 |
+
netcdf_file - A file object for NetCDF data
|
| 65 |
+
netcdf_variable - A data object for the netcdf module
|
| 66 |
+
|
| 67 |
+
Harwell-Boeing files
|
| 68 |
+
====================
|
| 69 |
+
|
| 70 |
+
.. autosummary::
|
| 71 |
+
:toctree: generated/
|
| 72 |
+
|
| 73 |
+
hb_read -- read H-B file
|
| 74 |
+
hb_write -- write H-B file
|
| 75 |
+
|
| 76 |
+
Wav sound files (:mod:`scipy.io.wavfile`)
|
| 77 |
+
=========================================
|
| 78 |
+
|
| 79 |
+
.. module:: scipy.io.wavfile
|
| 80 |
+
|
| 81 |
+
.. autosummary::
|
| 82 |
+
:toctree: generated/
|
| 83 |
+
|
| 84 |
+
read
|
| 85 |
+
write
|
| 86 |
+
WavFileWarning
|
| 87 |
+
|
| 88 |
+
Arff files (:mod:`scipy.io.arff`)
|
| 89 |
+
=================================
|
| 90 |
+
|
| 91 |
+
.. module:: scipy.io.arff
|
| 92 |
+
|
| 93 |
+
.. autosummary::
|
| 94 |
+
:toctree: generated/
|
| 95 |
+
|
| 96 |
+
loadarff
|
| 97 |
+
MetaData
|
| 98 |
+
ArffError
|
| 99 |
+
ParseArffError
|
| 100 |
+
"""
|
| 101 |
+
# matfile read and write
|
| 102 |
+
from .matlab import loadmat, savemat, whosmat
|
| 103 |
+
|
| 104 |
+
# netCDF file support
|
| 105 |
+
from ._netcdf import netcdf_file, netcdf_variable
|
| 106 |
+
|
| 107 |
+
# Fortran file support
|
| 108 |
+
from ._fortran import FortranFile, FortranEOFError, FortranFormattingError
|
| 109 |
+
|
| 110 |
+
from ._fast_matrix_market import mminfo, mmread, mmwrite
|
| 111 |
+
from ._idl import readsav
|
| 112 |
+
from ._harwell_boeing import hb_read, hb_write
|
| 113 |
+
|
| 114 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
| 115 |
+
from . import arff, harwell_boeing, idl, mmio, netcdf, wavfile
|
| 116 |
+
|
| 117 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
| 118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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module to read / write Fortran unformatted sequential files.
|
| 3 |
+
|
| 4 |
+
This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz.
|
| 5 |
+
|
| 6 |
+
"""
|
| 7 |
+
import warnings
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
__all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError']
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class FortranEOFError(TypeError, OSError):
|
| 14 |
+
"""Indicates that the file ended properly.
|
| 15 |
+
|
| 16 |
+
This error descends from TypeError because the code used to raise
|
| 17 |
+
TypeError (and this was the only way to know that the file had
|
| 18 |
+
ended) so users might have ``except TypeError:``.
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class FortranFormattingError(TypeError, OSError):
|
| 25 |
+
"""Indicates that the file ended mid-record.
|
| 26 |
+
|
| 27 |
+
Descends from TypeError for backward compatibility.
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class FortranFile:
|
| 34 |
+
"""
|
| 35 |
+
A file object for unformatted sequential files from Fortran code.
|
| 36 |
+
|
| 37 |
+
Parameters
|
| 38 |
+
----------
|
| 39 |
+
filename : file or str
|
| 40 |
+
Open file object or filename.
|
| 41 |
+
mode : {'r', 'w'}, optional
|
| 42 |
+
Read-write mode, default is 'r'.
|
| 43 |
+
header_dtype : dtype, optional
|
| 44 |
+
Data type of the header. Size and endianness must match the input/output file.
|
| 45 |
+
|
| 46 |
+
Notes
|
| 47 |
+
-----
|
| 48 |
+
These files are broken up into records of unspecified types. The size of
|
| 49 |
+
each record is given at the start (although the size of this header is not
|
| 50 |
+
standard) and the data is written onto disk without any formatting. Fortran
|
| 51 |
+
compilers supporting the BACKSPACE statement will write a second copy of
|
| 52 |
+
the size to facilitate backwards seeking.
|
| 53 |
+
|
| 54 |
+
This class only supports files written with both sizes for the record.
|
| 55 |
+
It also does not support the subrecords used in Intel and gfortran compilers
|
| 56 |
+
for records which are greater than 2GB with a 4-byte header.
|
| 57 |
+
|
| 58 |
+
An example of an unformatted sequential file in Fortran would be written as::
|
| 59 |
+
|
| 60 |
+
OPEN(1, FILE=myfilename, FORM='unformatted')
|
| 61 |
+
|
| 62 |
+
WRITE(1) myvariable
|
| 63 |
+
|
| 64 |
+
Since this is a non-standard file format, whose contents depend on the
|
| 65 |
+
compiler and the endianness of the machine, caution is advised. Files from
|
| 66 |
+
gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work.
|
| 67 |
+
|
| 68 |
+
Consider using Fortran direct-access files or files from the newer Stream
|
| 69 |
+
I/O, which can be easily read by `numpy.fromfile`.
|
| 70 |
+
|
| 71 |
+
Examples
|
| 72 |
+
--------
|
| 73 |
+
To create an unformatted sequential Fortran file:
|
| 74 |
+
|
| 75 |
+
>>> from scipy.io import FortranFile
|
| 76 |
+
>>> import numpy as np
|
| 77 |
+
>>> f = FortranFile('test.unf', 'w')
|
| 78 |
+
>>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32))
|
| 79 |
+
>>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T)
|
| 80 |
+
>>> f.close()
|
| 81 |
+
|
| 82 |
+
To read this file:
|
| 83 |
+
|
| 84 |
+
>>> f = FortranFile('test.unf', 'r')
|
| 85 |
+
>>> print(f.read_ints(np.int32))
|
| 86 |
+
[1 2 3 4 5]
|
| 87 |
+
>>> print(f.read_reals(float).reshape((5,4), order="F"))
|
| 88 |
+
[[0. 0.05263158 0.10526316 0.15789474]
|
| 89 |
+
[0.21052632 0.26315789 0.31578947 0.36842105]
|
| 90 |
+
[0.42105263 0.47368421 0.52631579 0.57894737]
|
| 91 |
+
[0.63157895 0.68421053 0.73684211 0.78947368]
|
| 92 |
+
[0.84210526 0.89473684 0.94736842 1. ]]
|
| 93 |
+
>>> f.close()
|
| 94 |
+
|
| 95 |
+
Or, in Fortran::
|
| 96 |
+
|
| 97 |
+
integer :: a(5), i
|
| 98 |
+
double precision :: b(5,4)
|
| 99 |
+
open(1, file='test.unf', form='unformatted')
|
| 100 |
+
read(1) a
|
| 101 |
+
read(1) b
|
| 102 |
+
close(1)
|
| 103 |
+
write(*,*) a
|
| 104 |
+
do i = 1, 5
|
| 105 |
+
write(*,*) b(i,:)
|
| 106 |
+
end do
|
| 107 |
+
|
| 108 |
+
"""
|
| 109 |
+
def __init__(self, filename, mode='r', header_dtype=np.uint32):
|
| 110 |
+
if header_dtype is None:
|
| 111 |
+
raise ValueError('Must specify dtype')
|
| 112 |
+
|
| 113 |
+
header_dtype = np.dtype(header_dtype)
|
| 114 |
+
if header_dtype.kind != 'u':
|
| 115 |
+
warnings.warn("Given a dtype which is not unsigned.", stacklevel=2)
|
| 116 |
+
|
| 117 |
+
if mode not in 'rw' or len(mode) != 1:
|
| 118 |
+
raise ValueError('mode must be either r or w')
|
| 119 |
+
|
| 120 |
+
if hasattr(filename, 'seek'):
|
| 121 |
+
self._fp = filename
|
| 122 |
+
else:
|
| 123 |
+
self._fp = open(filename, f'{mode}b')
|
| 124 |
+
|
| 125 |
+
self._header_dtype = header_dtype
|
| 126 |
+
|
| 127 |
+
def _read_size(self, eof_ok=False):
|
| 128 |
+
n = self._header_dtype.itemsize
|
| 129 |
+
b = self._fp.read(n)
|
| 130 |
+
if (not b) and eof_ok:
|
| 131 |
+
raise FortranEOFError("End of file occurred at end of record")
|
| 132 |
+
elif len(b) < n:
|
| 133 |
+
raise FortranFormattingError(
|
| 134 |
+
"End of file in the middle of the record size")
|
| 135 |
+
return int(np.frombuffer(b, dtype=self._header_dtype, count=1)[0])
|
| 136 |
+
|
| 137 |
+
def write_record(self, *items):
|
| 138 |
+
"""
|
| 139 |
+
Write a record (including sizes) to the file.
|
| 140 |
+
|
| 141 |
+
Parameters
|
| 142 |
+
----------
|
| 143 |
+
*items : array_like
|
| 144 |
+
The data arrays to write.
|
| 145 |
+
|
| 146 |
+
Notes
|
| 147 |
+
-----
|
| 148 |
+
Writes data items to a file::
|
| 149 |
+
|
| 150 |
+
write_record(a.T, b.T, c.T, ...)
|
| 151 |
+
|
| 152 |
+
write(1) a, b, c, ...
|
| 153 |
+
|
| 154 |
+
Note that data in multidimensional arrays is written in
|
| 155 |
+
row-major order --- to make them read correctly by Fortran
|
| 156 |
+
programs, you need to transpose the arrays yourself when
|
| 157 |
+
writing them.
|
| 158 |
+
|
| 159 |
+
"""
|
| 160 |
+
items = tuple(np.asarray(item) for item in items)
|
| 161 |
+
total_size = sum(item.nbytes for item in items)
|
| 162 |
+
|
| 163 |
+
nb = np.array([total_size], dtype=self._header_dtype)
|
| 164 |
+
|
| 165 |
+
nb.tofile(self._fp)
|
| 166 |
+
for item in items:
|
| 167 |
+
item.tofile(self._fp)
|
| 168 |
+
nb.tofile(self._fp)
|
| 169 |
+
|
| 170 |
+
def read_record(self, *dtypes, **kwargs):
|
| 171 |
+
"""
|
| 172 |
+
Reads a record of a given type from the file.
|
| 173 |
+
|
| 174 |
+
Parameters
|
| 175 |
+
----------
|
| 176 |
+
*dtypes : dtypes, optional
|
| 177 |
+
Data type(s) specifying the size and endianness of the data.
|
| 178 |
+
|
| 179 |
+
Returns
|
| 180 |
+
-------
|
| 181 |
+
data : ndarray
|
| 182 |
+
A 1-D array object.
|
| 183 |
+
|
| 184 |
+
Raises
|
| 185 |
+
------
|
| 186 |
+
FortranEOFError
|
| 187 |
+
To signal that no further records are available
|
| 188 |
+
FortranFormattingError
|
| 189 |
+
To signal that the end of the file was encountered
|
| 190 |
+
part-way through a record
|
| 191 |
+
|
| 192 |
+
Notes
|
| 193 |
+
-----
|
| 194 |
+
If the record contains a multidimensional array, you can specify
|
| 195 |
+
the size in the dtype. For example::
|
| 196 |
+
|
| 197 |
+
INTEGER var(5,4)
|
| 198 |
+
|
| 199 |
+
can be read with::
|
| 200 |
+
|
| 201 |
+
read_record('(4,5)i4').T
|
| 202 |
+
|
| 203 |
+
Note that this function does **not** assume the file data is in Fortran
|
| 204 |
+
column major order, so you need to (i) swap the order of dimensions
|
| 205 |
+
when reading and (ii) transpose the resulting array.
|
| 206 |
+
|
| 207 |
+
Alternatively, you can read the data as a 1-D array and handle the
|
| 208 |
+
ordering yourself. For example::
|
| 209 |
+
|
| 210 |
+
read_record('i4').reshape(5, 4, order='F')
|
| 211 |
+
|
| 212 |
+
For records that contain several variables or mixed types (as opposed
|
| 213 |
+
to single scalar or array types), give them as separate arguments::
|
| 214 |
+
|
| 215 |
+
double precision :: a
|
| 216 |
+
integer :: b
|
| 217 |
+
write(1) a, b
|
| 218 |
+
|
| 219 |
+
record = f.read_record('<f4', '<i4')
|
| 220 |
+
a = record[0] # first number
|
| 221 |
+
b = record[1] # second number
|
| 222 |
+
|
| 223 |
+
and if any of the variables are arrays, the shape can be specified as
|
| 224 |
+
the third item in the relevant dtype::
|
| 225 |
+
|
| 226 |
+
double precision :: a
|
| 227 |
+
integer :: b(3,4)
|
| 228 |
+
write(1) a, b
|
| 229 |
+
|
| 230 |
+
record = f.read_record('<f4', np.dtype(('<i4', (4, 3))))
|
| 231 |
+
a = record[0]
|
| 232 |
+
b = record[1].T
|
| 233 |
+
|
| 234 |
+
NumPy also supports a short syntax for this kind of type::
|
| 235 |
+
|
| 236 |
+
record = f.read_record('<f4', '(3,3)<i4')
|
| 237 |
+
|
| 238 |
+
See Also
|
| 239 |
+
--------
|
| 240 |
+
read_reals
|
| 241 |
+
read_ints
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
dtype = kwargs.pop('dtype', None)
|
| 245 |
+
if kwargs:
|
| 246 |
+
raise ValueError(f"Unknown keyword arguments {tuple(kwargs.keys())}")
|
| 247 |
+
|
| 248 |
+
if dtype is not None:
|
| 249 |
+
dtypes = dtypes + (dtype,)
|
| 250 |
+
elif not dtypes:
|
| 251 |
+
raise ValueError('Must specify at least one dtype')
|
| 252 |
+
|
| 253 |
+
first_size = self._read_size(eof_ok=True)
|
| 254 |
+
|
| 255 |
+
dtypes = tuple(np.dtype(dtype) for dtype in dtypes)
|
| 256 |
+
block_size = sum(dtype.itemsize for dtype in dtypes)
|
| 257 |
+
|
| 258 |
+
num_blocks, remainder = divmod(first_size, block_size)
|
| 259 |
+
if remainder != 0:
|
| 260 |
+
raise ValueError(f'Size obtained ({first_size}) is not a multiple of the '
|
| 261 |
+
f'dtypes given ({block_size}).')
|
| 262 |
+
|
| 263 |
+
if len(dtypes) != 1 and first_size != block_size:
|
| 264 |
+
# Fortran does not write mixed type array items in interleaved order,
|
| 265 |
+
# and it's not possible to guess the sizes of the arrays that were written.
|
| 266 |
+
# The user must specify the exact sizes of each of the arrays.
|
| 267 |
+
raise ValueError(f'Size obtained ({first_size}) does not match with the '
|
| 268 |
+
f'expected size ({block_size}) of multi-item record')
|
| 269 |
+
|
| 270 |
+
data = []
|
| 271 |
+
for dtype in dtypes:
|
| 272 |
+
r = np.fromfile(self._fp, dtype=dtype, count=num_blocks)
|
| 273 |
+
if len(r) != num_blocks:
|
| 274 |
+
raise FortranFormattingError(
|
| 275 |
+
"End of file in the middle of a record")
|
| 276 |
+
if dtype.shape != ():
|
| 277 |
+
# Squeeze outmost block dimension for array items
|
| 278 |
+
if num_blocks == 1:
|
| 279 |
+
assert r.shape == (1,) + dtype.shape
|
| 280 |
+
r = r[0]
|
| 281 |
+
|
| 282 |
+
data.append(r)
|
| 283 |
+
|
| 284 |
+
second_size = self._read_size()
|
| 285 |
+
if first_size != second_size:
|
| 286 |
+
raise ValueError('Sizes do not agree in the header and footer for '
|
| 287 |
+
'this record - check header dtype')
|
| 288 |
+
|
| 289 |
+
# Unpack result
|
| 290 |
+
if len(dtypes) == 1:
|
| 291 |
+
return data[0]
|
| 292 |
+
else:
|
| 293 |
+
return tuple(data)
|
| 294 |
+
|
| 295 |
+
def read_ints(self, dtype='i4'):
|
| 296 |
+
"""
|
| 297 |
+
Reads a record of a given type from the file, defaulting to an integer
|
| 298 |
+
type (``INTEGER*4`` in Fortran).
|
| 299 |
+
|
| 300 |
+
Parameters
|
| 301 |
+
----------
|
| 302 |
+
dtype : dtype, optional
|
| 303 |
+
Data type specifying the size and endianness of the data.
|
| 304 |
+
|
| 305 |
+
Returns
|
| 306 |
+
-------
|
| 307 |
+
data : ndarray
|
| 308 |
+
A 1-D array object.
|
| 309 |
+
|
| 310 |
+
See Also
|
| 311 |
+
--------
|
| 312 |
+
read_reals
|
| 313 |
+
read_record
|
| 314 |
+
|
| 315 |
+
"""
|
| 316 |
+
return self.read_record(dtype)
|
| 317 |
+
|
| 318 |
+
def read_reals(self, dtype='f8'):
|
| 319 |
+
"""
|
| 320 |
+
Reads a record of a given type from the file, defaulting to a floating
|
| 321 |
+
point number (``real*8`` in Fortran).
|
| 322 |
+
|
| 323 |
+
Parameters
|
| 324 |
+
----------
|
| 325 |
+
dtype : dtype, optional
|
| 326 |
+
Data type specifying the size and endianness of the data.
|
| 327 |
+
|
| 328 |
+
Returns
|
| 329 |
+
-------
|
| 330 |
+
data : ndarray
|
| 331 |
+
A 1-D array object.
|
| 332 |
+
|
| 333 |
+
See Also
|
| 334 |
+
--------
|
| 335 |
+
read_ints
|
| 336 |
+
read_record
|
| 337 |
+
|
| 338 |
+
"""
|
| 339 |
+
return self.read_record(dtype)
|
| 340 |
+
|
| 341 |
+
def close(self):
|
| 342 |
+
"""
|
| 343 |
+
Closes the file. It is unsupported to call any other methods off this
|
| 344 |
+
object after closing it. Note that this class supports the 'with'
|
| 345 |
+
statement in modern versions of Python, to call this automatically
|
| 346 |
+
|
| 347 |
+
"""
|
| 348 |
+
self._fp.close()
|
| 349 |
+
|
| 350 |
+
def __enter__(self):
|
| 351 |
+
return self
|
| 352 |
+
|
| 353 |
+
def __exit__(self, type, value, tb):
|
| 354 |
+
self.close()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/_idl.py
ADDED
|
@@ -0,0 +1,917 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# IDLSave - a python module to read IDL 'save' files
|
| 2 |
+
# Copyright (c) 2010 Thomas P. Robitaille
|
| 3 |
+
|
| 4 |
+
# Many thanks to Craig Markwardt for publishing the Unofficial Format
|
| 5 |
+
# Specification for IDL .sav files, without which this Python module would not
|
| 6 |
+
# exist (http://cow.physics.wisc.edu/~craigm/idl/savefmt).
|
| 7 |
+
|
| 8 |
+
# This code was developed by with permission from ITT Visual Information
|
| 9 |
+
# Systems. IDL(r) is a registered trademark of ITT Visual Information Systems,
|
| 10 |
+
# Inc. for their Interactive Data Language software.
|
| 11 |
+
|
| 12 |
+
# Permission is hereby granted, free of charge, to any person obtaining a
|
| 13 |
+
# copy of this software and associated documentation files (the "Software"),
|
| 14 |
+
# to deal in the Software without restriction, including without limitation
|
| 15 |
+
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 16 |
+
# and/or sell copies of the Software, and to permit persons to whom the
|
| 17 |
+
# Software is furnished to do so, subject to the following conditions:
|
| 18 |
+
|
| 19 |
+
# The above copyright notice and this permission notice shall be included in
|
| 20 |
+
# all copies or substantial portions of the Software.
|
| 21 |
+
|
| 22 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 23 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 24 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 25 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 26 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 27 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 28 |
+
# DEALINGS IN THE SOFTWARE.
|
| 29 |
+
|
| 30 |
+
__all__ = ['readsav']
|
| 31 |
+
|
| 32 |
+
import struct
|
| 33 |
+
import numpy as np
|
| 34 |
+
import tempfile
|
| 35 |
+
import zlib
|
| 36 |
+
import warnings
|
| 37 |
+
|
| 38 |
+
# Define the different data types that can be found in an IDL save file
|
| 39 |
+
DTYPE_DICT = {1: '>u1',
|
| 40 |
+
2: '>i2',
|
| 41 |
+
3: '>i4',
|
| 42 |
+
4: '>f4',
|
| 43 |
+
5: '>f8',
|
| 44 |
+
6: '>c8',
|
| 45 |
+
7: '|O',
|
| 46 |
+
8: '|O',
|
| 47 |
+
9: '>c16',
|
| 48 |
+
10: '|O',
|
| 49 |
+
11: '|O',
|
| 50 |
+
12: '>u2',
|
| 51 |
+
13: '>u4',
|
| 52 |
+
14: '>i8',
|
| 53 |
+
15: '>u8'}
|
| 54 |
+
|
| 55 |
+
# Define the different record types that can be found in an IDL save file
|
| 56 |
+
RECTYPE_DICT = {0: "START_MARKER",
|
| 57 |
+
1: "COMMON_VARIABLE",
|
| 58 |
+
2: "VARIABLE",
|
| 59 |
+
3: "SYSTEM_VARIABLE",
|
| 60 |
+
6: "END_MARKER",
|
| 61 |
+
10: "TIMESTAMP",
|
| 62 |
+
12: "COMPILED",
|
| 63 |
+
13: "IDENTIFICATION",
|
| 64 |
+
14: "VERSION",
|
| 65 |
+
15: "HEAP_HEADER",
|
| 66 |
+
16: "HEAP_DATA",
|
| 67 |
+
17: "PROMOTE64",
|
| 68 |
+
19: "NOTICE",
|
| 69 |
+
20: "DESCRIPTION"}
|
| 70 |
+
|
| 71 |
+
# Define a dictionary to contain structure definitions
|
| 72 |
+
STRUCT_DICT = {}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _align_32(f):
|
| 76 |
+
'''Align to the next 32-bit position in a file'''
|
| 77 |
+
|
| 78 |
+
pos = f.tell()
|
| 79 |
+
if pos % 4 != 0:
|
| 80 |
+
f.seek(pos + 4 - pos % 4)
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _skip_bytes(f, n):
|
| 85 |
+
'''Skip `n` bytes'''
|
| 86 |
+
f.read(n)
|
| 87 |
+
return
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _read_bytes(f, n):
|
| 91 |
+
'''Read the next `n` bytes'''
|
| 92 |
+
return f.read(n)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _read_byte(f):
|
| 96 |
+
'''Read a single byte'''
|
| 97 |
+
return np.uint8(struct.unpack('>B', f.read(4)[:1])[0])
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _read_long(f):
|
| 101 |
+
'''Read a signed 32-bit integer'''
|
| 102 |
+
return np.int32(struct.unpack('>l', f.read(4))[0])
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _read_int16(f):
|
| 106 |
+
'''Read a signed 16-bit integer'''
|
| 107 |
+
return np.int16(struct.unpack('>h', f.read(4)[2:4])[0])
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _read_int32(f):
|
| 111 |
+
'''Read a signed 32-bit integer'''
|
| 112 |
+
return np.int32(struct.unpack('>i', f.read(4))[0])
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _read_int64(f):
|
| 116 |
+
'''Read a signed 64-bit integer'''
|
| 117 |
+
return np.int64(struct.unpack('>q', f.read(8))[0])
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _read_uint16(f):
|
| 121 |
+
'''Read an unsigned 16-bit integer'''
|
| 122 |
+
return np.uint16(struct.unpack('>H', f.read(4)[2:4])[0])
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _read_uint32(f):
|
| 126 |
+
'''Read an unsigned 32-bit integer'''
|
| 127 |
+
return np.uint32(struct.unpack('>I', f.read(4))[0])
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _read_uint64(f):
|
| 131 |
+
'''Read an unsigned 64-bit integer'''
|
| 132 |
+
return np.uint64(struct.unpack('>Q', f.read(8))[0])
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _read_float32(f):
|
| 136 |
+
'''Read a 32-bit float'''
|
| 137 |
+
return np.float32(struct.unpack('>f', f.read(4))[0])
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _read_float64(f):
|
| 141 |
+
'''Read a 64-bit float'''
|
| 142 |
+
return np.float64(struct.unpack('>d', f.read(8))[0])
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class Pointer:
|
| 146 |
+
'''Class used to define pointers'''
|
| 147 |
+
|
| 148 |
+
def __init__(self, index):
|
| 149 |
+
self.index = index
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class ObjectPointer(Pointer):
|
| 154 |
+
'''Class used to define object pointers'''
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _read_string(f):
|
| 159 |
+
'''Read a string'''
|
| 160 |
+
length = _read_long(f)
|
| 161 |
+
if length > 0:
|
| 162 |
+
chars = _read_bytes(f, length).decode('latin1')
|
| 163 |
+
_align_32(f)
|
| 164 |
+
else:
|
| 165 |
+
chars = ''
|
| 166 |
+
return chars
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _read_string_data(f):
|
| 170 |
+
'''Read a data string (length is specified twice)'''
|
| 171 |
+
length = _read_long(f)
|
| 172 |
+
if length > 0:
|
| 173 |
+
length = _read_long(f)
|
| 174 |
+
string_data = _read_bytes(f, length)
|
| 175 |
+
_align_32(f)
|
| 176 |
+
else:
|
| 177 |
+
string_data = ''
|
| 178 |
+
return string_data
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _read_data(f, dtype):
|
| 182 |
+
'''Read a variable with a specified data type'''
|
| 183 |
+
if dtype == 1:
|
| 184 |
+
if _read_int32(f) != 1:
|
| 185 |
+
raise Exception("Error occurred while reading byte variable")
|
| 186 |
+
return _read_byte(f)
|
| 187 |
+
elif dtype == 2:
|
| 188 |
+
return _read_int16(f)
|
| 189 |
+
elif dtype == 3:
|
| 190 |
+
return _read_int32(f)
|
| 191 |
+
elif dtype == 4:
|
| 192 |
+
return _read_float32(f)
|
| 193 |
+
elif dtype == 5:
|
| 194 |
+
return _read_float64(f)
|
| 195 |
+
elif dtype == 6:
|
| 196 |
+
real = _read_float32(f)
|
| 197 |
+
imag = _read_float32(f)
|
| 198 |
+
return np.complex64(real + imag * 1j)
|
| 199 |
+
elif dtype == 7:
|
| 200 |
+
return _read_string_data(f)
|
| 201 |
+
elif dtype == 8:
|
| 202 |
+
raise Exception("Should not be here - please report this")
|
| 203 |
+
elif dtype == 9:
|
| 204 |
+
real = _read_float64(f)
|
| 205 |
+
imag = _read_float64(f)
|
| 206 |
+
return np.complex128(real + imag * 1j)
|
| 207 |
+
elif dtype == 10:
|
| 208 |
+
return Pointer(_read_int32(f))
|
| 209 |
+
elif dtype == 11:
|
| 210 |
+
return ObjectPointer(_read_int32(f))
|
| 211 |
+
elif dtype == 12:
|
| 212 |
+
return _read_uint16(f)
|
| 213 |
+
elif dtype == 13:
|
| 214 |
+
return _read_uint32(f)
|
| 215 |
+
elif dtype == 14:
|
| 216 |
+
return _read_int64(f)
|
| 217 |
+
elif dtype == 15:
|
| 218 |
+
return _read_uint64(f)
|
| 219 |
+
else:
|
| 220 |
+
raise Exception(f"Unknown IDL type: {dtype} - please report this")
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _read_structure(f, array_desc, struct_desc):
|
| 224 |
+
'''
|
| 225 |
+
Read a structure, with the array and structure descriptors given as
|
| 226 |
+
`array_desc` and `structure_desc` respectively.
|
| 227 |
+
'''
|
| 228 |
+
|
| 229 |
+
nrows = array_desc['nelements']
|
| 230 |
+
columns = struct_desc['tagtable']
|
| 231 |
+
|
| 232 |
+
dtype = []
|
| 233 |
+
for col in columns:
|
| 234 |
+
if col['structure'] or col['array']:
|
| 235 |
+
dtype.append(((col['name'].lower(), col['name']), np.object_))
|
| 236 |
+
else:
|
| 237 |
+
if col['typecode'] in DTYPE_DICT:
|
| 238 |
+
dtype.append(((col['name'].lower(), col['name']),
|
| 239 |
+
DTYPE_DICT[col['typecode']]))
|
| 240 |
+
else:
|
| 241 |
+
raise Exception(f"Variable type {col['typecode']} not implemented")
|
| 242 |
+
|
| 243 |
+
structure = np.rec.recarray((nrows, ), dtype=dtype)
|
| 244 |
+
|
| 245 |
+
for i in range(nrows):
|
| 246 |
+
for col in columns:
|
| 247 |
+
dtype = col['typecode']
|
| 248 |
+
if col['structure']:
|
| 249 |
+
structure[col['name']][i] = _read_structure(f,
|
| 250 |
+
struct_desc['arrtable'][col['name']],
|
| 251 |
+
struct_desc['structtable'][col['name']])
|
| 252 |
+
elif col['array']:
|
| 253 |
+
structure[col['name']][i] = _read_array(f, dtype,
|
| 254 |
+
struct_desc['arrtable'][col['name']])
|
| 255 |
+
else:
|
| 256 |
+
structure[col['name']][i] = _read_data(f, dtype)
|
| 257 |
+
|
| 258 |
+
# Reshape structure if needed
|
| 259 |
+
if array_desc['ndims'] > 1:
|
| 260 |
+
dims = array_desc['dims'][:int(array_desc['ndims'])]
|
| 261 |
+
dims.reverse()
|
| 262 |
+
structure = structure.reshape(dims)
|
| 263 |
+
|
| 264 |
+
return structure
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _read_array(f, typecode, array_desc):
|
| 268 |
+
'''
|
| 269 |
+
Read an array of type `typecode`, with the array descriptor given as
|
| 270 |
+
`array_desc`.
|
| 271 |
+
'''
|
| 272 |
+
|
| 273 |
+
if typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]:
|
| 274 |
+
|
| 275 |
+
if typecode == 1:
|
| 276 |
+
nbytes = _read_int32(f)
|
| 277 |
+
if nbytes != array_desc['nbytes']:
|
| 278 |
+
warnings.warn("Not able to verify number of bytes from header",
|
| 279 |
+
stacklevel=3)
|
| 280 |
+
|
| 281 |
+
# Read bytes as numpy array
|
| 282 |
+
array = np.frombuffer(f.read(array_desc['nbytes']),
|
| 283 |
+
dtype=DTYPE_DICT[typecode])
|
| 284 |
+
|
| 285 |
+
elif typecode in [2, 12]:
|
| 286 |
+
|
| 287 |
+
# These are 2 byte types, need to skip every two as they are not packed
|
| 288 |
+
|
| 289 |
+
array = np.frombuffer(f.read(array_desc['nbytes']*2),
|
| 290 |
+
dtype=DTYPE_DICT[typecode])[1::2]
|
| 291 |
+
|
| 292 |
+
else:
|
| 293 |
+
|
| 294 |
+
# Read bytes into list
|
| 295 |
+
array = []
|
| 296 |
+
for i in range(array_desc['nelements']):
|
| 297 |
+
dtype = typecode
|
| 298 |
+
data = _read_data(f, dtype)
|
| 299 |
+
array.append(data)
|
| 300 |
+
|
| 301 |
+
array = np.array(array, dtype=np.object_)
|
| 302 |
+
|
| 303 |
+
# Reshape array if needed
|
| 304 |
+
if array_desc['ndims'] > 1:
|
| 305 |
+
dims = array_desc['dims'][:int(array_desc['ndims'])]
|
| 306 |
+
dims.reverse()
|
| 307 |
+
array = array.reshape(dims)
|
| 308 |
+
|
| 309 |
+
# Go to next alignment position
|
| 310 |
+
_align_32(f)
|
| 311 |
+
|
| 312 |
+
return array
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _read_record(f):
|
| 316 |
+
'''Function to read in a full record'''
|
| 317 |
+
|
| 318 |
+
record = {'rectype': _read_long(f)}
|
| 319 |
+
|
| 320 |
+
nextrec = _read_uint32(f)
|
| 321 |
+
nextrec += _read_uint32(f).astype(np.int64) * 2**32
|
| 322 |
+
|
| 323 |
+
_skip_bytes(f, 4)
|
| 324 |
+
|
| 325 |
+
if record['rectype'] not in RECTYPE_DICT:
|
| 326 |
+
raise Exception(f"Unknown RECTYPE: {record['rectype']}")
|
| 327 |
+
|
| 328 |
+
record['rectype'] = RECTYPE_DICT[record['rectype']]
|
| 329 |
+
|
| 330 |
+
if record['rectype'] in ["VARIABLE", "HEAP_DATA"]:
|
| 331 |
+
|
| 332 |
+
if record['rectype'] == "VARIABLE":
|
| 333 |
+
record['varname'] = _read_string(f)
|
| 334 |
+
else:
|
| 335 |
+
record['heap_index'] = _read_long(f)
|
| 336 |
+
_skip_bytes(f, 4)
|
| 337 |
+
|
| 338 |
+
rectypedesc = _read_typedesc(f)
|
| 339 |
+
|
| 340 |
+
if rectypedesc['typecode'] == 0:
|
| 341 |
+
|
| 342 |
+
if nextrec == f.tell():
|
| 343 |
+
record['data'] = None # Indicates NULL value
|
| 344 |
+
else:
|
| 345 |
+
raise ValueError("Unexpected type code: 0")
|
| 346 |
+
|
| 347 |
+
else:
|
| 348 |
+
|
| 349 |
+
varstart = _read_long(f)
|
| 350 |
+
if varstart != 7:
|
| 351 |
+
raise Exception("VARSTART is not 7")
|
| 352 |
+
|
| 353 |
+
if rectypedesc['structure']:
|
| 354 |
+
record['data'] = _read_structure(f, rectypedesc['array_desc'],
|
| 355 |
+
rectypedesc['struct_desc'])
|
| 356 |
+
elif rectypedesc['array']:
|
| 357 |
+
record['data'] = _read_array(f, rectypedesc['typecode'],
|
| 358 |
+
rectypedesc['array_desc'])
|
| 359 |
+
else:
|
| 360 |
+
dtype = rectypedesc['typecode']
|
| 361 |
+
record['data'] = _read_data(f, dtype)
|
| 362 |
+
|
| 363 |
+
elif record['rectype'] == "TIMESTAMP":
|
| 364 |
+
|
| 365 |
+
_skip_bytes(f, 4*256)
|
| 366 |
+
record['date'] = _read_string(f)
|
| 367 |
+
record['user'] = _read_string(f)
|
| 368 |
+
record['host'] = _read_string(f)
|
| 369 |
+
|
| 370 |
+
elif record['rectype'] == "VERSION":
|
| 371 |
+
|
| 372 |
+
record['format'] = _read_long(f)
|
| 373 |
+
record['arch'] = _read_string(f)
|
| 374 |
+
record['os'] = _read_string(f)
|
| 375 |
+
record['release'] = _read_string(f)
|
| 376 |
+
|
| 377 |
+
elif record['rectype'] == "IDENTIFICATON":
|
| 378 |
+
|
| 379 |
+
record['author'] = _read_string(f)
|
| 380 |
+
record['title'] = _read_string(f)
|
| 381 |
+
record['idcode'] = _read_string(f)
|
| 382 |
+
|
| 383 |
+
elif record['rectype'] == "NOTICE":
|
| 384 |
+
|
| 385 |
+
record['notice'] = _read_string(f)
|
| 386 |
+
|
| 387 |
+
elif record['rectype'] == "DESCRIPTION":
|
| 388 |
+
|
| 389 |
+
record['description'] = _read_string_data(f)
|
| 390 |
+
|
| 391 |
+
elif record['rectype'] == "HEAP_HEADER":
|
| 392 |
+
|
| 393 |
+
record['nvalues'] = _read_long(f)
|
| 394 |
+
record['indices'] = [_read_long(f) for _ in range(record['nvalues'])]
|
| 395 |
+
|
| 396 |
+
elif record['rectype'] == "COMMONBLOCK":
|
| 397 |
+
|
| 398 |
+
record['nvars'] = _read_long(f)
|
| 399 |
+
record['name'] = _read_string(f)
|
| 400 |
+
record['varnames'] = [_read_string(f) for _ in range(record['nvars'])]
|
| 401 |
+
|
| 402 |
+
elif record['rectype'] == "END_MARKER":
|
| 403 |
+
|
| 404 |
+
record['end'] = True
|
| 405 |
+
|
| 406 |
+
elif record['rectype'] == "UNKNOWN":
|
| 407 |
+
|
| 408 |
+
warnings.warn("Skipping UNKNOWN record", stacklevel=3)
|
| 409 |
+
|
| 410 |
+
elif record['rectype'] == "SYSTEM_VARIABLE":
|
| 411 |
+
|
| 412 |
+
warnings.warn("Skipping SYSTEM_VARIABLE record", stacklevel=3)
|
| 413 |
+
|
| 414 |
+
else:
|
| 415 |
+
|
| 416 |
+
raise Exception(f"record['rectype']={record['rectype']} not implemented")
|
| 417 |
+
|
| 418 |
+
f.seek(nextrec)
|
| 419 |
+
|
| 420 |
+
return record
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _read_typedesc(f):
|
| 424 |
+
'''Function to read in a type descriptor'''
|
| 425 |
+
|
| 426 |
+
typedesc = {'typecode': _read_long(f), 'varflags': _read_long(f)}
|
| 427 |
+
|
| 428 |
+
if typedesc['varflags'] & 2 == 2:
|
| 429 |
+
raise Exception("System variables not implemented")
|
| 430 |
+
|
| 431 |
+
typedesc['array'] = typedesc['varflags'] & 4 == 4
|
| 432 |
+
typedesc['structure'] = typedesc['varflags'] & 32 == 32
|
| 433 |
+
|
| 434 |
+
if typedesc['structure']:
|
| 435 |
+
typedesc['array_desc'] = _read_arraydesc(f)
|
| 436 |
+
typedesc['struct_desc'] = _read_structdesc(f)
|
| 437 |
+
elif typedesc['array']:
|
| 438 |
+
typedesc['array_desc'] = _read_arraydesc(f)
|
| 439 |
+
|
| 440 |
+
return typedesc
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def _read_arraydesc(f):
|
| 444 |
+
'''Function to read in an array descriptor'''
|
| 445 |
+
|
| 446 |
+
arraydesc = {'arrstart': _read_long(f)}
|
| 447 |
+
|
| 448 |
+
if arraydesc['arrstart'] == 8:
|
| 449 |
+
|
| 450 |
+
_skip_bytes(f, 4)
|
| 451 |
+
|
| 452 |
+
arraydesc['nbytes'] = _read_long(f)
|
| 453 |
+
arraydesc['nelements'] = _read_long(f)
|
| 454 |
+
arraydesc['ndims'] = _read_long(f)
|
| 455 |
+
|
| 456 |
+
_skip_bytes(f, 8)
|
| 457 |
+
|
| 458 |
+
arraydesc['nmax'] = _read_long(f)
|
| 459 |
+
|
| 460 |
+
arraydesc['dims'] = [_read_long(f) for _ in range(arraydesc['nmax'])]
|
| 461 |
+
|
| 462 |
+
elif arraydesc['arrstart'] == 18:
|
| 463 |
+
|
| 464 |
+
warnings.warn("Using experimental 64-bit array read", stacklevel=3)
|
| 465 |
+
|
| 466 |
+
_skip_bytes(f, 8)
|
| 467 |
+
|
| 468 |
+
arraydesc['nbytes'] = _read_uint64(f)
|
| 469 |
+
arraydesc['nelements'] = _read_uint64(f)
|
| 470 |
+
arraydesc['ndims'] = _read_long(f)
|
| 471 |
+
|
| 472 |
+
_skip_bytes(f, 8)
|
| 473 |
+
|
| 474 |
+
arraydesc['nmax'] = 8
|
| 475 |
+
|
| 476 |
+
arraydesc['dims'] = []
|
| 477 |
+
for d in range(arraydesc['nmax']):
|
| 478 |
+
v = _read_long(f)
|
| 479 |
+
if v != 0:
|
| 480 |
+
raise Exception("Expected a zero in ARRAY_DESC")
|
| 481 |
+
arraydesc['dims'].append(_read_long(f))
|
| 482 |
+
|
| 483 |
+
else:
|
| 484 |
+
raise Exception(f"Unknown ARRSTART: {arraydesc['arrstart']}")
|
| 485 |
+
|
| 486 |
+
return arraydesc
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _read_structdesc(f):
|
| 490 |
+
'''Function to read in a structure descriptor'''
|
| 491 |
+
|
| 492 |
+
structdesc = {}
|
| 493 |
+
|
| 494 |
+
structstart = _read_long(f)
|
| 495 |
+
if structstart != 9:
|
| 496 |
+
raise Exception("STRUCTSTART should be 9")
|
| 497 |
+
|
| 498 |
+
structdesc['name'] = _read_string(f)
|
| 499 |
+
predef = _read_long(f)
|
| 500 |
+
structdesc['ntags'] = _read_long(f)
|
| 501 |
+
structdesc['nbytes'] = _read_long(f)
|
| 502 |
+
|
| 503 |
+
structdesc['predef'] = predef & 1
|
| 504 |
+
structdesc['inherits'] = predef & 2
|
| 505 |
+
structdesc['is_super'] = predef & 4
|
| 506 |
+
|
| 507 |
+
if not structdesc['predef']:
|
| 508 |
+
|
| 509 |
+
structdesc['tagtable'] = [_read_tagdesc(f)
|
| 510 |
+
for _ in range(structdesc['ntags'])]
|
| 511 |
+
|
| 512 |
+
for tag in structdesc['tagtable']:
|
| 513 |
+
tag['name'] = _read_string(f)
|
| 514 |
+
|
| 515 |
+
structdesc['arrtable'] = {tag['name']: _read_arraydesc(f)
|
| 516 |
+
for tag in structdesc['tagtable']
|
| 517 |
+
if tag['array']}
|
| 518 |
+
|
| 519 |
+
structdesc['structtable'] = {tag['name']: _read_structdesc(f)
|
| 520 |
+
for tag in structdesc['tagtable']
|
| 521 |
+
if tag['structure']}
|
| 522 |
+
|
| 523 |
+
if structdesc['inherits'] or structdesc['is_super']:
|
| 524 |
+
structdesc['classname'] = _read_string(f)
|
| 525 |
+
structdesc['nsupclasses'] = _read_long(f)
|
| 526 |
+
structdesc['supclassnames'] = [
|
| 527 |
+
_read_string(f) for _ in range(structdesc['nsupclasses'])]
|
| 528 |
+
structdesc['supclasstable'] = [
|
| 529 |
+
_read_structdesc(f) for _ in range(structdesc['nsupclasses'])]
|
| 530 |
+
|
| 531 |
+
STRUCT_DICT[structdesc['name']] = structdesc
|
| 532 |
+
|
| 533 |
+
else:
|
| 534 |
+
|
| 535 |
+
if structdesc['name'] not in STRUCT_DICT:
|
| 536 |
+
raise Exception("PREDEF=1 but can't find definition")
|
| 537 |
+
|
| 538 |
+
structdesc = STRUCT_DICT[structdesc['name']]
|
| 539 |
+
|
| 540 |
+
return structdesc
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def _read_tagdesc(f):
|
| 544 |
+
'''Function to read in a tag descriptor'''
|
| 545 |
+
|
| 546 |
+
tagdesc = {'offset': _read_long(f)}
|
| 547 |
+
|
| 548 |
+
if tagdesc['offset'] == -1:
|
| 549 |
+
tagdesc['offset'] = _read_uint64(f)
|
| 550 |
+
|
| 551 |
+
tagdesc['typecode'] = _read_long(f)
|
| 552 |
+
tagflags = _read_long(f)
|
| 553 |
+
|
| 554 |
+
tagdesc['array'] = tagflags & 4 == 4
|
| 555 |
+
tagdesc['structure'] = tagflags & 32 == 32
|
| 556 |
+
tagdesc['scalar'] = tagdesc['typecode'] in DTYPE_DICT
|
| 557 |
+
# Assume '10'x is scalar
|
| 558 |
+
|
| 559 |
+
return tagdesc
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _replace_heap(variable, heap):
|
| 563 |
+
|
| 564 |
+
if isinstance(variable, Pointer):
|
| 565 |
+
|
| 566 |
+
while isinstance(variable, Pointer):
|
| 567 |
+
|
| 568 |
+
if variable.index == 0:
|
| 569 |
+
variable = None
|
| 570 |
+
else:
|
| 571 |
+
if variable.index in heap:
|
| 572 |
+
variable = heap[variable.index]
|
| 573 |
+
else:
|
| 574 |
+
warnings.warn("Variable referenced by pointer not found "
|
| 575 |
+
"in heap: variable will be set to None",
|
| 576 |
+
stacklevel=3)
|
| 577 |
+
variable = None
|
| 578 |
+
|
| 579 |
+
replace, new = _replace_heap(variable, heap)
|
| 580 |
+
|
| 581 |
+
if replace:
|
| 582 |
+
variable = new
|
| 583 |
+
|
| 584 |
+
return True, variable
|
| 585 |
+
|
| 586 |
+
elif isinstance(variable, np.rec.recarray):
|
| 587 |
+
|
| 588 |
+
# Loop over records
|
| 589 |
+
for ir, record in enumerate(variable):
|
| 590 |
+
|
| 591 |
+
replace, new = _replace_heap(record, heap)
|
| 592 |
+
|
| 593 |
+
if replace:
|
| 594 |
+
variable[ir] = new
|
| 595 |
+
|
| 596 |
+
return False, variable
|
| 597 |
+
|
| 598 |
+
elif isinstance(variable, np.record):
|
| 599 |
+
|
| 600 |
+
# Loop over values
|
| 601 |
+
for iv, value in enumerate(variable):
|
| 602 |
+
|
| 603 |
+
replace, new = _replace_heap(value, heap)
|
| 604 |
+
|
| 605 |
+
if replace:
|
| 606 |
+
variable[iv] = new
|
| 607 |
+
|
| 608 |
+
return False, variable
|
| 609 |
+
|
| 610 |
+
elif isinstance(variable, np.ndarray):
|
| 611 |
+
|
| 612 |
+
# Loop over values if type is np.object_
|
| 613 |
+
if variable.dtype.type is np.object_:
|
| 614 |
+
|
| 615 |
+
for iv in range(variable.size):
|
| 616 |
+
|
| 617 |
+
replace, new = _replace_heap(variable.item(iv), heap)
|
| 618 |
+
|
| 619 |
+
if replace:
|
| 620 |
+
variable.reshape(-1)[iv] = new
|
| 621 |
+
|
| 622 |
+
return False, variable
|
| 623 |
+
|
| 624 |
+
else:
|
| 625 |
+
|
| 626 |
+
return False, variable
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
class AttrDict(dict):
|
| 630 |
+
'''
|
| 631 |
+
A case-insensitive dictionary with access via item, attribute, and call
|
| 632 |
+
notations:
|
| 633 |
+
|
| 634 |
+
>>> from scipy.io._idl import AttrDict
|
| 635 |
+
>>> d = AttrDict()
|
| 636 |
+
>>> d['Variable'] = 123
|
| 637 |
+
>>> d['Variable']
|
| 638 |
+
123
|
| 639 |
+
>>> d.Variable
|
| 640 |
+
123
|
| 641 |
+
>>> d.variable
|
| 642 |
+
123
|
| 643 |
+
>>> d('VARIABLE')
|
| 644 |
+
123
|
| 645 |
+
>>> d['missing']
|
| 646 |
+
Traceback (most recent error last):
|
| 647 |
+
...
|
| 648 |
+
KeyError: 'missing'
|
| 649 |
+
>>> d.missing
|
| 650 |
+
Traceback (most recent error last):
|
| 651 |
+
...
|
| 652 |
+
AttributeError: 'AttrDict' object has no attribute 'missing'
|
| 653 |
+
'''
|
| 654 |
+
|
| 655 |
+
def __init__(self, init=None):
|
| 656 |
+
if init is None:
|
| 657 |
+
init = {}
|
| 658 |
+
dict.__init__(self, init)
|
| 659 |
+
|
| 660 |
+
def __getitem__(self, name):
|
| 661 |
+
return super().__getitem__(name.lower())
|
| 662 |
+
|
| 663 |
+
def __setitem__(self, key, value):
|
| 664 |
+
return super().__setitem__(key.lower(), value)
|
| 665 |
+
|
| 666 |
+
def __getattr__(self, name):
|
| 667 |
+
try:
|
| 668 |
+
return self.__getitem__(name)
|
| 669 |
+
except KeyError:
|
| 670 |
+
raise AttributeError(
|
| 671 |
+
f"'{type(self)}' object has no attribute '{name}'") from None
|
| 672 |
+
|
| 673 |
+
__setattr__ = __setitem__
|
| 674 |
+
__call__ = __getitem__
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def readsav(file_name, idict=None, python_dict=False,
|
| 678 |
+
uncompressed_file_name=None, verbose=False):
|
| 679 |
+
"""
|
| 680 |
+
Read an IDL .sav file.
|
| 681 |
+
|
| 682 |
+
Parameters
|
| 683 |
+
----------
|
| 684 |
+
file_name : str
|
| 685 |
+
Name of the IDL save file.
|
| 686 |
+
idict : dict, optional
|
| 687 |
+
Dictionary in which to insert .sav file variables.
|
| 688 |
+
python_dict : bool, optional
|
| 689 |
+
By default, the object return is not a Python dictionary, but a
|
| 690 |
+
case-insensitive dictionary with item, attribute, and call access
|
| 691 |
+
to variables. To get a standard Python dictionary, set this option
|
| 692 |
+
to True.
|
| 693 |
+
uncompressed_file_name : str, optional
|
| 694 |
+
This option only has an effect for .sav files written with the
|
| 695 |
+
/compress option. If a file name is specified, compressed .sav
|
| 696 |
+
files are uncompressed to this file. Otherwise, readsav will use
|
| 697 |
+
the `tempfile` module to determine a temporary filename
|
| 698 |
+
automatically, and will remove the temporary file upon successfully
|
| 699 |
+
reading it in.
|
| 700 |
+
verbose : bool, optional
|
| 701 |
+
Whether to print out information about the save file, including
|
| 702 |
+
the records read, and available variables.
|
| 703 |
+
|
| 704 |
+
Returns
|
| 705 |
+
-------
|
| 706 |
+
idl_dict : AttrDict or dict
|
| 707 |
+
If `python_dict` is set to False (default), this function returns a
|
| 708 |
+
case-insensitive dictionary with item, attribute, and call access
|
| 709 |
+
to variables. If `python_dict` is set to True, this function
|
| 710 |
+
returns a Python dictionary with all variable names in lowercase.
|
| 711 |
+
If `idict` was specified, then variables are written to the
|
| 712 |
+
dictionary specified, and the updated dictionary is returned.
|
| 713 |
+
|
| 714 |
+
Examples
|
| 715 |
+
--------
|
| 716 |
+
>>> from os.path import dirname, join as pjoin
|
| 717 |
+
>>> import scipy.io as sio
|
| 718 |
+
>>> from scipy.io import readsav
|
| 719 |
+
|
| 720 |
+
Get the filename for an example .sav file from the tests/data directory.
|
| 721 |
+
|
| 722 |
+
>>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
|
| 723 |
+
>>> sav_fname = pjoin(data_dir, 'array_float32_1d.sav')
|
| 724 |
+
|
| 725 |
+
Load the .sav file contents.
|
| 726 |
+
|
| 727 |
+
>>> sav_data = readsav(sav_fname)
|
| 728 |
+
|
| 729 |
+
Get keys of the .sav file contents.
|
| 730 |
+
|
| 731 |
+
>>> print(sav_data.keys())
|
| 732 |
+
dict_keys(['array1d'])
|
| 733 |
+
|
| 734 |
+
Access a content with a key.
|
| 735 |
+
|
| 736 |
+
>>> print(sav_data['array1d'])
|
| 737 |
+
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
|
| 738 |
+
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
|
| 739 |
+
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
|
| 740 |
+
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
|
| 741 |
+
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
|
| 742 |
+
0. 0. 0.]
|
| 743 |
+
|
| 744 |
+
"""
|
| 745 |
+
|
| 746 |
+
# Initialize record and variable holders
|
| 747 |
+
records = []
|
| 748 |
+
if python_dict or idict:
|
| 749 |
+
variables = {}
|
| 750 |
+
else:
|
| 751 |
+
variables = AttrDict()
|
| 752 |
+
|
| 753 |
+
# Open the IDL file
|
| 754 |
+
f = open(file_name, 'rb')
|
| 755 |
+
|
| 756 |
+
# Read the signature, which should be 'SR'
|
| 757 |
+
signature = _read_bytes(f, 2)
|
| 758 |
+
if signature != b'SR':
|
| 759 |
+
raise Exception(f"Invalid SIGNATURE: {signature}")
|
| 760 |
+
|
| 761 |
+
# Next, the record format, which is '\x00\x04' for normal .sav
|
| 762 |
+
# files, and '\x00\x06' for compressed .sav files.
|
| 763 |
+
recfmt = _read_bytes(f, 2)
|
| 764 |
+
|
| 765 |
+
if recfmt == b'\x00\x04':
|
| 766 |
+
pass
|
| 767 |
+
|
| 768 |
+
elif recfmt == b'\x00\x06':
|
| 769 |
+
|
| 770 |
+
if verbose:
|
| 771 |
+
print("IDL Save file is compressed")
|
| 772 |
+
|
| 773 |
+
if uncompressed_file_name:
|
| 774 |
+
fout = open(uncompressed_file_name, 'w+b')
|
| 775 |
+
else:
|
| 776 |
+
fout = tempfile.NamedTemporaryFile(suffix='.sav')
|
| 777 |
+
|
| 778 |
+
if verbose:
|
| 779 |
+
print(f" -> expanding to {fout.name}")
|
| 780 |
+
|
| 781 |
+
# Write header
|
| 782 |
+
fout.write(b'SR\x00\x04')
|
| 783 |
+
|
| 784 |
+
# Cycle through records
|
| 785 |
+
while True:
|
| 786 |
+
|
| 787 |
+
# Read record type
|
| 788 |
+
rectype = _read_long(f)
|
| 789 |
+
fout.write(struct.pack('>l', int(rectype)))
|
| 790 |
+
|
| 791 |
+
# Read position of next record and return as int
|
| 792 |
+
nextrec = _read_uint32(f)
|
| 793 |
+
nextrec += _read_uint32(f).astype(np.int64) * 2**32
|
| 794 |
+
|
| 795 |
+
# Read the unknown 4 bytes
|
| 796 |
+
unknown = f.read(4)
|
| 797 |
+
|
| 798 |
+
# Check if the end of the file has been reached
|
| 799 |
+
if RECTYPE_DICT[rectype] == 'END_MARKER':
|
| 800 |
+
modval = np.int64(2**32)
|
| 801 |
+
fout.write(struct.pack('>I', int(nextrec) % modval))
|
| 802 |
+
fout.write(
|
| 803 |
+
struct.pack('>I', int((nextrec - (nextrec % modval)) / modval))
|
| 804 |
+
)
|
| 805 |
+
fout.write(unknown)
|
| 806 |
+
break
|
| 807 |
+
|
| 808 |
+
# Find current position
|
| 809 |
+
pos = f.tell()
|
| 810 |
+
|
| 811 |
+
# Decompress record
|
| 812 |
+
rec_string = zlib.decompress(f.read(nextrec-pos))
|
| 813 |
+
|
| 814 |
+
# Find new position of next record
|
| 815 |
+
nextrec = fout.tell() + len(rec_string) + 12
|
| 816 |
+
|
| 817 |
+
# Write out record
|
| 818 |
+
fout.write(struct.pack('>I', int(nextrec % 2**32)))
|
| 819 |
+
fout.write(struct.pack('>I', int((nextrec - (nextrec % 2**32)) / 2**32)))
|
| 820 |
+
fout.write(unknown)
|
| 821 |
+
fout.write(rec_string)
|
| 822 |
+
|
| 823 |
+
# Close the original compressed file
|
| 824 |
+
f.close()
|
| 825 |
+
|
| 826 |
+
# Set f to be the decompressed file, and skip the first four bytes
|
| 827 |
+
f = fout
|
| 828 |
+
f.seek(4)
|
| 829 |
+
|
| 830 |
+
else:
|
| 831 |
+
raise Exception(f"Invalid RECFMT: {recfmt}")
|
| 832 |
+
|
| 833 |
+
# Loop through records, and add them to the list
|
| 834 |
+
while True:
|
| 835 |
+
r = _read_record(f)
|
| 836 |
+
records.append(r)
|
| 837 |
+
if 'end' in r:
|
| 838 |
+
if r['end']:
|
| 839 |
+
break
|
| 840 |
+
|
| 841 |
+
# Close the file
|
| 842 |
+
f.close()
|
| 843 |
+
|
| 844 |
+
# Find heap data variables
|
| 845 |
+
heap = {}
|
| 846 |
+
for r in records:
|
| 847 |
+
if r['rectype'] == "HEAP_DATA":
|
| 848 |
+
heap[r['heap_index']] = r['data']
|
| 849 |
+
|
| 850 |
+
# Find all variables
|
| 851 |
+
for r in records:
|
| 852 |
+
if r['rectype'] == "VARIABLE":
|
| 853 |
+
replace, new = _replace_heap(r['data'], heap)
|
| 854 |
+
if replace:
|
| 855 |
+
r['data'] = new
|
| 856 |
+
variables[r['varname'].lower()] = r['data']
|
| 857 |
+
|
| 858 |
+
if verbose:
|
| 859 |
+
|
| 860 |
+
# Print out timestamp info about the file
|
| 861 |
+
for record in records:
|
| 862 |
+
if record['rectype'] == "TIMESTAMP":
|
| 863 |
+
print("-"*50)
|
| 864 |
+
print(f"Date: {record['date']}")
|
| 865 |
+
print(f"User: {record['user']}")
|
| 866 |
+
print(f"Host: {record['host']}")
|
| 867 |
+
break
|
| 868 |
+
|
| 869 |
+
# Print out version info about the file
|
| 870 |
+
for record in records:
|
| 871 |
+
if record['rectype'] == "VERSION":
|
| 872 |
+
print("-"*50)
|
| 873 |
+
print(f"Format: {record['format']}")
|
| 874 |
+
print(f"Architecture: {record['arch']}")
|
| 875 |
+
print(f"Operating System: {record['os']}")
|
| 876 |
+
print(f"IDL Version: {record['release']}")
|
| 877 |
+
break
|
| 878 |
+
|
| 879 |
+
# Print out identification info about the file
|
| 880 |
+
for record in records:
|
| 881 |
+
if record['rectype'] == "IDENTIFICATON":
|
| 882 |
+
print("-"*50)
|
| 883 |
+
print(f"Author: {record['author']}")
|
| 884 |
+
print(f"Title: {record['title']}")
|
| 885 |
+
print(f"ID Code: {record['idcode']}")
|
| 886 |
+
break
|
| 887 |
+
|
| 888 |
+
# Print out descriptions saved with the file
|
| 889 |
+
for record in records:
|
| 890 |
+
if record['rectype'] == "DESCRIPTION":
|
| 891 |
+
print("-"*50)
|
| 892 |
+
print(f"Description: {record['description']}")
|
| 893 |
+
break
|
| 894 |
+
|
| 895 |
+
print("-"*50)
|
| 896 |
+
print(f"Successfully read {len(records)} records of which:")
|
| 897 |
+
|
| 898 |
+
# Create convenience list of record types
|
| 899 |
+
rectypes = [r['rectype'] for r in records]
|
| 900 |
+
|
| 901 |
+
for rt in set(rectypes):
|
| 902 |
+
if rt != 'END_MARKER':
|
| 903 |
+
print(f" - {rectypes.count(rt)} are of type {rt}")
|
| 904 |
+
print("-"*50)
|
| 905 |
+
|
| 906 |
+
if 'VARIABLE' in rectypes:
|
| 907 |
+
print("Available variables:")
|
| 908 |
+
for var in variables:
|
| 909 |
+
print(f" - {var} [{type(variables[var])}]")
|
| 910 |
+
print("-"*50)
|
| 911 |
+
|
| 912 |
+
if idict:
|
| 913 |
+
for var in variables:
|
| 914 |
+
idict[var] = variables[var]
|
| 915 |
+
return idict
|
| 916 |
+
else:
|
| 917 |
+
return variables
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/_mmio.py
ADDED
|
@@ -0,0 +1,968 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ats.html
|
| 4 |
+
for information about the Matrix Market format.
|
| 5 |
+
"""
|
| 6 |
+
#
|
| 7 |
+
# Author: Pearu Peterson <pearu@cens.ioc.ee>
|
| 8 |
+
# Created: October, 2004
|
| 9 |
+
#
|
| 10 |
+
# References:
|
| 11 |
+
# http://math.nist.gov/MatrixMarket/
|
| 12 |
+
#
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from numpy import (asarray, real, imag, conj, zeros, ndarray, concatenate,
|
| 17 |
+
ones, can_cast)
|
| 18 |
+
|
| 19 |
+
from scipy.sparse import coo_array, issparse, coo_matrix
|
| 20 |
+
|
| 21 |
+
__all__ = ['mminfo', 'mmread', 'mmwrite', 'MMFile']
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# -----------------------------------------------------------------------------
|
| 25 |
+
def asstr(s):
|
| 26 |
+
if isinstance(s, bytes):
|
| 27 |
+
return s.decode('latin1')
|
| 28 |
+
return str(s)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def mminfo(source):
|
| 32 |
+
"""
|
| 33 |
+
Return size and storage parameters from Matrix Market file-like 'source'.
|
| 34 |
+
|
| 35 |
+
Parameters
|
| 36 |
+
----------
|
| 37 |
+
source : str or file-like
|
| 38 |
+
Matrix Market filename (extension .mtx) or open file-like object
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
-------
|
| 42 |
+
rows : int
|
| 43 |
+
Number of matrix rows.
|
| 44 |
+
cols : int
|
| 45 |
+
Number of matrix columns.
|
| 46 |
+
entries : int
|
| 47 |
+
Number of non-zero entries of a sparse matrix
|
| 48 |
+
or rows*cols for a dense matrix.
|
| 49 |
+
format : str
|
| 50 |
+
Either 'coordinate' or 'array'.
|
| 51 |
+
field : str
|
| 52 |
+
Either 'real', 'complex', 'pattern', or 'integer'.
|
| 53 |
+
symmetry : str
|
| 54 |
+
Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
|
| 55 |
+
|
| 56 |
+
Examples
|
| 57 |
+
--------
|
| 58 |
+
>>> from io import StringIO
|
| 59 |
+
>>> from scipy.io import mminfo
|
| 60 |
+
|
| 61 |
+
>>> text = '''%%MatrixMarket matrix coordinate real general
|
| 62 |
+
... 5 5 7
|
| 63 |
+
... 2 3 1.0
|
| 64 |
+
... 3 4 2.0
|
| 65 |
+
... 3 5 3.0
|
| 66 |
+
... 4 1 4.0
|
| 67 |
+
... 4 2 5.0
|
| 68 |
+
... 4 3 6.0
|
| 69 |
+
... 4 4 7.0
|
| 70 |
+
... '''
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
``mminfo(source)`` returns the number of rows, number of columns,
|
| 74 |
+
format, field type and symmetry attribute of the source file.
|
| 75 |
+
|
| 76 |
+
>>> mminfo(StringIO(text))
|
| 77 |
+
(5, 5, 7, 'coordinate', 'real', 'general')
|
| 78 |
+
"""
|
| 79 |
+
return MMFile.info(source)
|
| 80 |
+
|
| 81 |
+
# -----------------------------------------------------------------------------
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def mmread(source, *, spmatrix=True):
|
| 85 |
+
"""
|
| 86 |
+
Reads the contents of a Matrix Market file-like 'source' into a matrix.
|
| 87 |
+
|
| 88 |
+
Parameters
|
| 89 |
+
----------
|
| 90 |
+
source : str or file-like
|
| 91 |
+
Matrix Market filename (extensions .mtx, .mtz.gz)
|
| 92 |
+
or open file-like object.
|
| 93 |
+
spmatrix : bool, optional (default: True)
|
| 94 |
+
If ``True``, return sparse matrix. Otherwise return sparse array.
|
| 95 |
+
|
| 96 |
+
Returns
|
| 97 |
+
-------
|
| 98 |
+
a : ndarray or coo_array or coo_matrix
|
| 99 |
+
Dense or sparse array depending on the matrix format in the
|
| 100 |
+
Matrix Market file.
|
| 101 |
+
|
| 102 |
+
Examples
|
| 103 |
+
--------
|
| 104 |
+
>>> from io import StringIO
|
| 105 |
+
>>> from scipy.io import mmread
|
| 106 |
+
|
| 107 |
+
>>> text = '''%%MatrixMarket matrix coordinate real general
|
| 108 |
+
... 5 5 7
|
| 109 |
+
... 2 3 1.0
|
| 110 |
+
... 3 4 2.0
|
| 111 |
+
... 3 5 3.0
|
| 112 |
+
... 4 1 4.0
|
| 113 |
+
... 4 2 5.0
|
| 114 |
+
... 4 3 6.0
|
| 115 |
+
... 4 4 7.0
|
| 116 |
+
... '''
|
| 117 |
+
|
| 118 |
+
``mmread(source)`` returns the data as sparse matrix in COO format.
|
| 119 |
+
|
| 120 |
+
>>> m = mmread(StringIO(text), spmatrix=False)
|
| 121 |
+
>>> m
|
| 122 |
+
<COOrdinate sparse array of dtype 'float64'
|
| 123 |
+
with 7 stored elements and shape (5, 5)>
|
| 124 |
+
>>> m.toarray()
|
| 125 |
+
array([[0., 0., 0., 0., 0.],
|
| 126 |
+
[0., 0., 1., 0., 0.],
|
| 127 |
+
[0., 0., 0., 2., 3.],
|
| 128 |
+
[4., 5., 6., 7., 0.],
|
| 129 |
+
[0., 0., 0., 0., 0.]])
|
| 130 |
+
"""
|
| 131 |
+
return MMFile().read(source, spmatrix=spmatrix)
|
| 132 |
+
|
| 133 |
+
# -----------------------------------------------------------------------------
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def mmwrite(target, a, comment='', field=None, precision=None, symmetry=None):
|
| 137 |
+
r"""
|
| 138 |
+
Writes the sparse or dense array `a` to Matrix Market file-like `target`.
|
| 139 |
+
|
| 140 |
+
Parameters
|
| 141 |
+
----------
|
| 142 |
+
target : str or file-like
|
| 143 |
+
Matrix Market filename (extension .mtx) or open file-like object.
|
| 144 |
+
a : array like
|
| 145 |
+
Sparse or dense 2-D array.
|
| 146 |
+
comment : str, optional
|
| 147 |
+
Comments to be prepended to the Matrix Market file.
|
| 148 |
+
field : None or str, optional
|
| 149 |
+
Either 'real', 'complex', 'pattern', or 'integer'.
|
| 150 |
+
precision : None or int, optional
|
| 151 |
+
Number of digits to display for real or complex values.
|
| 152 |
+
symmetry : None or str, optional
|
| 153 |
+
Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
|
| 154 |
+
If symmetry is None the symmetry type of 'a' is determined by its
|
| 155 |
+
values.
|
| 156 |
+
|
| 157 |
+
Returns
|
| 158 |
+
-------
|
| 159 |
+
None
|
| 160 |
+
|
| 161 |
+
Examples
|
| 162 |
+
--------
|
| 163 |
+
>>> from io import BytesIO
|
| 164 |
+
>>> import numpy as np
|
| 165 |
+
>>> from scipy.sparse import coo_array
|
| 166 |
+
>>> from scipy.io import mmwrite
|
| 167 |
+
|
| 168 |
+
Write a small NumPy array to a matrix market file. The file will be
|
| 169 |
+
written in the ``'array'`` format.
|
| 170 |
+
|
| 171 |
+
>>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]])
|
| 172 |
+
>>> target = BytesIO()
|
| 173 |
+
>>> mmwrite(target, a)
|
| 174 |
+
>>> print(target.getvalue().decode('latin1'))
|
| 175 |
+
%%MatrixMarket matrix array real general
|
| 176 |
+
%
|
| 177 |
+
2 4
|
| 178 |
+
1
|
| 179 |
+
0
|
| 180 |
+
0
|
| 181 |
+
2.5
|
| 182 |
+
0
|
| 183 |
+
0
|
| 184 |
+
0
|
| 185 |
+
6.25
|
| 186 |
+
|
| 187 |
+
Add a comment to the output file, and set the precision to 3.
|
| 188 |
+
|
| 189 |
+
>>> target = BytesIO()
|
| 190 |
+
>>> mmwrite(target, a, comment='\n Some test data.\n', precision=3)
|
| 191 |
+
>>> print(target.getvalue().decode('latin1'))
|
| 192 |
+
%%MatrixMarket matrix array real general
|
| 193 |
+
%
|
| 194 |
+
% Some test data.
|
| 195 |
+
%
|
| 196 |
+
2 4
|
| 197 |
+
1.00e+00
|
| 198 |
+
0.00e+00
|
| 199 |
+
0.00e+00
|
| 200 |
+
2.50e+00
|
| 201 |
+
0.00e+00
|
| 202 |
+
0.00e+00
|
| 203 |
+
0.00e+00
|
| 204 |
+
6.25e+00
|
| 205 |
+
|
| 206 |
+
Convert to a sparse matrix before calling ``mmwrite``. This will
|
| 207 |
+
result in the output format being ``'coordinate'`` rather than
|
| 208 |
+
``'array'``.
|
| 209 |
+
|
| 210 |
+
>>> target = BytesIO()
|
| 211 |
+
>>> mmwrite(target, coo_array(a), precision=3)
|
| 212 |
+
>>> print(target.getvalue().decode('latin1'))
|
| 213 |
+
%%MatrixMarket matrix coordinate real general
|
| 214 |
+
%
|
| 215 |
+
2 4 3
|
| 216 |
+
1 1 1.00e+00
|
| 217 |
+
2 2 2.50e+00
|
| 218 |
+
2 4 6.25e+00
|
| 219 |
+
|
| 220 |
+
Write a complex Hermitian array to a matrix market file. Note that
|
| 221 |
+
only six values are actually written to the file; the other values
|
| 222 |
+
are implied by the symmetry.
|
| 223 |
+
|
| 224 |
+
>>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]])
|
| 225 |
+
>>> z
|
| 226 |
+
array([[ 3. +0.j, 1. +2.j, 4. -3.j],
|
| 227 |
+
[ 1. -2.j, 1. +0.j, -0. -5.j],
|
| 228 |
+
[ 4. +3.j, 0. +5.j, 2.5+0.j]])
|
| 229 |
+
|
| 230 |
+
>>> target = BytesIO()
|
| 231 |
+
>>> mmwrite(target, z, precision=2)
|
| 232 |
+
>>> print(target.getvalue().decode('latin1'))
|
| 233 |
+
%%MatrixMarket matrix array complex hermitian
|
| 234 |
+
%
|
| 235 |
+
3 3
|
| 236 |
+
3.0e+00 0.0e+00
|
| 237 |
+
1.0e+00 -2.0e+00
|
| 238 |
+
4.0e+00 3.0e+00
|
| 239 |
+
1.0e+00 0.0e+00
|
| 240 |
+
0.0e+00 5.0e+00
|
| 241 |
+
2.5e+00 0.0e+00
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
MMFile().write(target, a, comment, field, precision, symmetry)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
###############################################################################
|
| 248 |
+
class MMFile:
|
| 249 |
+
__slots__ = ('_rows',
|
| 250 |
+
'_cols',
|
| 251 |
+
'_entries',
|
| 252 |
+
'_format',
|
| 253 |
+
'_field',
|
| 254 |
+
'_symmetry')
|
| 255 |
+
|
| 256 |
+
@property
|
| 257 |
+
def rows(self):
|
| 258 |
+
return self._rows
|
| 259 |
+
|
| 260 |
+
@property
|
| 261 |
+
def cols(self):
|
| 262 |
+
return self._cols
|
| 263 |
+
|
| 264 |
+
@property
|
| 265 |
+
def entries(self):
|
| 266 |
+
return self._entries
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def format(self):
|
| 270 |
+
return self._format
|
| 271 |
+
|
| 272 |
+
@property
|
| 273 |
+
def field(self):
|
| 274 |
+
return self._field
|
| 275 |
+
|
| 276 |
+
@property
|
| 277 |
+
def symmetry(self):
|
| 278 |
+
return self._symmetry
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def has_symmetry(self):
|
| 282 |
+
return self._symmetry in (self.SYMMETRY_SYMMETRIC,
|
| 283 |
+
self.SYMMETRY_SKEW_SYMMETRIC,
|
| 284 |
+
self.SYMMETRY_HERMITIAN)
|
| 285 |
+
|
| 286 |
+
# format values
|
| 287 |
+
FORMAT_COORDINATE = 'coordinate'
|
| 288 |
+
FORMAT_ARRAY = 'array'
|
| 289 |
+
FORMAT_VALUES = (FORMAT_COORDINATE, FORMAT_ARRAY)
|
| 290 |
+
|
| 291 |
+
@classmethod
|
| 292 |
+
def _validate_format(self, format):
|
| 293 |
+
if format not in self.FORMAT_VALUES:
|
| 294 |
+
msg = f'unknown format type {format}, must be one of {self.FORMAT_VALUES}'
|
| 295 |
+
raise ValueError(msg)
|
| 296 |
+
|
| 297 |
+
# field values
|
| 298 |
+
FIELD_INTEGER = 'integer'
|
| 299 |
+
FIELD_UNSIGNED = 'unsigned-integer'
|
| 300 |
+
FIELD_REAL = 'real'
|
| 301 |
+
FIELD_COMPLEX = 'complex'
|
| 302 |
+
FIELD_PATTERN = 'pattern'
|
| 303 |
+
FIELD_VALUES = (FIELD_INTEGER, FIELD_UNSIGNED, FIELD_REAL, FIELD_COMPLEX,
|
| 304 |
+
FIELD_PATTERN)
|
| 305 |
+
|
| 306 |
+
@classmethod
|
| 307 |
+
def _validate_field(self, field):
|
| 308 |
+
if field not in self.FIELD_VALUES:
|
| 309 |
+
msg = f'unknown field type {field}, must be one of {self.FIELD_VALUES}'
|
| 310 |
+
raise ValueError(msg)
|
| 311 |
+
|
| 312 |
+
# symmetry values
|
| 313 |
+
SYMMETRY_GENERAL = 'general'
|
| 314 |
+
SYMMETRY_SYMMETRIC = 'symmetric'
|
| 315 |
+
SYMMETRY_SKEW_SYMMETRIC = 'skew-symmetric'
|
| 316 |
+
SYMMETRY_HERMITIAN = 'hermitian'
|
| 317 |
+
SYMMETRY_VALUES = (SYMMETRY_GENERAL, SYMMETRY_SYMMETRIC,
|
| 318 |
+
SYMMETRY_SKEW_SYMMETRIC, SYMMETRY_HERMITIAN)
|
| 319 |
+
|
| 320 |
+
@classmethod
|
| 321 |
+
def _validate_symmetry(self, symmetry):
|
| 322 |
+
if symmetry not in self.SYMMETRY_VALUES:
|
| 323 |
+
raise ValueError(f'unknown symmetry type {symmetry}, '
|
| 324 |
+
f'must be one of {self.SYMMETRY_VALUES}')
|
| 325 |
+
|
| 326 |
+
DTYPES_BY_FIELD = {FIELD_INTEGER: 'intp',
|
| 327 |
+
FIELD_UNSIGNED: 'uint64',
|
| 328 |
+
FIELD_REAL: 'd',
|
| 329 |
+
FIELD_COMPLEX: 'D',
|
| 330 |
+
FIELD_PATTERN: 'd'}
|
| 331 |
+
|
| 332 |
+
# -------------------------------------------------------------------------
|
| 333 |
+
@staticmethod
|
| 334 |
+
def reader():
|
| 335 |
+
pass
|
| 336 |
+
|
| 337 |
+
# -------------------------------------------------------------------------
|
| 338 |
+
@staticmethod
|
| 339 |
+
def writer():
|
| 340 |
+
pass
|
| 341 |
+
|
| 342 |
+
# -------------------------------------------------------------------------
|
| 343 |
+
@classmethod
|
| 344 |
+
def info(self, source):
|
| 345 |
+
"""
|
| 346 |
+
Return size, storage parameters from Matrix Market file-like 'source'.
|
| 347 |
+
|
| 348 |
+
Parameters
|
| 349 |
+
----------
|
| 350 |
+
source : str or file-like
|
| 351 |
+
Matrix Market filename (extension .mtx) or open file-like object
|
| 352 |
+
|
| 353 |
+
Returns
|
| 354 |
+
-------
|
| 355 |
+
rows : int
|
| 356 |
+
Number of matrix rows.
|
| 357 |
+
cols : int
|
| 358 |
+
Number of matrix columns.
|
| 359 |
+
entries : int
|
| 360 |
+
Number of non-zero entries of a sparse matrix
|
| 361 |
+
or rows*cols for a dense matrix.
|
| 362 |
+
format : str
|
| 363 |
+
Either 'coordinate' or 'array'.
|
| 364 |
+
field : str
|
| 365 |
+
Either 'real', 'complex', 'pattern', or 'integer'.
|
| 366 |
+
symmetry : str
|
| 367 |
+
Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
|
| 368 |
+
"""
|
| 369 |
+
|
| 370 |
+
stream, close_it = self._open(source)
|
| 371 |
+
|
| 372 |
+
try:
|
| 373 |
+
|
| 374 |
+
# read and validate header line
|
| 375 |
+
line = stream.readline()
|
| 376 |
+
mmid, matrix, format, field, symmetry = \
|
| 377 |
+
(asstr(part.strip()) for part in line.split())
|
| 378 |
+
if not mmid.startswith('%%MatrixMarket'):
|
| 379 |
+
raise ValueError('source is not in Matrix Market format')
|
| 380 |
+
if not matrix.lower() == 'matrix':
|
| 381 |
+
raise ValueError("Problem reading file header: " + line)
|
| 382 |
+
|
| 383 |
+
# http://math.nist.gov/MatrixMarket/formats.html
|
| 384 |
+
if format.lower() == 'array':
|
| 385 |
+
format = self.FORMAT_ARRAY
|
| 386 |
+
elif format.lower() == 'coordinate':
|
| 387 |
+
format = self.FORMAT_COORDINATE
|
| 388 |
+
|
| 389 |
+
# skip comments
|
| 390 |
+
# line.startswith('%')
|
| 391 |
+
while line:
|
| 392 |
+
if line.lstrip() and line.lstrip()[0] in ['%', 37]:
|
| 393 |
+
line = stream.readline()
|
| 394 |
+
else:
|
| 395 |
+
break
|
| 396 |
+
|
| 397 |
+
# skip empty lines
|
| 398 |
+
while not line.strip():
|
| 399 |
+
line = stream.readline()
|
| 400 |
+
|
| 401 |
+
split_line = line.split()
|
| 402 |
+
if format == self.FORMAT_ARRAY:
|
| 403 |
+
if not len(split_line) == 2:
|
| 404 |
+
raise ValueError("Header line not of length 2: " +
|
| 405 |
+
line.decode('ascii'))
|
| 406 |
+
rows, cols = map(int, split_line)
|
| 407 |
+
entries = rows * cols
|
| 408 |
+
else:
|
| 409 |
+
if not len(split_line) == 3:
|
| 410 |
+
raise ValueError("Header line not of length 3: " +
|
| 411 |
+
line.decode('ascii'))
|
| 412 |
+
rows, cols, entries = map(int, split_line)
|
| 413 |
+
|
| 414 |
+
return (rows, cols, entries, format, field.lower(),
|
| 415 |
+
symmetry.lower())
|
| 416 |
+
|
| 417 |
+
finally:
|
| 418 |
+
if close_it:
|
| 419 |
+
stream.close()
|
| 420 |
+
|
| 421 |
+
# -------------------------------------------------------------------------
|
| 422 |
+
@staticmethod
|
| 423 |
+
def _open(filespec, mode='rb'):
|
| 424 |
+
""" Return an open file stream for reading based on source.
|
| 425 |
+
|
| 426 |
+
If source is a file name, open it (after trying to find it with mtx and
|
| 427 |
+
gzipped mtx extensions). Otherwise, just return source.
|
| 428 |
+
|
| 429 |
+
Parameters
|
| 430 |
+
----------
|
| 431 |
+
filespec : str or file-like
|
| 432 |
+
String giving file name or file-like object
|
| 433 |
+
mode : str, optional
|
| 434 |
+
Mode with which to open file, if `filespec` is a file name.
|
| 435 |
+
|
| 436 |
+
Returns
|
| 437 |
+
-------
|
| 438 |
+
fobj : file-like
|
| 439 |
+
Open file-like object.
|
| 440 |
+
close_it : bool
|
| 441 |
+
True if the calling function should close this file when done,
|
| 442 |
+
false otherwise.
|
| 443 |
+
"""
|
| 444 |
+
# If 'filespec' is path-like (str, pathlib.Path, os.DirEntry, other class
|
| 445 |
+
# implementing a '__fspath__' method), try to convert it to str. If this
|
| 446 |
+
# fails by throwing a 'TypeError', assume it's an open file handle and
|
| 447 |
+
# return it as-is.
|
| 448 |
+
try:
|
| 449 |
+
filespec = os.fspath(filespec)
|
| 450 |
+
except TypeError:
|
| 451 |
+
return filespec, False
|
| 452 |
+
|
| 453 |
+
# 'filespec' is definitely a str now
|
| 454 |
+
|
| 455 |
+
# open for reading
|
| 456 |
+
if mode[0] == 'r':
|
| 457 |
+
|
| 458 |
+
# determine filename plus extension
|
| 459 |
+
if not os.path.isfile(filespec):
|
| 460 |
+
if os.path.isfile(filespec+'.mtx'):
|
| 461 |
+
filespec = filespec + '.mtx'
|
| 462 |
+
elif os.path.isfile(filespec+'.mtx.gz'):
|
| 463 |
+
filespec = filespec + '.mtx.gz'
|
| 464 |
+
elif os.path.isfile(filespec+'.mtx.bz2'):
|
| 465 |
+
filespec = filespec + '.mtx.bz2'
|
| 466 |
+
# open filename
|
| 467 |
+
if filespec.endswith('.gz'):
|
| 468 |
+
import gzip
|
| 469 |
+
stream = gzip.open(filespec, mode)
|
| 470 |
+
elif filespec.endswith('.bz2'):
|
| 471 |
+
import bz2
|
| 472 |
+
stream = bz2.BZ2File(filespec, 'rb')
|
| 473 |
+
else:
|
| 474 |
+
stream = open(filespec, mode)
|
| 475 |
+
|
| 476 |
+
# open for writing
|
| 477 |
+
else:
|
| 478 |
+
if filespec[-4:] != '.mtx':
|
| 479 |
+
filespec = filespec + '.mtx'
|
| 480 |
+
stream = open(filespec, mode)
|
| 481 |
+
|
| 482 |
+
return stream, True
|
| 483 |
+
|
| 484 |
+
# -------------------------------------------------------------------------
|
| 485 |
+
@staticmethod
|
| 486 |
+
def _get_symmetry(a):
|
| 487 |
+
m, n = a.shape
|
| 488 |
+
if m != n:
|
| 489 |
+
return MMFile.SYMMETRY_GENERAL
|
| 490 |
+
issymm = True
|
| 491 |
+
isskew = True
|
| 492 |
+
isherm = a.dtype.char in 'FD'
|
| 493 |
+
|
| 494 |
+
# sparse input
|
| 495 |
+
if issparse(a):
|
| 496 |
+
# check if number of nonzero entries of lower and upper triangle
|
| 497 |
+
# matrix are equal
|
| 498 |
+
a = a.tocoo()
|
| 499 |
+
(row, col) = a.nonzero()
|
| 500 |
+
if (row < col).sum() != (row > col).sum():
|
| 501 |
+
return MMFile.SYMMETRY_GENERAL
|
| 502 |
+
|
| 503 |
+
# define iterator over symmetric pair entries
|
| 504 |
+
a = a.todok()
|
| 505 |
+
|
| 506 |
+
def symm_iterator():
|
| 507 |
+
for ((i, j), aij) in a.items():
|
| 508 |
+
if i > j:
|
| 509 |
+
aji = a[j, i]
|
| 510 |
+
yield (aij, aji, False)
|
| 511 |
+
elif i == j:
|
| 512 |
+
yield (aij, aij, True)
|
| 513 |
+
|
| 514 |
+
# non-sparse input
|
| 515 |
+
else:
|
| 516 |
+
# define iterator over symmetric pair entries
|
| 517 |
+
def symm_iterator():
|
| 518 |
+
for j in range(n):
|
| 519 |
+
for i in range(j, n):
|
| 520 |
+
aij, aji = a[i][j], a[j][i]
|
| 521 |
+
yield (aij, aji, i == j)
|
| 522 |
+
|
| 523 |
+
# check for symmetry
|
| 524 |
+
# yields aij, aji, is_diagonal
|
| 525 |
+
for (aij, aji, is_diagonal) in symm_iterator():
|
| 526 |
+
if isskew and is_diagonal and aij != 0:
|
| 527 |
+
isskew = False
|
| 528 |
+
else:
|
| 529 |
+
if issymm and aij != aji:
|
| 530 |
+
issymm = False
|
| 531 |
+
with np.errstate(over="ignore"):
|
| 532 |
+
# This can give a warning for uint dtypes, so silence that
|
| 533 |
+
if isskew and aij != -aji:
|
| 534 |
+
isskew = False
|
| 535 |
+
if isherm and aij != conj(aji):
|
| 536 |
+
isherm = False
|
| 537 |
+
if not (issymm or isskew or isherm):
|
| 538 |
+
break
|
| 539 |
+
|
| 540 |
+
# return symmetry value
|
| 541 |
+
if issymm:
|
| 542 |
+
return MMFile.SYMMETRY_SYMMETRIC
|
| 543 |
+
if isskew:
|
| 544 |
+
return MMFile.SYMMETRY_SKEW_SYMMETRIC
|
| 545 |
+
if isherm:
|
| 546 |
+
return MMFile.SYMMETRY_HERMITIAN
|
| 547 |
+
return MMFile.SYMMETRY_GENERAL
|
| 548 |
+
|
| 549 |
+
# -------------------------------------------------------------------------
|
| 550 |
+
@staticmethod
|
| 551 |
+
def _field_template(field, precision):
|
| 552 |
+
return {MMFile.FIELD_REAL: '%%.%ie\n' % precision,
|
| 553 |
+
MMFile.FIELD_INTEGER: '%i\n',
|
| 554 |
+
MMFile.FIELD_UNSIGNED: '%u\n',
|
| 555 |
+
MMFile.FIELD_COMPLEX: '%%.%ie %%.%ie\n' %
|
| 556 |
+
(precision, precision)
|
| 557 |
+
}.get(field, None)
|
| 558 |
+
|
| 559 |
+
# -------------------------------------------------------------------------
|
| 560 |
+
def __init__(self, **kwargs):
|
| 561 |
+
self._init_attrs(**kwargs)
|
| 562 |
+
|
| 563 |
+
# -------------------------------------------------------------------------
|
| 564 |
+
def read(self, source, *, spmatrix=True):
|
| 565 |
+
"""
|
| 566 |
+
Reads the contents of a Matrix Market file-like 'source' into a matrix.
|
| 567 |
+
|
| 568 |
+
Parameters
|
| 569 |
+
----------
|
| 570 |
+
source : str or file-like
|
| 571 |
+
Matrix Market filename (extensions .mtx, .mtz.gz)
|
| 572 |
+
or open file object.
|
| 573 |
+
spmatrix : bool, optional (default: True)
|
| 574 |
+
If ``True``, return sparse matrix. Otherwise return sparse array.
|
| 575 |
+
|
| 576 |
+
Returns
|
| 577 |
+
-------
|
| 578 |
+
a : ndarray or coo_array or coo_matrix
|
| 579 |
+
Dense or sparse array depending on the matrix format in the
|
| 580 |
+
Matrix Market file.
|
| 581 |
+
"""
|
| 582 |
+
stream, close_it = self._open(source)
|
| 583 |
+
|
| 584 |
+
try:
|
| 585 |
+
self._parse_header(stream)
|
| 586 |
+
data = self._parse_body(stream)
|
| 587 |
+
|
| 588 |
+
finally:
|
| 589 |
+
if close_it:
|
| 590 |
+
stream.close()
|
| 591 |
+
if spmatrix and isinstance(data, coo_array):
|
| 592 |
+
data = coo_matrix(data)
|
| 593 |
+
return data
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
# -------------------------------------------------------------------------
|
| 597 |
+
def write(self, target, a, comment='', field=None, precision=None,
|
| 598 |
+
symmetry=None):
|
| 599 |
+
"""
|
| 600 |
+
Writes sparse or dense array `a` to Matrix Market file-like `target`.
|
| 601 |
+
|
| 602 |
+
Parameters
|
| 603 |
+
----------
|
| 604 |
+
target : str or file-like
|
| 605 |
+
Matrix Market filename (extension .mtx) or open file-like object.
|
| 606 |
+
a : array like
|
| 607 |
+
Sparse or dense 2-D array.
|
| 608 |
+
comment : str, optional
|
| 609 |
+
Comments to be prepended to the Matrix Market file.
|
| 610 |
+
field : None or str, optional
|
| 611 |
+
Either 'real', 'complex', 'pattern', or 'integer'.
|
| 612 |
+
precision : None or int, optional
|
| 613 |
+
Number of digits to display for real or complex values.
|
| 614 |
+
symmetry : None or str, optional
|
| 615 |
+
Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
|
| 616 |
+
If symmetry is None the symmetry type of 'a' is determined by its
|
| 617 |
+
values.
|
| 618 |
+
"""
|
| 619 |
+
|
| 620 |
+
stream, close_it = self._open(target, 'wb')
|
| 621 |
+
|
| 622 |
+
try:
|
| 623 |
+
self._write(stream, a, comment, field, precision, symmetry)
|
| 624 |
+
|
| 625 |
+
finally:
|
| 626 |
+
if close_it:
|
| 627 |
+
stream.close()
|
| 628 |
+
else:
|
| 629 |
+
stream.flush()
|
| 630 |
+
|
| 631 |
+
# -------------------------------------------------------------------------
|
| 632 |
+
def _init_attrs(self, **kwargs):
|
| 633 |
+
"""
|
| 634 |
+
Initialize each attributes with the corresponding keyword arg value
|
| 635 |
+
or a default of None
|
| 636 |
+
"""
|
| 637 |
+
|
| 638 |
+
attrs = self.__class__.__slots__
|
| 639 |
+
public_attrs = [attr[1:] for attr in attrs]
|
| 640 |
+
invalid_keys = set(kwargs.keys()) - set(public_attrs)
|
| 641 |
+
|
| 642 |
+
if invalid_keys:
|
| 643 |
+
raise ValueError(f"found {tuple(invalid_keys)} invalid keyword "
|
| 644 |
+
f"arguments, please only use {public_attrs}")
|
| 645 |
+
|
| 646 |
+
for attr in attrs:
|
| 647 |
+
setattr(self, attr, kwargs.get(attr[1:], None))
|
| 648 |
+
|
| 649 |
+
# -------------------------------------------------------------------------
|
| 650 |
+
def _parse_header(self, stream):
|
| 651 |
+
rows, cols, entries, format, field, symmetry = \
|
| 652 |
+
self.__class__.info(stream)
|
| 653 |
+
self._init_attrs(rows=rows, cols=cols, entries=entries, format=format,
|
| 654 |
+
field=field, symmetry=symmetry)
|
| 655 |
+
|
| 656 |
+
# -------------------------------------------------------------------------
|
| 657 |
+
def _parse_body(self, stream):
|
| 658 |
+
rows, cols, entries, format, field, symm = (self.rows, self.cols,
|
| 659 |
+
self.entries, self.format,
|
| 660 |
+
self.field, self.symmetry)
|
| 661 |
+
|
| 662 |
+
dtype = self.DTYPES_BY_FIELD.get(field, None)
|
| 663 |
+
|
| 664 |
+
has_symmetry = self.has_symmetry
|
| 665 |
+
is_integer = field == self.FIELD_INTEGER
|
| 666 |
+
is_unsigned_integer = field == self.FIELD_UNSIGNED
|
| 667 |
+
is_complex = field == self.FIELD_COMPLEX
|
| 668 |
+
is_skew = symm == self.SYMMETRY_SKEW_SYMMETRIC
|
| 669 |
+
is_herm = symm == self.SYMMETRY_HERMITIAN
|
| 670 |
+
is_pattern = field == self.FIELD_PATTERN
|
| 671 |
+
|
| 672 |
+
if format == self.FORMAT_ARRAY:
|
| 673 |
+
a = zeros((rows, cols), dtype=dtype)
|
| 674 |
+
line = 1
|
| 675 |
+
i, j = 0, 0
|
| 676 |
+
if is_skew:
|
| 677 |
+
a[i, j] = 0
|
| 678 |
+
if i < rows - 1:
|
| 679 |
+
i += 1
|
| 680 |
+
while line:
|
| 681 |
+
line = stream.readline()
|
| 682 |
+
# line.startswith('%')
|
| 683 |
+
if not line or line[0] in ['%', 37] or not line.strip():
|
| 684 |
+
continue
|
| 685 |
+
if is_integer:
|
| 686 |
+
aij = int(line)
|
| 687 |
+
elif is_unsigned_integer:
|
| 688 |
+
aij = int(line)
|
| 689 |
+
elif is_complex:
|
| 690 |
+
aij = complex(*map(float, line.split()))
|
| 691 |
+
else:
|
| 692 |
+
aij = float(line)
|
| 693 |
+
a[i, j] = aij
|
| 694 |
+
if has_symmetry and i != j:
|
| 695 |
+
if is_skew:
|
| 696 |
+
a[j, i] = -aij
|
| 697 |
+
elif is_herm:
|
| 698 |
+
a[j, i] = conj(aij)
|
| 699 |
+
else:
|
| 700 |
+
a[j, i] = aij
|
| 701 |
+
if i < rows-1:
|
| 702 |
+
i = i + 1
|
| 703 |
+
else:
|
| 704 |
+
j = j + 1
|
| 705 |
+
if not has_symmetry:
|
| 706 |
+
i = 0
|
| 707 |
+
else:
|
| 708 |
+
i = j
|
| 709 |
+
if is_skew:
|
| 710 |
+
a[i, j] = 0
|
| 711 |
+
if i < rows-1:
|
| 712 |
+
i += 1
|
| 713 |
+
|
| 714 |
+
if is_skew:
|
| 715 |
+
if not (i in [0, j] and j == cols - 1):
|
| 716 |
+
raise ValueError("Parse error, did not read all lines.")
|
| 717 |
+
else:
|
| 718 |
+
if not (i in [0, j] and j == cols):
|
| 719 |
+
raise ValueError("Parse error, did not read all lines.")
|
| 720 |
+
|
| 721 |
+
elif format == self.FORMAT_COORDINATE:
|
| 722 |
+
# Read sparse COOrdinate format
|
| 723 |
+
|
| 724 |
+
if entries == 0:
|
| 725 |
+
# empty matrix
|
| 726 |
+
return coo_array((rows, cols), dtype=dtype)
|
| 727 |
+
|
| 728 |
+
I = zeros(entries, dtype='intc')
|
| 729 |
+
J = zeros(entries, dtype='intc')
|
| 730 |
+
if is_pattern:
|
| 731 |
+
V = ones(entries, dtype='int8')
|
| 732 |
+
elif is_integer:
|
| 733 |
+
V = zeros(entries, dtype='intp')
|
| 734 |
+
elif is_unsigned_integer:
|
| 735 |
+
V = zeros(entries, dtype='uint64')
|
| 736 |
+
elif is_complex:
|
| 737 |
+
V = zeros(entries, dtype='complex')
|
| 738 |
+
else:
|
| 739 |
+
V = zeros(entries, dtype='float')
|
| 740 |
+
|
| 741 |
+
entry_number = 0
|
| 742 |
+
for line in stream:
|
| 743 |
+
# line.startswith('%')
|
| 744 |
+
if not line or line[0] in ['%', 37] or not line.strip():
|
| 745 |
+
continue
|
| 746 |
+
|
| 747 |
+
if entry_number+1 > entries:
|
| 748 |
+
raise ValueError("'entries' in header is smaller than "
|
| 749 |
+
"number of entries")
|
| 750 |
+
l = line.split()
|
| 751 |
+
I[entry_number], J[entry_number] = map(int, l[:2])
|
| 752 |
+
|
| 753 |
+
if not is_pattern:
|
| 754 |
+
if is_integer:
|
| 755 |
+
V[entry_number] = int(l[2])
|
| 756 |
+
elif is_unsigned_integer:
|
| 757 |
+
V[entry_number] = int(l[2])
|
| 758 |
+
elif is_complex:
|
| 759 |
+
V[entry_number] = complex(*map(float, l[2:]))
|
| 760 |
+
else:
|
| 761 |
+
V[entry_number] = float(l[2])
|
| 762 |
+
entry_number += 1
|
| 763 |
+
if entry_number < entries:
|
| 764 |
+
raise ValueError("'entries' in header is larger than "
|
| 765 |
+
"number of entries")
|
| 766 |
+
|
| 767 |
+
I -= 1 # adjust indices (base 1 -> base 0)
|
| 768 |
+
J -= 1
|
| 769 |
+
|
| 770 |
+
if has_symmetry:
|
| 771 |
+
mask = (I != J) # off diagonal mask
|
| 772 |
+
od_I = I[mask]
|
| 773 |
+
od_J = J[mask]
|
| 774 |
+
od_V = V[mask]
|
| 775 |
+
|
| 776 |
+
I = concatenate((I, od_J))
|
| 777 |
+
J = concatenate((J, od_I))
|
| 778 |
+
|
| 779 |
+
if is_skew:
|
| 780 |
+
od_V *= -1
|
| 781 |
+
elif is_herm:
|
| 782 |
+
od_V = od_V.conjugate()
|
| 783 |
+
|
| 784 |
+
V = concatenate((V, od_V))
|
| 785 |
+
|
| 786 |
+
a = coo_array((V, (I, J)), shape=(rows, cols), dtype=dtype)
|
| 787 |
+
else:
|
| 788 |
+
raise NotImplementedError(format)
|
| 789 |
+
|
| 790 |
+
return a
|
| 791 |
+
|
| 792 |
+
# ------------------------------------------------------------------------
|
| 793 |
+
def _write(self, stream, a, comment='', field=None, precision=None,
|
| 794 |
+
symmetry=None):
|
| 795 |
+
if isinstance(a, list) or isinstance(a, ndarray) or \
|
| 796 |
+
isinstance(a, tuple) or hasattr(a, '__array__'):
|
| 797 |
+
rep = self.FORMAT_ARRAY
|
| 798 |
+
a = asarray(a)
|
| 799 |
+
if len(a.shape) != 2:
|
| 800 |
+
raise ValueError('Expected 2 dimensional array')
|
| 801 |
+
rows, cols = a.shape
|
| 802 |
+
|
| 803 |
+
if field is not None:
|
| 804 |
+
|
| 805 |
+
if field == self.FIELD_INTEGER:
|
| 806 |
+
if not can_cast(a.dtype, 'intp'):
|
| 807 |
+
raise OverflowError("mmwrite does not support integer "
|
| 808 |
+
"dtypes larger than native 'intp'.")
|
| 809 |
+
a = a.astype('intp')
|
| 810 |
+
elif field == self.FIELD_REAL:
|
| 811 |
+
if a.dtype.char not in 'fd':
|
| 812 |
+
a = a.astype('d')
|
| 813 |
+
elif field == self.FIELD_COMPLEX:
|
| 814 |
+
if a.dtype.char not in 'FD':
|
| 815 |
+
a = a.astype('D')
|
| 816 |
+
|
| 817 |
+
else:
|
| 818 |
+
if not issparse(a):
|
| 819 |
+
raise ValueError(f'unknown matrix type: {type(a)}')
|
| 820 |
+
|
| 821 |
+
rep = 'coordinate'
|
| 822 |
+
rows, cols = a.shape
|
| 823 |
+
|
| 824 |
+
typecode = a.dtype.char
|
| 825 |
+
|
| 826 |
+
if precision is None:
|
| 827 |
+
if typecode in 'fF':
|
| 828 |
+
precision = 8
|
| 829 |
+
else:
|
| 830 |
+
precision = 16
|
| 831 |
+
if field is None:
|
| 832 |
+
kind = a.dtype.kind
|
| 833 |
+
if kind == 'i':
|
| 834 |
+
if not can_cast(a.dtype, 'intp'):
|
| 835 |
+
raise OverflowError("mmwrite does not support integer "
|
| 836 |
+
"dtypes larger than native 'intp'.")
|
| 837 |
+
field = 'integer'
|
| 838 |
+
elif kind == 'f':
|
| 839 |
+
field = 'real'
|
| 840 |
+
elif kind == 'c':
|
| 841 |
+
field = 'complex'
|
| 842 |
+
elif kind == 'u':
|
| 843 |
+
field = 'unsigned-integer'
|
| 844 |
+
else:
|
| 845 |
+
raise TypeError('unexpected dtype kind ' + kind)
|
| 846 |
+
|
| 847 |
+
if symmetry is None:
|
| 848 |
+
symmetry = self._get_symmetry(a)
|
| 849 |
+
|
| 850 |
+
# validate rep, field, and symmetry
|
| 851 |
+
self.__class__._validate_format(rep)
|
| 852 |
+
self.__class__._validate_field(field)
|
| 853 |
+
self.__class__._validate_symmetry(symmetry)
|
| 854 |
+
|
| 855 |
+
# write initial header line
|
| 856 |
+
data = f'%%MatrixMarket matrix {rep} {field} {symmetry}\n'
|
| 857 |
+
stream.write(data.encode('latin1'))
|
| 858 |
+
|
| 859 |
+
# write comments
|
| 860 |
+
for line in comment.split('\n'):
|
| 861 |
+
data = f'%{line}\n'
|
| 862 |
+
stream.write(data.encode('latin1'))
|
| 863 |
+
|
| 864 |
+
template = self._field_template(field, precision)
|
| 865 |
+
# write dense format
|
| 866 |
+
if rep == self.FORMAT_ARRAY:
|
| 867 |
+
# write shape spec
|
| 868 |
+
data = '%i %i\n' % (rows, cols)
|
| 869 |
+
stream.write(data.encode('latin1'))
|
| 870 |
+
|
| 871 |
+
if field in (self.FIELD_INTEGER, self.FIELD_REAL,
|
| 872 |
+
self.FIELD_UNSIGNED):
|
| 873 |
+
if symmetry == self.SYMMETRY_GENERAL:
|
| 874 |
+
for j in range(cols):
|
| 875 |
+
for i in range(rows):
|
| 876 |
+
data = template % a[i, j]
|
| 877 |
+
stream.write(data.encode('latin1'))
|
| 878 |
+
|
| 879 |
+
elif symmetry == self.SYMMETRY_SKEW_SYMMETRIC:
|
| 880 |
+
for j in range(cols):
|
| 881 |
+
for i in range(j + 1, rows):
|
| 882 |
+
data = template % a[i, j]
|
| 883 |
+
stream.write(data.encode('latin1'))
|
| 884 |
+
|
| 885 |
+
else:
|
| 886 |
+
for j in range(cols):
|
| 887 |
+
for i in range(j, rows):
|
| 888 |
+
data = template % a[i, j]
|
| 889 |
+
stream.write(data.encode('latin1'))
|
| 890 |
+
|
| 891 |
+
elif field == self.FIELD_COMPLEX:
|
| 892 |
+
|
| 893 |
+
if symmetry == self.SYMMETRY_GENERAL:
|
| 894 |
+
for j in range(cols):
|
| 895 |
+
for i in range(rows):
|
| 896 |
+
aij = a[i, j]
|
| 897 |
+
data = template % (real(aij), imag(aij))
|
| 898 |
+
stream.write(data.encode('latin1'))
|
| 899 |
+
else:
|
| 900 |
+
for j in range(cols):
|
| 901 |
+
for i in range(j, rows):
|
| 902 |
+
aij = a[i, j]
|
| 903 |
+
data = template % (real(aij), imag(aij))
|
| 904 |
+
stream.write(data.encode('latin1'))
|
| 905 |
+
|
| 906 |
+
elif field == self.FIELD_PATTERN:
|
| 907 |
+
raise ValueError('pattern type inconsisted with dense format')
|
| 908 |
+
|
| 909 |
+
else:
|
| 910 |
+
raise TypeError(f'Unknown field type {field}')
|
| 911 |
+
|
| 912 |
+
# write sparse format
|
| 913 |
+
else:
|
| 914 |
+
coo = a.tocoo() # convert to COOrdinate format
|
| 915 |
+
|
| 916 |
+
# if symmetry format used, remove values above main diagonal
|
| 917 |
+
if symmetry != self.SYMMETRY_GENERAL:
|
| 918 |
+
lower_triangle_mask = coo.row >= coo.col
|
| 919 |
+
coo = coo_array((coo.data[lower_triangle_mask],
|
| 920 |
+
(coo.row[lower_triangle_mask],
|
| 921 |
+
coo.col[lower_triangle_mask])),
|
| 922 |
+
shape=coo.shape)
|
| 923 |
+
|
| 924 |
+
# write shape spec
|
| 925 |
+
data = '%i %i %i\n' % (rows, cols, coo.nnz)
|
| 926 |
+
stream.write(data.encode('latin1'))
|
| 927 |
+
|
| 928 |
+
template = self._field_template(field, precision-1)
|
| 929 |
+
|
| 930 |
+
if field == self.FIELD_PATTERN:
|
| 931 |
+
for r, c in zip(coo.row+1, coo.col+1):
|
| 932 |
+
data = "%i %i\n" % (r, c)
|
| 933 |
+
stream.write(data.encode('latin1'))
|
| 934 |
+
elif field in (self.FIELD_INTEGER, self.FIELD_REAL,
|
| 935 |
+
self.FIELD_UNSIGNED):
|
| 936 |
+
for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
|
| 937 |
+
data = ("%i %i " % (r, c)) + (template % d)
|
| 938 |
+
stream.write(data.encode('latin1'))
|
| 939 |
+
elif field == self.FIELD_COMPLEX:
|
| 940 |
+
for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
|
| 941 |
+
data = ("%i %i " % (r, c)) + (template % (d.real, d.imag))
|
| 942 |
+
stream.write(data.encode('latin1'))
|
| 943 |
+
else:
|
| 944 |
+
raise TypeError(f'Unknown field type {field}')
|
| 945 |
+
|
| 946 |
+
|
| 947 |
+
def _is_fromfile_compatible(stream):
|
| 948 |
+
"""
|
| 949 |
+
Check whether `stream` is compatible with numpy.fromfile.
|
| 950 |
+
|
| 951 |
+
Passing a gzipped file object to ``fromfile/fromstring`` doesn't work with
|
| 952 |
+
Python 3.
|
| 953 |
+
"""
|
| 954 |
+
|
| 955 |
+
bad_cls = []
|
| 956 |
+
try:
|
| 957 |
+
import gzip
|
| 958 |
+
bad_cls.append(gzip.GzipFile)
|
| 959 |
+
except ImportError:
|
| 960 |
+
pass
|
| 961 |
+
try:
|
| 962 |
+
import bz2
|
| 963 |
+
bad_cls.append(bz2.BZ2File)
|
| 964 |
+
except ImportError:
|
| 965 |
+
pass
|
| 966 |
+
|
| 967 |
+
bad_cls = tuple(bad_cls)
|
| 968 |
+
return not isinstance(stream, bad_cls)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/_netcdf.py
ADDED
|
@@ -0,0 +1,1104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NetCDF reader/writer module.
|
| 3 |
+
|
| 4 |
+
This module is used to read and create NetCDF files. NetCDF files are
|
| 5 |
+
accessed through the `netcdf_file` object. Data written to and from NetCDF
|
| 6 |
+
files are contained in `netcdf_variable` objects. Attributes are given
|
| 7 |
+
as member variables of the `netcdf_file` and `netcdf_variable` objects.
|
| 8 |
+
|
| 9 |
+
This module implements the Scientific.IO.NetCDF API to read and create
|
| 10 |
+
NetCDF files. The same API is also used in the PyNIO and pynetcdf
|
| 11 |
+
modules, allowing these modules to be used interchangeably when working
|
| 12 |
+
with NetCDF files.
|
| 13 |
+
|
| 14 |
+
Only NetCDF3 is supported here; for NetCDF4 see
|
| 15 |
+
`netCDF4-python <http://unidata.github.io/netcdf4-python/>`__,
|
| 16 |
+
which has a similar API.
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
# TODO:
|
| 21 |
+
# * properly implement ``_FillValue``.
|
| 22 |
+
# * fix character variables.
|
| 23 |
+
# * implement PAGESIZE for Python 2.6?
|
| 24 |
+
|
| 25 |
+
# The Scientific.IO.NetCDF API allows attributes to be added directly to
|
| 26 |
+
# instances of ``netcdf_file`` and ``netcdf_variable``. To differentiate
|
| 27 |
+
# between user-set attributes and instance attributes, user-set attributes
|
| 28 |
+
# are automatically stored in the ``_attributes`` attribute by overloading
|
| 29 |
+
#``__setattr__``. This is the reason why the code sometimes uses
|
| 30 |
+
#``obj.__dict__['key'] = value``, instead of simply ``obj.key = value``;
|
| 31 |
+
# otherwise the key would be inserted into userspace attributes.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
__all__ = ['netcdf_file', 'netcdf_variable']
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
import warnings
|
| 38 |
+
import weakref
|
| 39 |
+
from operator import mul
|
| 40 |
+
from platform import python_implementation
|
| 41 |
+
|
| 42 |
+
import mmap as mm
|
| 43 |
+
|
| 44 |
+
import numpy as np
|
| 45 |
+
from numpy import frombuffer, dtype, empty, array, asarray
|
| 46 |
+
from numpy import little_endian as LITTLE_ENDIAN
|
| 47 |
+
from functools import reduce
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
IS_PYPY = python_implementation() == 'PyPy'
|
| 51 |
+
|
| 52 |
+
ABSENT = b'\x00\x00\x00\x00\x00\x00\x00\x00'
|
| 53 |
+
ZERO = b'\x00\x00\x00\x00'
|
| 54 |
+
NC_BYTE = b'\x00\x00\x00\x01'
|
| 55 |
+
NC_CHAR = b'\x00\x00\x00\x02'
|
| 56 |
+
NC_SHORT = b'\x00\x00\x00\x03'
|
| 57 |
+
NC_INT = b'\x00\x00\x00\x04'
|
| 58 |
+
NC_FLOAT = b'\x00\x00\x00\x05'
|
| 59 |
+
NC_DOUBLE = b'\x00\x00\x00\x06'
|
| 60 |
+
NC_DIMENSION = b'\x00\x00\x00\n'
|
| 61 |
+
NC_VARIABLE = b'\x00\x00\x00\x0b'
|
| 62 |
+
NC_ATTRIBUTE = b'\x00\x00\x00\x0c'
|
| 63 |
+
FILL_BYTE = b'\x81'
|
| 64 |
+
FILL_CHAR = b'\x00'
|
| 65 |
+
FILL_SHORT = b'\x80\x01'
|
| 66 |
+
FILL_INT = b'\x80\x00\x00\x01'
|
| 67 |
+
FILL_FLOAT = b'\x7C\xF0\x00\x00'
|
| 68 |
+
FILL_DOUBLE = b'\x47\x9E\x00\x00\x00\x00\x00\x00'
|
| 69 |
+
|
| 70 |
+
TYPEMAP = {NC_BYTE: ('b', 1),
|
| 71 |
+
NC_CHAR: ('c', 1),
|
| 72 |
+
NC_SHORT: ('h', 2),
|
| 73 |
+
NC_INT: ('i', 4),
|
| 74 |
+
NC_FLOAT: ('f', 4),
|
| 75 |
+
NC_DOUBLE: ('d', 8)}
|
| 76 |
+
|
| 77 |
+
FILLMAP = {NC_BYTE: FILL_BYTE,
|
| 78 |
+
NC_CHAR: FILL_CHAR,
|
| 79 |
+
NC_SHORT: FILL_SHORT,
|
| 80 |
+
NC_INT: FILL_INT,
|
| 81 |
+
NC_FLOAT: FILL_FLOAT,
|
| 82 |
+
NC_DOUBLE: FILL_DOUBLE}
|
| 83 |
+
|
| 84 |
+
REVERSE = {('b', 1): NC_BYTE,
|
| 85 |
+
('B', 1): NC_CHAR,
|
| 86 |
+
('c', 1): NC_CHAR,
|
| 87 |
+
('h', 2): NC_SHORT,
|
| 88 |
+
('i', 4): NC_INT,
|
| 89 |
+
('f', 4): NC_FLOAT,
|
| 90 |
+
('d', 8): NC_DOUBLE,
|
| 91 |
+
|
| 92 |
+
# these come from asarray(1).dtype.char and asarray('foo').dtype.char,
|
| 93 |
+
# used when getting the types from generic attributes.
|
| 94 |
+
('l', 4): NC_INT,
|
| 95 |
+
('S', 1): NC_CHAR}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class netcdf_file:
|
| 99 |
+
"""
|
| 100 |
+
A file object for NetCDF data.
|
| 101 |
+
|
| 102 |
+
A `netcdf_file` object has two standard attributes: `dimensions` and
|
| 103 |
+
`variables`. The values of both are dictionaries, mapping dimension
|
| 104 |
+
names to their associated lengths and variable names to variables,
|
| 105 |
+
respectively. Application programs should never modify these
|
| 106 |
+
dictionaries.
|
| 107 |
+
|
| 108 |
+
All other attributes correspond to global attributes defined in the
|
| 109 |
+
NetCDF file. Global file attributes are created by assigning to an
|
| 110 |
+
attribute of the `netcdf_file` object.
|
| 111 |
+
|
| 112 |
+
Parameters
|
| 113 |
+
----------
|
| 114 |
+
filename : string or file-like
|
| 115 |
+
string -> filename
|
| 116 |
+
mode : {'r', 'w', 'a'}, optional
|
| 117 |
+
read-write-append mode, default is 'r'
|
| 118 |
+
mmap : None or bool, optional
|
| 119 |
+
Whether to mmap `filename` when reading. Default is True
|
| 120 |
+
when `filename` is a file name, False when `filename` is a
|
| 121 |
+
file-like object. Note that when mmap is in use, data arrays
|
| 122 |
+
returned refer directly to the mmapped data on disk, and the
|
| 123 |
+
file cannot be closed as long as references to it exist.
|
| 124 |
+
version : {1, 2}, optional
|
| 125 |
+
version of netcdf to read / write, where 1 means *Classic
|
| 126 |
+
format* and 2 means *64-bit offset format*. Default is 1. See
|
| 127 |
+
`here <https://docs.unidata.ucar.edu/nug/current/netcdf_introduction.html#select_format>`__
|
| 128 |
+
for more info.
|
| 129 |
+
maskandscale : bool, optional
|
| 130 |
+
Whether to automatically scale and/or mask data based on attributes.
|
| 131 |
+
Default is False.
|
| 132 |
+
|
| 133 |
+
Notes
|
| 134 |
+
-----
|
| 135 |
+
This module is derived from
|
| 136 |
+
`pupynere <https://bitbucket.org/robertodealmeida/pupynere/>`_.
|
| 137 |
+
The major advantage of this module over other modules is that it doesn't
|
| 138 |
+
require the code to be linked to the NetCDF libraries. However, for a more
|
| 139 |
+
recent version of the NetCDF standard and additional features, please consider
|
| 140 |
+
the permissively-licensed
|
| 141 |
+
`netcdf4-python <https://unidata.github.io/netcdf4-python/>`_.
|
| 142 |
+
|
| 143 |
+
NetCDF files are a self-describing binary data format. The file contains
|
| 144 |
+
metadata that describes the dimensions and variables in the file. More
|
| 145 |
+
details about NetCDF files can be found `here
|
| 146 |
+
<https://www.unidata.ucar.edu/software/netcdf/guide_toc.html>`__. There
|
| 147 |
+
are three main sections to a NetCDF data structure:
|
| 148 |
+
|
| 149 |
+
1. Dimensions
|
| 150 |
+
2. Variables
|
| 151 |
+
3. Attributes
|
| 152 |
+
|
| 153 |
+
The dimensions section records the name and length of each dimension used
|
| 154 |
+
by the variables. The variables would then indicate which dimensions it
|
| 155 |
+
uses and any attributes such as data units, along with containing the data
|
| 156 |
+
values for the variable. It is good practice to include a
|
| 157 |
+
variable that is the same name as a dimension to provide the values for
|
| 158 |
+
that axes. Lastly, the attributes section would contain additional
|
| 159 |
+
information such as the name of the file creator or the instrument used to
|
| 160 |
+
collect the data.
|
| 161 |
+
|
| 162 |
+
When writing data to a NetCDF file, there is often the need to indicate the
|
| 163 |
+
'record dimension'. A record dimension is the unbounded dimension for a
|
| 164 |
+
variable. For example, a temperature variable may have dimensions of
|
| 165 |
+
latitude, longitude and time. If one wants to add more temperature data to
|
| 166 |
+
the NetCDF file as time progresses, then the temperature variable should
|
| 167 |
+
have the time dimension flagged as the record dimension.
|
| 168 |
+
|
| 169 |
+
In addition, the NetCDF file header contains the position of the data in
|
| 170 |
+
the file, so access can be done in an efficient manner without loading
|
| 171 |
+
unnecessary data into memory. It uses the ``mmap`` module to create
|
| 172 |
+
Numpy arrays mapped to the data on disk, for the same purpose.
|
| 173 |
+
|
| 174 |
+
Note that when `netcdf_file` is used to open a file with mmap=True
|
| 175 |
+
(default for read-only), arrays returned by it refer to data
|
| 176 |
+
directly on the disk. The file should not be closed, and cannot be cleanly
|
| 177 |
+
closed when asked, if such arrays are alive. You may want to copy data arrays
|
| 178 |
+
obtained from mmapped Netcdf file if they are to be processed after the file
|
| 179 |
+
is closed, see the example below.
|
| 180 |
+
|
| 181 |
+
Examples
|
| 182 |
+
--------
|
| 183 |
+
To create a NetCDF file:
|
| 184 |
+
|
| 185 |
+
>>> from scipy.io import netcdf_file
|
| 186 |
+
>>> import numpy as np
|
| 187 |
+
>>> f = netcdf_file('simple.nc', 'w')
|
| 188 |
+
>>> f.history = 'Created for a test'
|
| 189 |
+
>>> f.createDimension('time', 10)
|
| 190 |
+
>>> time = f.createVariable('time', 'i', ('time',))
|
| 191 |
+
>>> time[:] = np.arange(10)
|
| 192 |
+
>>> time.units = 'days since 2008-01-01'
|
| 193 |
+
>>> f.close()
|
| 194 |
+
|
| 195 |
+
Note the assignment of ``arange(10)`` to ``time[:]``. Exposing the slice
|
| 196 |
+
of the time variable allows for the data to be set in the object, rather
|
| 197 |
+
than letting ``arange(10)`` overwrite the ``time`` variable.
|
| 198 |
+
|
| 199 |
+
To read the NetCDF file we just created:
|
| 200 |
+
|
| 201 |
+
>>> from scipy.io import netcdf_file
|
| 202 |
+
>>> f = netcdf_file('simple.nc', 'r')
|
| 203 |
+
>>> print(f.history)
|
| 204 |
+
b'Created for a test'
|
| 205 |
+
>>> time = f.variables['time']
|
| 206 |
+
>>> print(time.units)
|
| 207 |
+
b'days since 2008-01-01'
|
| 208 |
+
>>> print(time.shape)
|
| 209 |
+
(10,)
|
| 210 |
+
>>> print(time[-1])
|
| 211 |
+
9
|
| 212 |
+
|
| 213 |
+
NetCDF files, when opened read-only, return arrays that refer
|
| 214 |
+
directly to memory-mapped data on disk:
|
| 215 |
+
|
| 216 |
+
>>> data = time[:]
|
| 217 |
+
|
| 218 |
+
If the data is to be processed after the file is closed, it needs
|
| 219 |
+
to be copied to main memory:
|
| 220 |
+
|
| 221 |
+
>>> data = time[:].copy()
|
| 222 |
+
>>> del time
|
| 223 |
+
>>> f.close()
|
| 224 |
+
>>> data.mean()
|
| 225 |
+
4.5
|
| 226 |
+
|
| 227 |
+
A NetCDF file can also be used as context manager:
|
| 228 |
+
|
| 229 |
+
>>> from scipy.io import netcdf_file
|
| 230 |
+
>>> with netcdf_file('simple.nc', 'r') as f:
|
| 231 |
+
... print(f.history)
|
| 232 |
+
b'Created for a test'
|
| 233 |
+
|
| 234 |
+
"""
|
| 235 |
+
def __init__(self, filename, mode='r', mmap=None, version=1,
|
| 236 |
+
maskandscale=False):
|
| 237 |
+
"""Initialize netcdf_file from fileobj (str or file-like)."""
|
| 238 |
+
if mode not in 'rwa':
|
| 239 |
+
raise ValueError("Mode must be either 'r', 'w' or 'a'.")
|
| 240 |
+
|
| 241 |
+
if hasattr(filename, 'seek'): # file-like
|
| 242 |
+
self.fp = filename
|
| 243 |
+
self.filename = 'None'
|
| 244 |
+
if mmap is None:
|
| 245 |
+
mmap = False
|
| 246 |
+
elif mmap and not hasattr(filename, 'fileno'):
|
| 247 |
+
raise ValueError('Cannot use file object for mmap')
|
| 248 |
+
else: # maybe it's a string
|
| 249 |
+
self.filename = filename
|
| 250 |
+
omode = 'r+' if mode == 'a' else mode
|
| 251 |
+
self.fp = open(self.filename, f'{omode}b')
|
| 252 |
+
if mmap is None:
|
| 253 |
+
# Mmapped files on PyPy cannot be usually closed
|
| 254 |
+
# before the GC runs, so it's better to use mmap=False
|
| 255 |
+
# as the default.
|
| 256 |
+
mmap = (not IS_PYPY)
|
| 257 |
+
|
| 258 |
+
if mode != 'r':
|
| 259 |
+
# Cannot read write-only files
|
| 260 |
+
mmap = False
|
| 261 |
+
|
| 262 |
+
self.use_mmap = mmap
|
| 263 |
+
self.mode = mode
|
| 264 |
+
self.version_byte = version
|
| 265 |
+
self.maskandscale = maskandscale
|
| 266 |
+
|
| 267 |
+
self.dimensions = {}
|
| 268 |
+
self.variables = {}
|
| 269 |
+
|
| 270 |
+
self._dims = []
|
| 271 |
+
self._recs = 0
|
| 272 |
+
self._recsize = 0
|
| 273 |
+
|
| 274 |
+
self._mm = None
|
| 275 |
+
self._mm_buf = None
|
| 276 |
+
if self.use_mmap:
|
| 277 |
+
self._mm = mm.mmap(self.fp.fileno(), 0, access=mm.ACCESS_READ)
|
| 278 |
+
self._mm_buf = np.frombuffer(self._mm, dtype=np.int8)
|
| 279 |
+
|
| 280 |
+
self._attributes = {}
|
| 281 |
+
|
| 282 |
+
if mode in 'ra':
|
| 283 |
+
self._read()
|
| 284 |
+
|
| 285 |
+
def __setattr__(self, attr, value):
|
| 286 |
+
# Store user defined attributes in a separate dict,
|
| 287 |
+
# so we can save them to file later.
|
| 288 |
+
try:
|
| 289 |
+
self._attributes[attr] = value
|
| 290 |
+
except AttributeError:
|
| 291 |
+
pass
|
| 292 |
+
self.__dict__[attr] = value
|
| 293 |
+
|
| 294 |
+
def close(self):
|
| 295 |
+
"""Closes the NetCDF file."""
|
| 296 |
+
if hasattr(self, 'fp') and not self.fp.closed:
|
| 297 |
+
try:
|
| 298 |
+
self.flush()
|
| 299 |
+
finally:
|
| 300 |
+
self.variables = {}
|
| 301 |
+
if self._mm_buf is not None:
|
| 302 |
+
ref = weakref.ref(self._mm_buf)
|
| 303 |
+
self._mm_buf = None
|
| 304 |
+
if ref() is None:
|
| 305 |
+
# self._mm_buf is gc'd, and we can close the mmap
|
| 306 |
+
self._mm.close()
|
| 307 |
+
else:
|
| 308 |
+
# we cannot close self._mm, since self._mm_buf is
|
| 309 |
+
# alive and there may still be arrays referring to it
|
| 310 |
+
warnings.warn(
|
| 311 |
+
"Cannot close a netcdf_file opened with mmap=True, when "
|
| 312 |
+
"netcdf_variables or arrays referring to its data still "
|
| 313 |
+
"exist. All data arrays obtained from such files refer "
|
| 314 |
+
"directly to data on disk, and must be copied before the "
|
| 315 |
+
"file can be cleanly closed. "
|
| 316 |
+
"(See netcdf_file docstring for more information on mmap.)",
|
| 317 |
+
category=RuntimeWarning, stacklevel=2,
|
| 318 |
+
)
|
| 319 |
+
self._mm = None
|
| 320 |
+
self.fp.close()
|
| 321 |
+
__del__ = close
|
| 322 |
+
|
| 323 |
+
def __enter__(self):
|
| 324 |
+
return self
|
| 325 |
+
|
| 326 |
+
def __exit__(self, type, value, traceback):
|
| 327 |
+
self.close()
|
| 328 |
+
|
| 329 |
+
def createDimension(self, name, length):
|
| 330 |
+
"""
|
| 331 |
+
Adds a dimension to the Dimension section of the NetCDF data structure.
|
| 332 |
+
|
| 333 |
+
Note that this function merely adds a new dimension that the variables can
|
| 334 |
+
reference. The values for the dimension, if desired, should be added as
|
| 335 |
+
a variable using `createVariable`, referring to this dimension.
|
| 336 |
+
|
| 337 |
+
Parameters
|
| 338 |
+
----------
|
| 339 |
+
name : str
|
| 340 |
+
Name of the dimension (Eg, 'lat' or 'time').
|
| 341 |
+
length : int
|
| 342 |
+
Length of the dimension.
|
| 343 |
+
|
| 344 |
+
See Also
|
| 345 |
+
--------
|
| 346 |
+
createVariable
|
| 347 |
+
|
| 348 |
+
"""
|
| 349 |
+
if length is None and self._dims:
|
| 350 |
+
raise ValueError("Only first dimension may be unlimited!")
|
| 351 |
+
|
| 352 |
+
self.dimensions[name] = length
|
| 353 |
+
self._dims.append(name)
|
| 354 |
+
|
| 355 |
+
def createVariable(self, name, type, dimensions):
|
| 356 |
+
"""
|
| 357 |
+
Create an empty variable for the `netcdf_file` object, specifying its data
|
| 358 |
+
type and the dimensions it uses.
|
| 359 |
+
|
| 360 |
+
Parameters
|
| 361 |
+
----------
|
| 362 |
+
name : str
|
| 363 |
+
Name of the new variable.
|
| 364 |
+
type : dtype or str
|
| 365 |
+
Data type of the variable.
|
| 366 |
+
dimensions : sequence of str
|
| 367 |
+
List of the dimension names used by the variable, in the desired order.
|
| 368 |
+
|
| 369 |
+
Returns
|
| 370 |
+
-------
|
| 371 |
+
variable : netcdf_variable
|
| 372 |
+
The newly created ``netcdf_variable`` object.
|
| 373 |
+
This object has also been added to the `netcdf_file` object as well.
|
| 374 |
+
|
| 375 |
+
See Also
|
| 376 |
+
--------
|
| 377 |
+
createDimension
|
| 378 |
+
|
| 379 |
+
Notes
|
| 380 |
+
-----
|
| 381 |
+
Any dimensions to be used by the variable should already exist in the
|
| 382 |
+
NetCDF data structure or should be created by `createDimension` prior to
|
| 383 |
+
creating the NetCDF variable.
|
| 384 |
+
|
| 385 |
+
"""
|
| 386 |
+
shape = tuple([self.dimensions[dim] for dim in dimensions])
|
| 387 |
+
shape_ = tuple([dim or 0 for dim in shape]) # replace None with 0 for NumPy
|
| 388 |
+
|
| 389 |
+
type = dtype(type)
|
| 390 |
+
typecode, size = type.char, type.itemsize
|
| 391 |
+
if (typecode, size) not in REVERSE:
|
| 392 |
+
raise ValueError(f"NetCDF 3 does not support type {type}")
|
| 393 |
+
|
| 394 |
+
# convert to big endian always for NetCDF 3
|
| 395 |
+
data = empty(shape_, dtype=type.newbyteorder("B"))
|
| 396 |
+
self.variables[name] = netcdf_variable(
|
| 397 |
+
data, typecode, size, shape, dimensions,
|
| 398 |
+
maskandscale=self.maskandscale)
|
| 399 |
+
return self.variables[name]
|
| 400 |
+
|
| 401 |
+
def flush(self):
|
| 402 |
+
"""
|
| 403 |
+
Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.
|
| 404 |
+
|
| 405 |
+
See Also
|
| 406 |
+
--------
|
| 407 |
+
sync : Identical function
|
| 408 |
+
|
| 409 |
+
"""
|
| 410 |
+
if hasattr(self, 'mode') and self.mode in 'wa':
|
| 411 |
+
self._write()
|
| 412 |
+
sync = flush
|
| 413 |
+
|
| 414 |
+
def _write(self):
|
| 415 |
+
self.fp.seek(0)
|
| 416 |
+
self.fp.write(b'CDF')
|
| 417 |
+
self.fp.write(array(self.version_byte, '>b').tobytes())
|
| 418 |
+
|
| 419 |
+
# Write headers and data.
|
| 420 |
+
self._write_numrecs()
|
| 421 |
+
self._write_dim_array()
|
| 422 |
+
self._write_gatt_array()
|
| 423 |
+
self._write_var_array()
|
| 424 |
+
|
| 425 |
+
def _write_numrecs(self):
|
| 426 |
+
# Get highest record count from all record variables.
|
| 427 |
+
for var in self.variables.values():
|
| 428 |
+
if var.isrec and len(var.data) > self._recs:
|
| 429 |
+
self.__dict__['_recs'] = len(var.data)
|
| 430 |
+
self._pack_int(self._recs)
|
| 431 |
+
|
| 432 |
+
def _write_dim_array(self):
|
| 433 |
+
if self.dimensions:
|
| 434 |
+
self.fp.write(NC_DIMENSION)
|
| 435 |
+
self._pack_int(len(self.dimensions))
|
| 436 |
+
for name in self._dims:
|
| 437 |
+
self._pack_string(name)
|
| 438 |
+
length = self.dimensions[name]
|
| 439 |
+
self._pack_int(length or 0) # replace None with 0 for record dimension
|
| 440 |
+
else:
|
| 441 |
+
self.fp.write(ABSENT)
|
| 442 |
+
|
| 443 |
+
def _write_gatt_array(self):
|
| 444 |
+
self._write_att_array(self._attributes)
|
| 445 |
+
|
| 446 |
+
def _write_att_array(self, attributes):
|
| 447 |
+
if attributes:
|
| 448 |
+
self.fp.write(NC_ATTRIBUTE)
|
| 449 |
+
self._pack_int(len(attributes))
|
| 450 |
+
for name, values in attributes.items():
|
| 451 |
+
self._pack_string(name)
|
| 452 |
+
self._write_att_values(values)
|
| 453 |
+
else:
|
| 454 |
+
self.fp.write(ABSENT)
|
| 455 |
+
|
| 456 |
+
def _write_var_array(self):
|
| 457 |
+
if self.variables:
|
| 458 |
+
self.fp.write(NC_VARIABLE)
|
| 459 |
+
self._pack_int(len(self.variables))
|
| 460 |
+
|
| 461 |
+
# Sort variable names non-recs first, then recs.
|
| 462 |
+
def sortkey(n):
|
| 463 |
+
v = self.variables[n]
|
| 464 |
+
if v.isrec:
|
| 465 |
+
return (-1,)
|
| 466 |
+
return v._shape
|
| 467 |
+
variables = sorted(self.variables, key=sortkey, reverse=True)
|
| 468 |
+
|
| 469 |
+
# Set the metadata for all variables.
|
| 470 |
+
for name in variables:
|
| 471 |
+
self._write_var_metadata(name)
|
| 472 |
+
# Now that we have the metadata, we know the vsize of
|
| 473 |
+
# each record variable, so we can calculate recsize.
|
| 474 |
+
self.__dict__['_recsize'] = sum([
|
| 475 |
+
var._vsize for var in self.variables.values()
|
| 476 |
+
if var.isrec])
|
| 477 |
+
# Set the data for all variables.
|
| 478 |
+
for name in variables:
|
| 479 |
+
self._write_var_data(name)
|
| 480 |
+
else:
|
| 481 |
+
self.fp.write(ABSENT)
|
| 482 |
+
|
| 483 |
+
def _write_var_metadata(self, name):
|
| 484 |
+
var = self.variables[name]
|
| 485 |
+
|
| 486 |
+
self._pack_string(name)
|
| 487 |
+
self._pack_int(len(var.dimensions))
|
| 488 |
+
for dimname in var.dimensions:
|
| 489 |
+
dimid = self._dims.index(dimname)
|
| 490 |
+
self._pack_int(dimid)
|
| 491 |
+
|
| 492 |
+
self._write_att_array(var._attributes)
|
| 493 |
+
|
| 494 |
+
nc_type = REVERSE[var.typecode(), var.itemsize()]
|
| 495 |
+
self.fp.write(nc_type)
|
| 496 |
+
|
| 497 |
+
if not var.isrec:
|
| 498 |
+
vsize = var.data.size * var.data.itemsize
|
| 499 |
+
vsize += -vsize % 4
|
| 500 |
+
else: # record variable
|
| 501 |
+
try:
|
| 502 |
+
vsize = var.data[0].size * var.data.itemsize
|
| 503 |
+
except IndexError:
|
| 504 |
+
vsize = 0
|
| 505 |
+
rec_vars = len([v for v in self.variables.values()
|
| 506 |
+
if v.isrec])
|
| 507 |
+
if rec_vars > 1:
|
| 508 |
+
vsize += -vsize % 4
|
| 509 |
+
self.variables[name].__dict__['_vsize'] = vsize
|
| 510 |
+
self._pack_int(vsize)
|
| 511 |
+
|
| 512 |
+
# Pack a bogus begin, and set the real value later.
|
| 513 |
+
self.variables[name].__dict__['_begin'] = self.fp.tell()
|
| 514 |
+
self._pack_begin(0)
|
| 515 |
+
|
| 516 |
+
def _write_var_data(self, name):
|
| 517 |
+
var = self.variables[name]
|
| 518 |
+
|
| 519 |
+
# Set begin in file header.
|
| 520 |
+
the_beguine = self.fp.tell()
|
| 521 |
+
self.fp.seek(var._begin)
|
| 522 |
+
self._pack_begin(the_beguine)
|
| 523 |
+
self.fp.seek(the_beguine)
|
| 524 |
+
|
| 525 |
+
# Write data.
|
| 526 |
+
if not var.isrec:
|
| 527 |
+
self.fp.write(var.data.tobytes())
|
| 528 |
+
count = var.data.size * var.data.itemsize
|
| 529 |
+
self._write_var_padding(var, var._vsize - count)
|
| 530 |
+
else: # record variable
|
| 531 |
+
# Handle rec vars with shape[0] < nrecs.
|
| 532 |
+
if self._recs > len(var.data):
|
| 533 |
+
shape = (self._recs,) + var.data.shape[1:]
|
| 534 |
+
# Resize in-place does not always work since
|
| 535 |
+
# the array might not be single-segment
|
| 536 |
+
try:
|
| 537 |
+
var.data.resize(shape)
|
| 538 |
+
except ValueError:
|
| 539 |
+
dtype = var.data.dtype
|
| 540 |
+
var.__dict__['data'] = np.resize(var.data, shape).astype(dtype)
|
| 541 |
+
|
| 542 |
+
pos0 = pos = self.fp.tell()
|
| 543 |
+
for rec in var.data:
|
| 544 |
+
# Apparently scalars cannot be converted to big endian. If we
|
| 545 |
+
# try to convert a ``=i4`` scalar to, say, '>i4' the dtype
|
| 546 |
+
# will remain as ``=i4``.
|
| 547 |
+
if not rec.shape and (rec.dtype.byteorder == '<' or
|
| 548 |
+
(rec.dtype.byteorder == '=' and LITTLE_ENDIAN)):
|
| 549 |
+
rec = rec.byteswap()
|
| 550 |
+
self.fp.write(rec.tobytes())
|
| 551 |
+
# Padding
|
| 552 |
+
count = rec.size * rec.itemsize
|
| 553 |
+
self._write_var_padding(var, var._vsize - count)
|
| 554 |
+
pos += self._recsize
|
| 555 |
+
self.fp.seek(pos)
|
| 556 |
+
self.fp.seek(pos0 + var._vsize)
|
| 557 |
+
|
| 558 |
+
def _write_var_padding(self, var, size):
|
| 559 |
+
encoded_fill_value = var._get_encoded_fill_value()
|
| 560 |
+
num_fills = size // len(encoded_fill_value)
|
| 561 |
+
self.fp.write(encoded_fill_value * num_fills)
|
| 562 |
+
|
| 563 |
+
def _write_att_values(self, values):
|
| 564 |
+
if hasattr(values, 'dtype'):
|
| 565 |
+
nc_type = REVERSE[values.dtype.char, values.dtype.itemsize]
|
| 566 |
+
else:
|
| 567 |
+
types = [(int, NC_INT), (float, NC_FLOAT), (str, NC_CHAR)]
|
| 568 |
+
|
| 569 |
+
# bytes index into scalars in py3k. Check for "string" types
|
| 570 |
+
if isinstance(values, str | bytes):
|
| 571 |
+
sample = values
|
| 572 |
+
else:
|
| 573 |
+
try:
|
| 574 |
+
sample = values[0] # subscriptable?
|
| 575 |
+
except TypeError:
|
| 576 |
+
sample = values # scalar
|
| 577 |
+
|
| 578 |
+
for class_, nc_type in types:
|
| 579 |
+
if isinstance(sample, class_):
|
| 580 |
+
break
|
| 581 |
+
|
| 582 |
+
typecode, size = TYPEMAP[nc_type]
|
| 583 |
+
dtype_ = f'>{typecode}'
|
| 584 |
+
# asarray() dies with bytes and '>c' in py3k. Change to 'S'
|
| 585 |
+
dtype_ = 'S' if dtype_ == '>c' else dtype_
|
| 586 |
+
|
| 587 |
+
values = asarray(values, dtype=dtype_)
|
| 588 |
+
|
| 589 |
+
self.fp.write(nc_type)
|
| 590 |
+
|
| 591 |
+
if values.dtype.char == 'S':
|
| 592 |
+
nelems = values.itemsize
|
| 593 |
+
else:
|
| 594 |
+
nelems = values.size
|
| 595 |
+
self._pack_int(nelems)
|
| 596 |
+
|
| 597 |
+
if not values.shape and (values.dtype.byteorder == '<' or
|
| 598 |
+
(values.dtype.byteorder == '=' and LITTLE_ENDIAN)):
|
| 599 |
+
values = values.byteswap()
|
| 600 |
+
self.fp.write(values.tobytes())
|
| 601 |
+
count = values.size * values.itemsize
|
| 602 |
+
self.fp.write(b'\x00' * (-count % 4)) # pad
|
| 603 |
+
|
| 604 |
+
def _read(self):
|
| 605 |
+
# Check magic bytes and version
|
| 606 |
+
magic = self.fp.read(3)
|
| 607 |
+
if not magic == b'CDF':
|
| 608 |
+
raise TypeError(f"Error: {self.filename} is not a valid NetCDF 3 file")
|
| 609 |
+
self.__dict__['version_byte'] = frombuffer(self.fp.read(1), '>b')[0]
|
| 610 |
+
|
| 611 |
+
# Read file headers and set data.
|
| 612 |
+
self._read_numrecs()
|
| 613 |
+
self._read_dim_array()
|
| 614 |
+
self._read_gatt_array()
|
| 615 |
+
self._read_var_array()
|
| 616 |
+
|
| 617 |
+
def _read_numrecs(self):
|
| 618 |
+
self.__dict__['_recs'] = self._unpack_int()
|
| 619 |
+
|
| 620 |
+
def _read_dim_array(self):
|
| 621 |
+
header = self.fp.read(4)
|
| 622 |
+
if header not in [ZERO, NC_DIMENSION]:
|
| 623 |
+
raise ValueError("Unexpected header.")
|
| 624 |
+
count = self._unpack_int()
|
| 625 |
+
|
| 626 |
+
for dim in range(count):
|
| 627 |
+
name = self._unpack_string().decode('latin1')
|
| 628 |
+
length = self._unpack_int() or None # None for record dimension
|
| 629 |
+
self.dimensions[name] = length
|
| 630 |
+
self._dims.append(name) # preserve order
|
| 631 |
+
|
| 632 |
+
def _read_gatt_array(self):
|
| 633 |
+
for k, v in self._read_att_array().items():
|
| 634 |
+
self.__setattr__(k, v)
|
| 635 |
+
|
| 636 |
+
def _read_att_array(self):
|
| 637 |
+
header = self.fp.read(4)
|
| 638 |
+
if header not in [ZERO, NC_ATTRIBUTE]:
|
| 639 |
+
raise ValueError("Unexpected header.")
|
| 640 |
+
count = self._unpack_int()
|
| 641 |
+
|
| 642 |
+
attributes = {}
|
| 643 |
+
for attr in range(count):
|
| 644 |
+
name = self._unpack_string().decode('latin1')
|
| 645 |
+
attributes[name] = self._read_att_values()
|
| 646 |
+
return attributes
|
| 647 |
+
|
| 648 |
+
def _read_var_array(self):
|
| 649 |
+
header = self.fp.read(4)
|
| 650 |
+
if header not in [ZERO, NC_VARIABLE]:
|
| 651 |
+
raise ValueError("Unexpected header.")
|
| 652 |
+
|
| 653 |
+
begin = 0
|
| 654 |
+
dtypes = {'names': [], 'formats': []}
|
| 655 |
+
rec_vars = []
|
| 656 |
+
count = self._unpack_int()
|
| 657 |
+
for var in range(count):
|
| 658 |
+
(name, dimensions, shape, attributes,
|
| 659 |
+
typecode, size, dtype_, begin_, vsize) = self._read_var()
|
| 660 |
+
# https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
|
| 661 |
+
# Note that vsize is the product of the dimension lengths
|
| 662 |
+
# (omitting the record dimension) and the number of bytes
|
| 663 |
+
# per value (determined from the type), increased to the
|
| 664 |
+
# next multiple of 4, for each variable. If a record
|
| 665 |
+
# variable, this is the amount of space per record. The
|
| 666 |
+
# netCDF "record size" is calculated as the sum of the
|
| 667 |
+
# vsize's of all the record variables.
|
| 668 |
+
#
|
| 669 |
+
# The vsize field is actually redundant, because its value
|
| 670 |
+
# may be computed from other information in the header. The
|
| 671 |
+
# 32-bit vsize field is not large enough to contain the size
|
| 672 |
+
# of variables that require more than 2^32 - 4 bytes, so
|
| 673 |
+
# 2^32 - 1 is used in the vsize field for such variables.
|
| 674 |
+
if shape and shape[0] is None: # record variable
|
| 675 |
+
rec_vars.append(name)
|
| 676 |
+
# The netCDF "record size" is calculated as the sum of
|
| 677 |
+
# the vsize's of all the record variables.
|
| 678 |
+
self.__dict__['_recsize'] += vsize
|
| 679 |
+
if begin == 0:
|
| 680 |
+
begin = begin_
|
| 681 |
+
dtypes['names'].append(name)
|
| 682 |
+
dtypes['formats'].append(str(shape[1:]) + dtype_)
|
| 683 |
+
|
| 684 |
+
# Handle padding with a virtual variable.
|
| 685 |
+
if typecode in 'bch':
|
| 686 |
+
actual_size = reduce(mul, (1,) + shape[1:]) * size
|
| 687 |
+
padding = -actual_size % 4
|
| 688 |
+
if padding:
|
| 689 |
+
dtypes['names'].append(f'_padding_{var}')
|
| 690 |
+
dtypes['formats'].append(f'({padding},)>b')
|
| 691 |
+
|
| 692 |
+
# Data will be set later.
|
| 693 |
+
data = None
|
| 694 |
+
else: # not a record variable
|
| 695 |
+
# Calculate size to avoid problems with vsize (above)
|
| 696 |
+
a_size = reduce(mul, shape, 1) * size
|
| 697 |
+
if self.use_mmap:
|
| 698 |
+
data = self._mm_buf[begin_:begin_+a_size].view(dtype=dtype_)
|
| 699 |
+
data = data.reshape(shape)
|
| 700 |
+
else:
|
| 701 |
+
pos = self.fp.tell()
|
| 702 |
+
self.fp.seek(begin_)
|
| 703 |
+
data = frombuffer(self.fp.read(a_size), dtype=dtype_
|
| 704 |
+
).copy()
|
| 705 |
+
data = data.reshape(shape)
|
| 706 |
+
self.fp.seek(pos)
|
| 707 |
+
|
| 708 |
+
# Add variable.
|
| 709 |
+
self.variables[name] = netcdf_variable(
|
| 710 |
+
data, typecode, size, shape, dimensions, attributes,
|
| 711 |
+
maskandscale=self.maskandscale)
|
| 712 |
+
|
| 713 |
+
if rec_vars:
|
| 714 |
+
# Remove padding when only one record variable.
|
| 715 |
+
if len(rec_vars) == 1:
|
| 716 |
+
dtypes['names'] = dtypes['names'][:1]
|
| 717 |
+
dtypes['formats'] = dtypes['formats'][:1]
|
| 718 |
+
|
| 719 |
+
# Build rec array.
|
| 720 |
+
if self.use_mmap:
|
| 721 |
+
buf = self._mm_buf[begin:begin+self._recs*self._recsize]
|
| 722 |
+
rec_array = buf.view(dtype=dtypes)
|
| 723 |
+
rec_array = rec_array.reshape((self._recs,))
|
| 724 |
+
else:
|
| 725 |
+
pos = self.fp.tell()
|
| 726 |
+
self.fp.seek(begin)
|
| 727 |
+
rec_array = frombuffer(self.fp.read(self._recs*self._recsize),
|
| 728 |
+
dtype=dtypes).copy()
|
| 729 |
+
rec_array = rec_array.reshape((self._recs,))
|
| 730 |
+
self.fp.seek(pos)
|
| 731 |
+
|
| 732 |
+
for var in rec_vars:
|
| 733 |
+
self.variables[var].__dict__['data'] = rec_array[var]
|
| 734 |
+
|
| 735 |
+
def _read_var(self):
|
| 736 |
+
name = self._unpack_string().decode('latin1')
|
| 737 |
+
dimensions = []
|
| 738 |
+
shape = []
|
| 739 |
+
dims = self._unpack_int()
|
| 740 |
+
|
| 741 |
+
for i in range(dims):
|
| 742 |
+
dimid = self._unpack_int()
|
| 743 |
+
dimname = self._dims[dimid]
|
| 744 |
+
dimensions.append(dimname)
|
| 745 |
+
dim = self.dimensions[dimname]
|
| 746 |
+
shape.append(dim)
|
| 747 |
+
dimensions = tuple(dimensions)
|
| 748 |
+
shape = tuple(shape)
|
| 749 |
+
|
| 750 |
+
attributes = self._read_att_array()
|
| 751 |
+
nc_type = self.fp.read(4)
|
| 752 |
+
vsize = self._unpack_int()
|
| 753 |
+
begin = [self._unpack_int, self._unpack_int64][self.version_byte-1]()
|
| 754 |
+
|
| 755 |
+
typecode, size = TYPEMAP[nc_type]
|
| 756 |
+
dtype_ = f'>{typecode}'
|
| 757 |
+
|
| 758 |
+
return name, dimensions, shape, attributes, typecode, size, dtype_, begin, vsize
|
| 759 |
+
|
| 760 |
+
def _read_att_values(self):
|
| 761 |
+
nc_type = self.fp.read(4)
|
| 762 |
+
n = self._unpack_int()
|
| 763 |
+
|
| 764 |
+
typecode, size = TYPEMAP[nc_type]
|
| 765 |
+
|
| 766 |
+
count = n*size
|
| 767 |
+
values = self.fp.read(int(count))
|
| 768 |
+
self.fp.read(-count % 4) # read padding
|
| 769 |
+
|
| 770 |
+
if typecode != 'c':
|
| 771 |
+
values = frombuffer(values, dtype=f'>{typecode}').copy()
|
| 772 |
+
if values.shape == (1,):
|
| 773 |
+
values = values[0]
|
| 774 |
+
else:
|
| 775 |
+
values = values.rstrip(b'\x00')
|
| 776 |
+
return values
|
| 777 |
+
|
| 778 |
+
def _pack_begin(self, begin):
|
| 779 |
+
if self.version_byte == 1:
|
| 780 |
+
self._pack_int(begin)
|
| 781 |
+
elif self.version_byte == 2:
|
| 782 |
+
self._pack_int64(begin)
|
| 783 |
+
|
| 784 |
+
def _pack_int(self, value):
|
| 785 |
+
self.fp.write(array(value, '>i').tobytes())
|
| 786 |
+
_pack_int32 = _pack_int
|
| 787 |
+
|
| 788 |
+
def _unpack_int(self):
|
| 789 |
+
return int(frombuffer(self.fp.read(4), '>i')[0])
|
| 790 |
+
_unpack_int32 = _unpack_int
|
| 791 |
+
|
| 792 |
+
def _pack_int64(self, value):
|
| 793 |
+
self.fp.write(array(value, '>q').tobytes())
|
| 794 |
+
|
| 795 |
+
def _unpack_int64(self):
|
| 796 |
+
return frombuffer(self.fp.read(8), '>q')[0]
|
| 797 |
+
|
| 798 |
+
def _pack_string(self, s):
|
| 799 |
+
count = len(s)
|
| 800 |
+
self._pack_int(count)
|
| 801 |
+
self.fp.write(s.encode('latin1'))
|
| 802 |
+
self.fp.write(b'\x00' * (-count % 4)) # pad
|
| 803 |
+
|
| 804 |
+
def _unpack_string(self):
|
| 805 |
+
count = self._unpack_int()
|
| 806 |
+
s = self.fp.read(count).rstrip(b'\x00')
|
| 807 |
+
self.fp.read(-count % 4) # read padding
|
| 808 |
+
return s
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
class netcdf_variable:
|
| 812 |
+
"""
|
| 813 |
+
A data object for netcdf files.
|
| 814 |
+
|
| 815 |
+
`netcdf_variable` objects are constructed by calling the method
|
| 816 |
+
`netcdf_file.createVariable` on the `netcdf_file` object. `netcdf_variable`
|
| 817 |
+
objects behave much like array objects defined in numpy, except that their
|
| 818 |
+
data resides in a file. Data is read by indexing and written by assigning
|
| 819 |
+
to an indexed subset; the entire array can be accessed by the index ``[:]``
|
| 820 |
+
or (for scalars) by using the methods `getValue` and `assignValue`.
|
| 821 |
+
`netcdf_variable` objects also have attribute `shape` with the same meaning
|
| 822 |
+
as for arrays, but the shape cannot be modified. There is another read-only
|
| 823 |
+
attribute `dimensions`, whose value is the tuple of dimension names.
|
| 824 |
+
|
| 825 |
+
All other attributes correspond to variable attributes defined in
|
| 826 |
+
the NetCDF file. Variable attributes are created by assigning to an
|
| 827 |
+
attribute of the `netcdf_variable` object.
|
| 828 |
+
|
| 829 |
+
Parameters
|
| 830 |
+
----------
|
| 831 |
+
data : array_like
|
| 832 |
+
The data array that holds the values for the variable.
|
| 833 |
+
Typically, this is initialized as empty, but with the proper shape.
|
| 834 |
+
typecode : dtype character code
|
| 835 |
+
Desired data-type for the data array.
|
| 836 |
+
size : int
|
| 837 |
+
Desired element size for the data array.
|
| 838 |
+
shape : sequence of ints
|
| 839 |
+
The shape of the array. This should match the lengths of the
|
| 840 |
+
variable's dimensions.
|
| 841 |
+
dimensions : sequence of strings
|
| 842 |
+
The names of the dimensions used by the variable. Must be in the
|
| 843 |
+
same order of the dimension lengths given by `shape`.
|
| 844 |
+
attributes : dict, optional
|
| 845 |
+
Attribute values (any type) keyed by string names. These attributes
|
| 846 |
+
become attributes for the netcdf_variable object.
|
| 847 |
+
maskandscale : bool, optional
|
| 848 |
+
Whether to automatically scale and/or mask data based on attributes.
|
| 849 |
+
Default is False.
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
Attributes
|
| 853 |
+
----------
|
| 854 |
+
dimensions : list of str
|
| 855 |
+
List of names of dimensions used by the variable object.
|
| 856 |
+
isrec, shape
|
| 857 |
+
Properties
|
| 858 |
+
|
| 859 |
+
See also
|
| 860 |
+
--------
|
| 861 |
+
isrec, shape
|
| 862 |
+
|
| 863 |
+
Notes
|
| 864 |
+
-----
|
| 865 |
+
For a more recent version of the NetCDF standard and additional features, please
|
| 866 |
+
consider the permissively-licensed
|
| 867 |
+
`netcdf4-python <https://unidata.github.io/netcdf4-python/>`_.
|
| 868 |
+
|
| 869 |
+
"""
|
| 870 |
+
def __init__(self, data, typecode, size, shape, dimensions,
|
| 871 |
+
attributes=None,
|
| 872 |
+
maskandscale=False):
|
| 873 |
+
self.data = data
|
| 874 |
+
self._typecode = typecode
|
| 875 |
+
self._size = size
|
| 876 |
+
self._shape = shape
|
| 877 |
+
self.dimensions = dimensions
|
| 878 |
+
self.maskandscale = maskandscale
|
| 879 |
+
|
| 880 |
+
self._attributes = attributes or {}
|
| 881 |
+
for k, v in self._attributes.items():
|
| 882 |
+
self.__dict__[k] = v
|
| 883 |
+
|
| 884 |
+
def __setattr__(self, attr, value):
|
| 885 |
+
# Store user defined attributes in a separate dict,
|
| 886 |
+
# so we can save them to file later.
|
| 887 |
+
try:
|
| 888 |
+
self._attributes[attr] = value
|
| 889 |
+
except AttributeError:
|
| 890 |
+
pass
|
| 891 |
+
self.__dict__[attr] = value
|
| 892 |
+
|
| 893 |
+
def isrec(self):
|
| 894 |
+
"""Returns whether the variable has a record dimension or not.
|
| 895 |
+
|
| 896 |
+
A record dimension is a dimension along which additional data could be
|
| 897 |
+
easily appended in the netcdf data structure without much rewriting of
|
| 898 |
+
the data file. This attribute is a read-only property of the
|
| 899 |
+
`netcdf_variable`.
|
| 900 |
+
|
| 901 |
+
"""
|
| 902 |
+
return bool(self.data.shape) and not self._shape[0]
|
| 903 |
+
isrec = property(isrec)
|
| 904 |
+
|
| 905 |
+
def shape(self):
|
| 906 |
+
"""Returns the shape tuple of the data variable.
|
| 907 |
+
|
| 908 |
+
This is a read-only attribute and can not be modified in the
|
| 909 |
+
same manner of other numpy arrays.
|
| 910 |
+
"""
|
| 911 |
+
return self.data.shape
|
| 912 |
+
shape = property(shape)
|
| 913 |
+
|
| 914 |
+
def getValue(self):
|
| 915 |
+
"""
|
| 916 |
+
Retrieve a scalar value from a `netcdf_variable` of length one.
|
| 917 |
+
|
| 918 |
+
Raises
|
| 919 |
+
------
|
| 920 |
+
ValueError
|
| 921 |
+
If the netcdf variable is an array of length greater than one,
|
| 922 |
+
this exception will be raised.
|
| 923 |
+
|
| 924 |
+
"""
|
| 925 |
+
return self.data.item()
|
| 926 |
+
|
| 927 |
+
def assignValue(self, value):
|
| 928 |
+
"""
|
| 929 |
+
Assign a scalar value to a `netcdf_variable` of length one.
|
| 930 |
+
|
| 931 |
+
Parameters
|
| 932 |
+
----------
|
| 933 |
+
value : scalar
|
| 934 |
+
Scalar value (of compatible type) to assign to a length-one netcdf
|
| 935 |
+
variable. This value will be written to file.
|
| 936 |
+
|
| 937 |
+
Raises
|
| 938 |
+
------
|
| 939 |
+
ValueError
|
| 940 |
+
If the input is not a scalar, or if the destination is not a length-one
|
| 941 |
+
netcdf variable.
|
| 942 |
+
|
| 943 |
+
"""
|
| 944 |
+
if not self.data.flags.writeable:
|
| 945 |
+
# Work-around for a bug in NumPy. Calling itemset() on a read-only
|
| 946 |
+
# memory-mapped array causes a seg. fault.
|
| 947 |
+
# See NumPy ticket #1622, and SciPy ticket #1202.
|
| 948 |
+
# This check for `writeable` can be removed when the oldest version
|
| 949 |
+
# of NumPy still supported by scipy contains the fix for #1622.
|
| 950 |
+
raise RuntimeError("variable is not writeable")
|
| 951 |
+
|
| 952 |
+
self.data[:] = value
|
| 953 |
+
|
| 954 |
+
def typecode(self):
|
| 955 |
+
"""
|
| 956 |
+
Return the typecode of the variable.
|
| 957 |
+
|
| 958 |
+
Returns
|
| 959 |
+
-------
|
| 960 |
+
typecode : char
|
| 961 |
+
The character typecode of the variable (e.g., 'i' for int).
|
| 962 |
+
|
| 963 |
+
"""
|
| 964 |
+
return self._typecode
|
| 965 |
+
|
| 966 |
+
def itemsize(self):
|
| 967 |
+
"""
|
| 968 |
+
Return the itemsize of the variable.
|
| 969 |
+
|
| 970 |
+
Returns
|
| 971 |
+
-------
|
| 972 |
+
itemsize : int
|
| 973 |
+
The element size of the variable (e.g., 8 for float64).
|
| 974 |
+
|
| 975 |
+
"""
|
| 976 |
+
return self._size
|
| 977 |
+
|
| 978 |
+
def __getitem__(self, index):
|
| 979 |
+
if not self.maskandscale:
|
| 980 |
+
return self.data[index]
|
| 981 |
+
|
| 982 |
+
data = self.data[index].copy()
|
| 983 |
+
missing_value = self._get_missing_value()
|
| 984 |
+
data = self._apply_missing_value(data, missing_value)
|
| 985 |
+
scale_factor = self._attributes.get('scale_factor')
|
| 986 |
+
add_offset = self._attributes.get('add_offset')
|
| 987 |
+
if add_offset is not None or scale_factor is not None:
|
| 988 |
+
data = data.astype(np.float64)
|
| 989 |
+
if scale_factor is not None:
|
| 990 |
+
data = data * scale_factor
|
| 991 |
+
if add_offset is not None:
|
| 992 |
+
data += add_offset
|
| 993 |
+
|
| 994 |
+
return data
|
| 995 |
+
|
| 996 |
+
def __setitem__(self, index, data):
|
| 997 |
+
if self.maskandscale:
|
| 998 |
+
missing_value = (
|
| 999 |
+
self._get_missing_value() or
|
| 1000 |
+
getattr(data, 'fill_value', 999999))
|
| 1001 |
+
self._attributes.setdefault('missing_value', missing_value)
|
| 1002 |
+
self._attributes.setdefault('_FillValue', missing_value)
|
| 1003 |
+
data = ((data - self._attributes.get('add_offset', 0.0)) /
|
| 1004 |
+
self._attributes.get('scale_factor', 1.0))
|
| 1005 |
+
data = np.ma.asarray(data).filled(missing_value)
|
| 1006 |
+
if self._typecode not in 'fd' and data.dtype.kind == 'f':
|
| 1007 |
+
data = np.round(data)
|
| 1008 |
+
|
| 1009 |
+
# Expand data for record vars?
|
| 1010 |
+
if self.isrec:
|
| 1011 |
+
if isinstance(index, tuple):
|
| 1012 |
+
rec_index = index[0]
|
| 1013 |
+
else:
|
| 1014 |
+
rec_index = index
|
| 1015 |
+
if isinstance(rec_index, slice):
|
| 1016 |
+
recs = (rec_index.start or 0) + len(data)
|
| 1017 |
+
else:
|
| 1018 |
+
recs = rec_index + 1
|
| 1019 |
+
if recs > len(self.data):
|
| 1020 |
+
shape = (recs,) + self._shape[1:]
|
| 1021 |
+
# Resize in-place does not always work since
|
| 1022 |
+
# the array might not be single-segment
|
| 1023 |
+
try:
|
| 1024 |
+
self.data.resize(shape)
|
| 1025 |
+
except ValueError:
|
| 1026 |
+
dtype = self.data.dtype
|
| 1027 |
+
self.__dict__['data'] = np.resize(self.data, shape).astype(dtype)
|
| 1028 |
+
self.data[index] = data
|
| 1029 |
+
|
| 1030 |
+
def _default_encoded_fill_value(self):
|
| 1031 |
+
"""
|
| 1032 |
+
The default encoded fill-value for this Variable's data type.
|
| 1033 |
+
"""
|
| 1034 |
+
nc_type = REVERSE[self.typecode(), self.itemsize()]
|
| 1035 |
+
return FILLMAP[nc_type]
|
| 1036 |
+
|
| 1037 |
+
def _get_encoded_fill_value(self):
|
| 1038 |
+
"""
|
| 1039 |
+
Returns the encoded fill value for this variable as bytes.
|
| 1040 |
+
|
| 1041 |
+
This is taken from either the _FillValue attribute, or the default fill
|
| 1042 |
+
value for this variable's data type.
|
| 1043 |
+
"""
|
| 1044 |
+
if '_FillValue' in self._attributes:
|
| 1045 |
+
fill_value = np.array(self._attributes['_FillValue'],
|
| 1046 |
+
dtype=self.data.dtype).tobytes()
|
| 1047 |
+
if len(fill_value) == self.itemsize():
|
| 1048 |
+
return fill_value
|
| 1049 |
+
else:
|
| 1050 |
+
return self._default_encoded_fill_value()
|
| 1051 |
+
else:
|
| 1052 |
+
return self._default_encoded_fill_value()
|
| 1053 |
+
|
| 1054 |
+
def _get_missing_value(self):
|
| 1055 |
+
"""
|
| 1056 |
+
Returns the value denoting "no data" for this variable.
|
| 1057 |
+
|
| 1058 |
+
If this variable does not have a missing/fill value, returns None.
|
| 1059 |
+
|
| 1060 |
+
If both _FillValue and missing_value are given, give precedence to
|
| 1061 |
+
_FillValue. The netCDF standard gives special meaning to _FillValue;
|
| 1062 |
+
missing_value is just used for compatibility with old datasets.
|
| 1063 |
+
"""
|
| 1064 |
+
|
| 1065 |
+
if '_FillValue' in self._attributes:
|
| 1066 |
+
missing_value = self._attributes['_FillValue']
|
| 1067 |
+
elif 'missing_value' in self._attributes:
|
| 1068 |
+
missing_value = self._attributes['missing_value']
|
| 1069 |
+
else:
|
| 1070 |
+
missing_value = None
|
| 1071 |
+
|
| 1072 |
+
return missing_value
|
| 1073 |
+
|
| 1074 |
+
@staticmethod
|
| 1075 |
+
def _apply_missing_value(data, missing_value):
|
| 1076 |
+
"""
|
| 1077 |
+
Applies the given missing value to the data array.
|
| 1078 |
+
|
| 1079 |
+
Returns a numpy.ma array, with any value equal to missing_value masked
|
| 1080 |
+
out (unless missing_value is None, in which case the original array is
|
| 1081 |
+
returned).
|
| 1082 |
+
"""
|
| 1083 |
+
|
| 1084 |
+
if missing_value is None:
|
| 1085 |
+
newdata = data
|
| 1086 |
+
else:
|
| 1087 |
+
try:
|
| 1088 |
+
missing_value_isnan = np.isnan(missing_value)
|
| 1089 |
+
except (TypeError, NotImplementedError):
|
| 1090 |
+
# some data types (e.g., characters) cannot be tested for NaN
|
| 1091 |
+
missing_value_isnan = False
|
| 1092 |
+
|
| 1093 |
+
if missing_value_isnan:
|
| 1094 |
+
mymask = np.isnan(data)
|
| 1095 |
+
else:
|
| 1096 |
+
mymask = (data == missing_value)
|
| 1097 |
+
|
| 1098 |
+
newdata = np.ma.masked_where(mymask, data)
|
| 1099 |
+
|
| 1100 |
+
return newdata
|
| 1101 |
+
|
| 1102 |
+
|
| 1103 |
+
NetCDFFile = netcdf_file
|
| 1104 |
+
NetCDFVariable = netcdf_variable
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/harwell_boeing.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.io` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["hb_read", "hb_write"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="harwell_boeing",
|
| 16 |
+
private_modules=["_harwell_boeing"], all=__all__,
|
| 17 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/idl.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.io` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["readsav"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="idl",
|
| 16 |
+
private_modules=["_idl"], all=__all__,
|
| 17 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/mmio.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.io` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["mminfo", "mmread", "mmwrite"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="mmio",
|
| 16 |
+
private_modules=["_mmio"], all=__all__,
|
| 17 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/netcdf.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.io` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["netcdf_file", "netcdf_variable"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="netcdf",
|
| 16 |
+
private_modules=["_netcdf"], all=__all__,
|
| 17 |
+
attribute=name)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/io/wavfile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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module to read / write wav files using NumPy arrays
|
| 3 |
+
|
| 4 |
+
Functions
|
| 5 |
+
---------
|
| 6 |
+
`read`: Return the sample rate (in samples/sec) and data from a WAV file.
|
| 7 |
+
|
| 8 |
+
`write`: Write a NumPy array as a WAV file.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
import io
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import numpy as np
|
| 15 |
+
import struct
|
| 16 |
+
import warnings
|
| 17 |
+
from enum import IntEnum
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
'WavFileWarning',
|
| 22 |
+
'read',
|
| 23 |
+
'write'
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class WavFileWarning(UserWarning):
|
| 28 |
+
"""
|
| 29 |
+
Warning for WAV files with format issues that can still be read.
|
| 30 |
+
|
| 31 |
+
Raised when a WAV file has problems like missing metadata or
|
| 32 |
+
non-standard formatting, but can still be processed successfully.
|
| 33 |
+
"""
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SeekEmulatingReader:
|
| 38 |
+
"""
|
| 39 |
+
Tracks stream position, provides tell(), and emulates only those
|
| 40 |
+
seeks that can be supported by reading forward. Other seeks raise
|
| 41 |
+
io.UnsupportedOperation. Note that this class implements only the
|
| 42 |
+
minimum necessary to keep wavfile.read() happy.
|
| 43 |
+
"""
|
| 44 |
+
def __init__(self, reader):
|
| 45 |
+
self.reader = reader
|
| 46 |
+
self.pos = 0
|
| 47 |
+
|
| 48 |
+
def read(self, size=-1, /):
|
| 49 |
+
data = self.reader.read(size)
|
| 50 |
+
self.pos += len(data)
|
| 51 |
+
return data
|
| 52 |
+
|
| 53 |
+
def seek(self, offset, whence=os.SEEK_SET, /):
|
| 54 |
+
match whence:
|
| 55 |
+
case os.SEEK_SET if offset >= self.pos:
|
| 56 |
+
self.read(offset - self.pos) # convert to relative
|
| 57 |
+
case os.SEEK_CUR if offset >= 0:
|
| 58 |
+
self.read(offset) # advance by offset
|
| 59 |
+
case os.SEEK_END if offset == 0:
|
| 60 |
+
self.read() # advance to end of stream
|
| 61 |
+
case _:
|
| 62 |
+
raise io.UnsupportedOperation("SeekEmulatingReader was asked to emulate"
|
| 63 |
+
" a seek operation it does not support.")
|
| 64 |
+
return self.pos
|
| 65 |
+
|
| 66 |
+
def tell(self):
|
| 67 |
+
return self.pos
|
| 68 |
+
|
| 69 |
+
def close(self):
|
| 70 |
+
self.reader.close()
|
| 71 |
+
|
| 72 |
+
# np.fromfile expects to be able to call flush(), and _read_data_chunk
|
| 73 |
+
# expects to catch io.UnsupportedOperation if np.fromfile fails.
|
| 74 |
+
def flush(self):
|
| 75 |
+
raise io.UnsupportedOperation("SeekEmulatingReader can't flush.")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class WAVE_FORMAT(IntEnum):
|
| 79 |
+
"""
|
| 80 |
+
WAVE form wFormatTag IDs
|
| 81 |
+
|
| 82 |
+
Complete list is in mmreg.h in Windows 10 SDK. ALAC and OPUS are the
|
| 83 |
+
newest additions, in v10.0.14393 2016-07
|
| 84 |
+
"""
|
| 85 |
+
UNKNOWN = 0x0000
|
| 86 |
+
PCM = 0x0001
|
| 87 |
+
ADPCM = 0x0002
|
| 88 |
+
IEEE_FLOAT = 0x0003
|
| 89 |
+
VSELP = 0x0004
|
| 90 |
+
IBM_CVSD = 0x0005
|
| 91 |
+
ALAW = 0x0006
|
| 92 |
+
MULAW = 0x0007
|
| 93 |
+
DTS = 0x0008
|
| 94 |
+
DRM = 0x0009
|
| 95 |
+
WMAVOICE9 = 0x000A
|
| 96 |
+
WMAVOICE10 = 0x000B
|
| 97 |
+
OKI_ADPCM = 0x0010
|
| 98 |
+
DVI_ADPCM = 0x0011
|
| 99 |
+
IMA_ADPCM = 0x0011 # Duplicate
|
| 100 |
+
MEDIASPACE_ADPCM = 0x0012
|
| 101 |
+
SIERRA_ADPCM = 0x0013
|
| 102 |
+
G723_ADPCM = 0x0014
|
| 103 |
+
DIGISTD = 0x0015
|
| 104 |
+
DIGIFIX = 0x0016
|
| 105 |
+
DIALOGIC_OKI_ADPCM = 0x0017
|
| 106 |
+
MEDIAVISION_ADPCM = 0x0018
|
| 107 |
+
CU_CODEC = 0x0019
|
| 108 |
+
HP_DYN_VOICE = 0x001A
|
| 109 |
+
YAMAHA_ADPCM = 0x0020
|
| 110 |
+
SONARC = 0x0021
|
| 111 |
+
DSPGROUP_TRUESPEECH = 0x0022
|
| 112 |
+
ECHOSC1 = 0x0023
|
| 113 |
+
AUDIOFILE_AF36 = 0x0024
|
| 114 |
+
APTX = 0x0025
|
| 115 |
+
AUDIOFILE_AF10 = 0x0026
|
| 116 |
+
PROSODY_1612 = 0x0027
|
| 117 |
+
LRC = 0x0028
|
| 118 |
+
DOLBY_AC2 = 0x0030
|
| 119 |
+
GSM610 = 0x0031
|
| 120 |
+
MSNAUDIO = 0x0032
|
| 121 |
+
ANTEX_ADPCME = 0x0033
|
| 122 |
+
CONTROL_RES_VQLPC = 0x0034
|
| 123 |
+
DIGIREAL = 0x0035
|
| 124 |
+
DIGIADPCM = 0x0036
|
| 125 |
+
CONTROL_RES_CR10 = 0x0037
|
| 126 |
+
NMS_VBXADPCM = 0x0038
|
| 127 |
+
CS_IMAADPCM = 0x0039
|
| 128 |
+
ECHOSC3 = 0x003A
|
| 129 |
+
ROCKWELL_ADPCM = 0x003B
|
| 130 |
+
ROCKWELL_DIGITALK = 0x003C
|
| 131 |
+
XEBEC = 0x003D
|
| 132 |
+
G721_ADPCM = 0x0040
|
| 133 |
+
G728_CELP = 0x0041
|
| 134 |
+
MSG723 = 0x0042
|
| 135 |
+
INTEL_G723_1 = 0x0043
|
| 136 |
+
INTEL_G729 = 0x0044
|
| 137 |
+
SHARP_G726 = 0x0045
|
| 138 |
+
MPEG = 0x0050
|
| 139 |
+
RT24 = 0x0052
|
| 140 |
+
PAC = 0x0053
|
| 141 |
+
MPEGLAYER3 = 0x0055
|
| 142 |
+
LUCENT_G723 = 0x0059
|
| 143 |
+
CIRRUS = 0x0060
|
| 144 |
+
ESPCM = 0x0061
|
| 145 |
+
VOXWARE = 0x0062
|
| 146 |
+
CANOPUS_ATRAC = 0x0063
|
| 147 |
+
G726_ADPCM = 0x0064
|
| 148 |
+
G722_ADPCM = 0x0065
|
| 149 |
+
DSAT = 0x0066
|
| 150 |
+
DSAT_DISPLAY = 0x0067
|
| 151 |
+
VOXWARE_BYTE_ALIGNED = 0x0069
|
| 152 |
+
VOXWARE_AC8 = 0x0070
|
| 153 |
+
VOXWARE_AC10 = 0x0071
|
| 154 |
+
VOXWARE_AC16 = 0x0072
|
| 155 |
+
VOXWARE_AC20 = 0x0073
|
| 156 |
+
VOXWARE_RT24 = 0x0074
|
| 157 |
+
VOXWARE_RT29 = 0x0075
|
| 158 |
+
VOXWARE_RT29HW = 0x0076
|
| 159 |
+
VOXWARE_VR12 = 0x0077
|
| 160 |
+
VOXWARE_VR18 = 0x0078
|
| 161 |
+
VOXWARE_TQ40 = 0x0079
|
| 162 |
+
VOXWARE_SC3 = 0x007A
|
| 163 |
+
VOXWARE_SC3_1 = 0x007B
|
| 164 |
+
SOFTSOUND = 0x0080
|
| 165 |
+
VOXWARE_TQ60 = 0x0081
|
| 166 |
+
MSRT24 = 0x0082
|
| 167 |
+
G729A = 0x0083
|
| 168 |
+
MVI_MVI2 = 0x0084
|
| 169 |
+
DF_G726 = 0x0085
|
| 170 |
+
DF_GSM610 = 0x0086
|
| 171 |
+
ISIAUDIO = 0x0088
|
| 172 |
+
ONLIVE = 0x0089
|
| 173 |
+
MULTITUDE_FT_SX20 = 0x008A
|
| 174 |
+
INFOCOM_ITS_G721_ADPCM = 0x008B
|
| 175 |
+
CONVEDIA_G729 = 0x008C
|
| 176 |
+
CONGRUENCY = 0x008D
|
| 177 |
+
SBC24 = 0x0091
|
| 178 |
+
DOLBY_AC3_SPDIF = 0x0092
|
| 179 |
+
MEDIASONIC_G723 = 0x0093
|
| 180 |
+
PROSODY_8KBPS = 0x0094
|
| 181 |
+
ZYXEL_ADPCM = 0x0097
|
| 182 |
+
PHILIPS_LPCBB = 0x0098
|
| 183 |
+
PACKED = 0x0099
|
| 184 |
+
MALDEN_PHONYTALK = 0x00A0
|
| 185 |
+
RACAL_RECORDER_GSM = 0x00A1
|
| 186 |
+
RACAL_RECORDER_G720_A = 0x00A2
|
| 187 |
+
RACAL_RECORDER_G723_1 = 0x00A3
|
| 188 |
+
RACAL_RECORDER_TETRA_ACELP = 0x00A4
|
| 189 |
+
NEC_AAC = 0x00B0
|
| 190 |
+
RAW_AAC1 = 0x00FF
|
| 191 |
+
RHETOREX_ADPCM = 0x0100
|
| 192 |
+
IRAT = 0x0101
|
| 193 |
+
VIVO_G723 = 0x0111
|
| 194 |
+
VIVO_SIREN = 0x0112
|
| 195 |
+
PHILIPS_CELP = 0x0120
|
| 196 |
+
PHILIPS_GRUNDIG = 0x0121
|
| 197 |
+
DIGITAL_G723 = 0x0123
|
| 198 |
+
SANYO_LD_ADPCM = 0x0125
|
| 199 |
+
SIPROLAB_ACEPLNET = 0x0130
|
| 200 |
+
SIPROLAB_ACELP4800 = 0x0131
|
| 201 |
+
SIPROLAB_ACELP8V3 = 0x0132
|
| 202 |
+
SIPROLAB_G729 = 0x0133
|
| 203 |
+
SIPROLAB_G729A = 0x0134
|
| 204 |
+
SIPROLAB_KELVIN = 0x0135
|
| 205 |
+
VOICEAGE_AMR = 0x0136
|
| 206 |
+
G726ADPCM = 0x0140
|
| 207 |
+
DICTAPHONE_CELP68 = 0x0141
|
| 208 |
+
DICTAPHONE_CELP54 = 0x0142
|
| 209 |
+
QUALCOMM_PUREVOICE = 0x0150
|
| 210 |
+
QUALCOMM_HALFRATE = 0x0151
|
| 211 |
+
TUBGSM = 0x0155
|
| 212 |
+
MSAUDIO1 = 0x0160
|
| 213 |
+
WMAUDIO2 = 0x0161
|
| 214 |
+
WMAUDIO3 = 0x0162
|
| 215 |
+
WMAUDIO_LOSSLESS = 0x0163
|
| 216 |
+
WMASPDIF = 0x0164
|
| 217 |
+
UNISYS_NAP_ADPCM = 0x0170
|
| 218 |
+
UNISYS_NAP_ULAW = 0x0171
|
| 219 |
+
UNISYS_NAP_ALAW = 0x0172
|
| 220 |
+
UNISYS_NAP_16K = 0x0173
|
| 221 |
+
SYCOM_ACM_SYC008 = 0x0174
|
| 222 |
+
SYCOM_ACM_SYC701_G726L = 0x0175
|
| 223 |
+
SYCOM_ACM_SYC701_CELP54 = 0x0176
|
| 224 |
+
SYCOM_ACM_SYC701_CELP68 = 0x0177
|
| 225 |
+
KNOWLEDGE_ADVENTURE_ADPCM = 0x0178
|
| 226 |
+
FRAUNHOFER_IIS_MPEG2_AAC = 0x0180
|
| 227 |
+
DTS_DS = 0x0190
|
| 228 |
+
CREATIVE_ADPCM = 0x0200
|
| 229 |
+
CREATIVE_FASTSPEECH8 = 0x0202
|
| 230 |
+
CREATIVE_FASTSPEECH10 = 0x0203
|
| 231 |
+
UHER_ADPCM = 0x0210
|
| 232 |
+
ULEAD_DV_AUDIO = 0x0215
|
| 233 |
+
ULEAD_DV_AUDIO_1 = 0x0216
|
| 234 |
+
QUARTERDECK = 0x0220
|
| 235 |
+
ILINK_VC = 0x0230
|
| 236 |
+
RAW_SPORT = 0x0240
|
| 237 |
+
ESST_AC3 = 0x0241
|
| 238 |
+
GENERIC_PASSTHRU = 0x0249
|
| 239 |
+
IPI_HSX = 0x0250
|
| 240 |
+
IPI_RPELP = 0x0251
|
| 241 |
+
CS2 = 0x0260
|
| 242 |
+
SONY_SCX = 0x0270
|
| 243 |
+
SONY_SCY = 0x0271
|
| 244 |
+
SONY_ATRAC3 = 0x0272
|
| 245 |
+
SONY_SPC = 0x0273
|
| 246 |
+
TELUM_AUDIO = 0x0280
|
| 247 |
+
TELUM_IA_AUDIO = 0x0281
|
| 248 |
+
NORCOM_VOICE_SYSTEMS_ADPCM = 0x0285
|
| 249 |
+
FM_TOWNS_SND = 0x0300
|
| 250 |
+
MICRONAS = 0x0350
|
| 251 |
+
MICRONAS_CELP833 = 0x0351
|
| 252 |
+
BTV_DIGITAL = 0x0400
|
| 253 |
+
INTEL_MUSIC_CODER = 0x0401
|
| 254 |
+
INDEO_AUDIO = 0x0402
|
| 255 |
+
QDESIGN_MUSIC = 0x0450
|
| 256 |
+
ON2_VP7_AUDIO = 0x0500
|
| 257 |
+
ON2_VP6_AUDIO = 0x0501
|
| 258 |
+
VME_VMPCM = 0x0680
|
| 259 |
+
TPC = 0x0681
|
| 260 |
+
LIGHTWAVE_LOSSLESS = 0x08AE
|
| 261 |
+
OLIGSM = 0x1000
|
| 262 |
+
OLIADPCM = 0x1001
|
| 263 |
+
OLICELP = 0x1002
|
| 264 |
+
OLISBC = 0x1003
|
| 265 |
+
OLIOPR = 0x1004
|
| 266 |
+
LH_CODEC = 0x1100
|
| 267 |
+
LH_CODEC_CELP = 0x1101
|
| 268 |
+
LH_CODEC_SBC8 = 0x1102
|
| 269 |
+
LH_CODEC_SBC12 = 0x1103
|
| 270 |
+
LH_CODEC_SBC16 = 0x1104
|
| 271 |
+
NORRIS = 0x1400
|
| 272 |
+
ISIAUDIO_2 = 0x1401
|
| 273 |
+
SOUNDSPACE_MUSICOMPRESS = 0x1500
|
| 274 |
+
MPEG_ADTS_AAC = 0x1600
|
| 275 |
+
MPEG_RAW_AAC = 0x1601
|
| 276 |
+
MPEG_LOAS = 0x1602
|
| 277 |
+
NOKIA_MPEG_ADTS_AAC = 0x1608
|
| 278 |
+
NOKIA_MPEG_RAW_AAC = 0x1609
|
| 279 |
+
VODAFONE_MPEG_ADTS_AAC = 0x160A
|
| 280 |
+
VODAFONE_MPEG_RAW_AAC = 0x160B
|
| 281 |
+
MPEG_HEAAC = 0x1610
|
| 282 |
+
VOXWARE_RT24_SPEECH = 0x181C
|
| 283 |
+
SONICFOUNDRY_LOSSLESS = 0x1971
|
| 284 |
+
INNINGS_TELECOM_ADPCM = 0x1979
|
| 285 |
+
LUCENT_SX8300P = 0x1C07
|
| 286 |
+
LUCENT_SX5363S = 0x1C0C
|
| 287 |
+
CUSEEME = 0x1F03
|
| 288 |
+
NTCSOFT_ALF2CM_ACM = 0x1FC4
|
| 289 |
+
DVM = 0x2000
|
| 290 |
+
DTS2 = 0x2001
|
| 291 |
+
MAKEAVIS = 0x3313
|
| 292 |
+
DIVIO_MPEG4_AAC = 0x4143
|
| 293 |
+
NOKIA_ADAPTIVE_MULTIRATE = 0x4201
|
| 294 |
+
DIVIO_G726 = 0x4243
|
| 295 |
+
LEAD_SPEECH = 0x434C
|
| 296 |
+
LEAD_VORBIS = 0x564C
|
| 297 |
+
WAVPACK_AUDIO = 0x5756
|
| 298 |
+
OGG_VORBIS_MODE_1 = 0x674F
|
| 299 |
+
OGG_VORBIS_MODE_2 = 0x6750
|
| 300 |
+
OGG_VORBIS_MODE_3 = 0x6751
|
| 301 |
+
OGG_VORBIS_MODE_1_PLUS = 0x676F
|
| 302 |
+
OGG_VORBIS_MODE_2_PLUS = 0x6770
|
| 303 |
+
OGG_VORBIS_MODE_3_PLUS = 0x6771
|
| 304 |
+
ALAC = 0x6C61
|
| 305 |
+
_3COM_NBX = 0x7000 # Can't have leading digit
|
| 306 |
+
OPUS = 0x704F
|
| 307 |
+
FAAD_AAC = 0x706D
|
| 308 |
+
AMR_NB = 0x7361
|
| 309 |
+
AMR_WB = 0x7362
|
| 310 |
+
AMR_WP = 0x7363
|
| 311 |
+
GSM_AMR_CBR = 0x7A21
|
| 312 |
+
GSM_AMR_VBR_SID = 0x7A22
|
| 313 |
+
COMVERSE_INFOSYS_G723_1 = 0xA100
|
| 314 |
+
COMVERSE_INFOSYS_AVQSBC = 0xA101
|
| 315 |
+
COMVERSE_INFOSYS_SBC = 0xA102
|
| 316 |
+
SYMBOL_G729_A = 0xA103
|
| 317 |
+
VOICEAGE_AMR_WB = 0xA104
|
| 318 |
+
INGENIENT_G726 = 0xA105
|
| 319 |
+
MPEG4_AAC = 0xA106
|
| 320 |
+
ENCORE_G726 = 0xA107
|
| 321 |
+
ZOLL_ASAO = 0xA108
|
| 322 |
+
SPEEX_VOICE = 0xA109
|
| 323 |
+
VIANIX_MASC = 0xA10A
|
| 324 |
+
WM9_SPECTRUM_ANALYZER = 0xA10B
|
| 325 |
+
WMF_SPECTRUM_ANAYZER = 0xA10C
|
| 326 |
+
GSM_610 = 0xA10D
|
| 327 |
+
GSM_620 = 0xA10E
|
| 328 |
+
GSM_660 = 0xA10F
|
| 329 |
+
GSM_690 = 0xA110
|
| 330 |
+
GSM_ADAPTIVE_MULTIRATE_WB = 0xA111
|
| 331 |
+
POLYCOM_G722 = 0xA112
|
| 332 |
+
POLYCOM_G728 = 0xA113
|
| 333 |
+
POLYCOM_G729_A = 0xA114
|
| 334 |
+
POLYCOM_SIREN = 0xA115
|
| 335 |
+
GLOBAL_IP_ILBC = 0xA116
|
| 336 |
+
RADIOTIME_TIME_SHIFT_RADIO = 0xA117
|
| 337 |
+
NICE_ACA = 0xA118
|
| 338 |
+
NICE_ADPCM = 0xA119
|
| 339 |
+
VOCORD_G721 = 0xA11A
|
| 340 |
+
VOCORD_G726 = 0xA11B
|
| 341 |
+
VOCORD_G722_1 = 0xA11C
|
| 342 |
+
VOCORD_G728 = 0xA11D
|
| 343 |
+
VOCORD_G729 = 0xA11E
|
| 344 |
+
VOCORD_G729_A = 0xA11F
|
| 345 |
+
VOCORD_G723_1 = 0xA120
|
| 346 |
+
VOCORD_LBC = 0xA121
|
| 347 |
+
NICE_G728 = 0xA122
|
| 348 |
+
FRACE_TELECOM_G729 = 0xA123
|
| 349 |
+
CODIAN = 0xA124
|
| 350 |
+
FLAC = 0xF1AC
|
| 351 |
+
EXTENSIBLE = 0xFFFE
|
| 352 |
+
DEVELOPMENT = 0xFFFF
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
KNOWN_WAVE_FORMATS = {WAVE_FORMAT.PCM, WAVE_FORMAT.IEEE_FLOAT}
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _raise_bad_format(format_tag):
|
| 359 |
+
try:
|
| 360 |
+
format_name = WAVE_FORMAT(format_tag).name
|
| 361 |
+
except ValueError:
|
| 362 |
+
format_name = f'{format_tag:#06x}'
|
| 363 |
+
raise ValueError(f"Unknown wave file format: {format_name}. Supported "
|
| 364 |
+
"formats: " +
|
| 365 |
+
', '.join(x.name for x in KNOWN_WAVE_FORMATS))
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _read_fmt_chunk(fid, is_big_endian):
|
| 369 |
+
"""
|
| 370 |
+
Returns
|
| 371 |
+
-------
|
| 372 |
+
size : int
|
| 373 |
+
size of format subchunk in bytes (minus 8 for "fmt " and itself)
|
| 374 |
+
format_tag : int
|
| 375 |
+
PCM, float, or compressed format
|
| 376 |
+
channels : int
|
| 377 |
+
number of channels
|
| 378 |
+
fs : int
|
| 379 |
+
sampling frequency in samples per second
|
| 380 |
+
bytes_per_second : int
|
| 381 |
+
overall byte rate for the file
|
| 382 |
+
block_align : int
|
| 383 |
+
bytes per sample, including all channels
|
| 384 |
+
bit_depth : int
|
| 385 |
+
bits per sample
|
| 386 |
+
|
| 387 |
+
Notes
|
| 388 |
+
-----
|
| 389 |
+
Assumes file pointer is immediately after the 'fmt ' id
|
| 390 |
+
"""
|
| 391 |
+
if is_big_endian:
|
| 392 |
+
fmt = '>'
|
| 393 |
+
else:
|
| 394 |
+
fmt = '<'
|
| 395 |
+
|
| 396 |
+
size = struct.unpack(fmt+'I', fid.read(4))[0]
|
| 397 |
+
|
| 398 |
+
if size < 16:
|
| 399 |
+
raise ValueError("Binary structure of wave file is not compliant")
|
| 400 |
+
|
| 401 |
+
res = struct.unpack(fmt+'HHIIHH', fid.read(16))
|
| 402 |
+
bytes_read = 16
|
| 403 |
+
|
| 404 |
+
format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res
|
| 405 |
+
|
| 406 |
+
if format_tag == WAVE_FORMAT.EXTENSIBLE and size >= (16+2):
|
| 407 |
+
ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0]
|
| 408 |
+
bytes_read += 2
|
| 409 |
+
if ext_chunk_size >= 22:
|
| 410 |
+
extensible_chunk_data = fid.read(22)
|
| 411 |
+
bytes_read += 22
|
| 412 |
+
raw_guid = extensible_chunk_data[2+4:2+4+16]
|
| 413 |
+
# GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361)
|
| 414 |
+
# MS GUID byte order: first three groups are native byte order,
|
| 415 |
+
# rest is Big Endian
|
| 416 |
+
if is_big_endian:
|
| 417 |
+
tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71'
|
| 418 |
+
else:
|
| 419 |
+
tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71'
|
| 420 |
+
if raw_guid.endswith(tail):
|
| 421 |
+
format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0]
|
| 422 |
+
else:
|
| 423 |
+
raise ValueError("Binary structure of wave file is not compliant")
|
| 424 |
+
|
| 425 |
+
if format_tag not in KNOWN_WAVE_FORMATS:
|
| 426 |
+
_raise_bad_format(format_tag)
|
| 427 |
+
|
| 428 |
+
# move file pointer to next chunk
|
| 429 |
+
if size > bytes_read:
|
| 430 |
+
fid.read(size - bytes_read)
|
| 431 |
+
|
| 432 |
+
# fmt should always be 16, 18 or 40, but handle it just in case
|
| 433 |
+
_handle_pad_byte(fid, size)
|
| 434 |
+
|
| 435 |
+
if format_tag == WAVE_FORMAT.PCM:
|
| 436 |
+
if bytes_per_second != fs * block_align:
|
| 437 |
+
raise ValueError("WAV header is invalid: nAvgBytesPerSec must"
|
| 438 |
+
" equal product of nSamplesPerSec and"
|
| 439 |
+
" nBlockAlign, but file has nSamplesPerSec ="
|
| 440 |
+
f" {fs}, nBlockAlign = {block_align}, and"
|
| 441 |
+
f" nAvgBytesPerSec = {bytes_per_second}")
|
| 442 |
+
|
| 443 |
+
return (size, format_tag, channels, fs, bytes_per_second, block_align,
|
| 444 |
+
bit_depth)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, is_rf64,
|
| 448 |
+
block_align, mmap=False, rf64_chunk_size=None):
|
| 449 |
+
"""
|
| 450 |
+
Notes
|
| 451 |
+
-----
|
| 452 |
+
Assumes file pointer is immediately after the 'data' id
|
| 453 |
+
|
| 454 |
+
It's possible to not use all available bits in a container, or to store
|
| 455 |
+
samples in a container bigger than necessary, so bytes_per_sample uses
|
| 456 |
+
the actual reported container size (nBlockAlign / nChannels). Real-world
|
| 457 |
+
examples:
|
| 458 |
+
|
| 459 |
+
Adobe Audition's "24-bit packed int (type 1, 20-bit)"
|
| 460 |
+
|
| 461 |
+
nChannels = 2, nBlockAlign = 6, wBitsPerSample = 20
|
| 462 |
+
|
| 463 |
+
http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples/AFsp/M1F1-int12-AFsp.wav
|
| 464 |
+
is:
|
| 465 |
+
|
| 466 |
+
nChannels = 2, nBlockAlign = 4, wBitsPerSample = 12
|
| 467 |
+
|
| 468 |
+
http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
|
| 469 |
+
gives an example of:
|
| 470 |
+
|
| 471 |
+
nChannels = 2, nBlockAlign = 8, wBitsPerSample = 20
|
| 472 |
+
"""
|
| 473 |
+
if is_big_endian:
|
| 474 |
+
fmt = '>'
|
| 475 |
+
else:
|
| 476 |
+
fmt = '<'
|
| 477 |
+
|
| 478 |
+
# Size of the data subchunk in bytes
|
| 479 |
+
if not is_rf64:
|
| 480 |
+
size = struct.unpack(fmt+'I', fid.read(4))[0]
|
| 481 |
+
else:
|
| 482 |
+
# chunk size is stored in global file header for RF64
|
| 483 |
+
size = rf64_chunk_size
|
| 484 |
+
# skip data chunk size as it is 0xFFFFFFF
|
| 485 |
+
fid.read(4)
|
| 486 |
+
|
| 487 |
+
# Number of bytes per sample (sample container size)
|
| 488 |
+
bytes_per_sample = block_align // channels
|
| 489 |
+
n_samples = size // bytes_per_sample
|
| 490 |
+
|
| 491 |
+
if format_tag == WAVE_FORMAT.PCM:
|
| 492 |
+
if 1 <= bit_depth <= 8:
|
| 493 |
+
dtype = 'u1' # WAV of 8-bit integer or less are unsigned
|
| 494 |
+
elif bytes_per_sample in {3, 5, 6, 7}:
|
| 495 |
+
# No compatible dtype. Load as raw bytes for reshaping later.
|
| 496 |
+
dtype = 'V1'
|
| 497 |
+
elif bit_depth <= 64:
|
| 498 |
+
# Remaining bit depths can map directly to signed numpy dtypes
|
| 499 |
+
dtype = f'{fmt}i{bytes_per_sample}'
|
| 500 |
+
else:
|
| 501 |
+
raise ValueError("Unsupported bit depth: the WAV file "
|
| 502 |
+
f"has {bit_depth}-bit integer data.")
|
| 503 |
+
elif format_tag == WAVE_FORMAT.IEEE_FLOAT:
|
| 504 |
+
if bit_depth in {32, 64}:
|
| 505 |
+
dtype = f'{fmt}f{bytes_per_sample}'
|
| 506 |
+
else:
|
| 507 |
+
raise ValueError("Unsupported bit depth: the WAV file "
|
| 508 |
+
f"has {bit_depth}-bit floating-point data.")
|
| 509 |
+
else:
|
| 510 |
+
_raise_bad_format(format_tag)
|
| 511 |
+
|
| 512 |
+
start = fid.tell()
|
| 513 |
+
if not mmap:
|
| 514 |
+
try:
|
| 515 |
+
count = size if dtype == 'V1' else n_samples
|
| 516 |
+
data = np.fromfile(fid, dtype=dtype, count=count)
|
| 517 |
+
except io.UnsupportedOperation: # not a C-like file
|
| 518 |
+
fid.seek(start, 0) # just in case it seeked, though it shouldn't
|
| 519 |
+
data = np.frombuffer(fid.read(size), dtype=dtype)
|
| 520 |
+
|
| 521 |
+
if dtype == 'V1':
|
| 522 |
+
# Rearrange raw bytes into smallest compatible numpy dtype
|
| 523 |
+
dt = f'{fmt}i4' if bytes_per_sample == 3 else f'{fmt}i8'
|
| 524 |
+
a = np.zeros((len(data) // bytes_per_sample, np.dtype(dt).itemsize),
|
| 525 |
+
dtype='V1')
|
| 526 |
+
if is_big_endian:
|
| 527 |
+
a[:, :bytes_per_sample] = data.reshape((-1, bytes_per_sample))
|
| 528 |
+
else:
|
| 529 |
+
a[:, -bytes_per_sample:] = data.reshape((-1, bytes_per_sample))
|
| 530 |
+
data = a.view(dt).reshape(a.shape[:-1])
|
| 531 |
+
else:
|
| 532 |
+
if bytes_per_sample in {1, 2, 4, 8}:
|
| 533 |
+
start = fid.tell()
|
| 534 |
+
data = np.memmap(fid, dtype=dtype, mode='c', offset=start,
|
| 535 |
+
shape=(n_samples,))
|
| 536 |
+
fid.seek(start + size)
|
| 537 |
+
else:
|
| 538 |
+
raise ValueError("mmap=True not compatible with "
|
| 539 |
+
f"{bytes_per_sample}-byte container size.")
|
| 540 |
+
|
| 541 |
+
_handle_pad_byte(fid, size)
|
| 542 |
+
|
| 543 |
+
if channels > 1:
|
| 544 |
+
data = data.reshape(-1, channels)
|
| 545 |
+
return data
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def _skip_unknown_chunk(fid, is_big_endian):
|
| 549 |
+
if is_big_endian:
|
| 550 |
+
fmt = '>I'
|
| 551 |
+
else:
|
| 552 |
+
fmt = '<I'
|
| 553 |
+
|
| 554 |
+
data = fid.read(4)
|
| 555 |
+
# call unpack() and seek() only if we have really read data from file
|
| 556 |
+
# otherwise empty read at the end of the file would trigger
|
| 557 |
+
# unnecessary exception at unpack() call
|
| 558 |
+
# in case data equals somehow to 0, there is no need for seek() anyway
|
| 559 |
+
if data:
|
| 560 |
+
size = struct.unpack(fmt, data)[0]
|
| 561 |
+
fid.seek(size, 1)
|
| 562 |
+
_handle_pad_byte(fid, size)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def _read_riff_chunk(fid):
|
| 566 |
+
str1 = fid.read(4) # File signature
|
| 567 |
+
if str1 == b'RIFF':
|
| 568 |
+
is_rf64 = False
|
| 569 |
+
is_big_endian = False
|
| 570 |
+
fmt = '<I'
|
| 571 |
+
elif str1 == b'RIFX':
|
| 572 |
+
is_rf64 = False
|
| 573 |
+
is_big_endian = True
|
| 574 |
+
fmt = '>I'
|
| 575 |
+
elif str1 == b'RF64':
|
| 576 |
+
is_rf64 = True
|
| 577 |
+
is_big_endian = False
|
| 578 |
+
fmt = '<Q'
|
| 579 |
+
else:
|
| 580 |
+
# There are also .wav files with "FFIR" or "XFIR" signatures?
|
| 581 |
+
raise ValueError(f"File format {repr(str1)} not understood. Only "
|
| 582 |
+
"'RIFF', 'RIFX', and 'RF64' supported.")
|
| 583 |
+
# Size of entire file
|
| 584 |
+
if not is_rf64:
|
| 585 |
+
file_size = struct.unpack(fmt, fid.read(4))[0] + 8
|
| 586 |
+
rf64_chunk_size = None
|
| 587 |
+
str2 = fid.read(4)
|
| 588 |
+
else:
|
| 589 |
+
# Skip 0xFFFFFFFF (-1) bytes
|
| 590 |
+
fid.read(4)
|
| 591 |
+
str2 = fid.read(4)
|
| 592 |
+
str3 = fid.read(4)
|
| 593 |
+
if str3 != b'ds64':
|
| 594 |
+
raise ValueError("Invalid RF64 file: ds64 chunk not found.")
|
| 595 |
+
ds64_size = struct.unpack("<I", fid.read(4))[0]
|
| 596 |
+
file_size = struct.unpack(fmt, fid.read(8))[0] + 8
|
| 597 |
+
rf64_chunk_size = struct.unpack('<Q', fid.read(8))[0]
|
| 598 |
+
# Ignore additional attributes of ds64 chunk like sample count, tables, etc.
|
| 599 |
+
# and just skip to the next chunk
|
| 600 |
+
fid.seek(ds64_size - 16, 1)
|
| 601 |
+
|
| 602 |
+
if str2 != b'WAVE':
|
| 603 |
+
raise ValueError(f"Not a WAV file. RIFF form type is {repr(str2)}.")
|
| 604 |
+
|
| 605 |
+
return file_size, is_big_endian, is_rf64, rf64_chunk_size
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def _handle_pad_byte(fid, size):
|
| 609 |
+
# "If the chunk size is an odd number of bytes, a pad byte with value zero
|
| 610 |
+
# is written after ckData." So we need to seek past this after each chunk.
|
| 611 |
+
if size % 2:
|
| 612 |
+
fid.seek(1, 1)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def read(filename, mmap=False):
|
| 616 |
+
"""
|
| 617 |
+
Open a WAV file.
|
| 618 |
+
|
| 619 |
+
Return the sample rate (in samples/sec) and data from an LPCM WAV file.
|
| 620 |
+
|
| 621 |
+
Parameters
|
| 622 |
+
----------
|
| 623 |
+
filename : string or open file handle
|
| 624 |
+
Input WAV file.
|
| 625 |
+
mmap : bool, optional
|
| 626 |
+
Whether to read data as memory-mapped (default: False). Not compatible
|
| 627 |
+
with some bit depths; see Notes. Only to be used on real files.
|
| 628 |
+
|
| 629 |
+
.. versionadded:: 0.12.0
|
| 630 |
+
|
| 631 |
+
Returns
|
| 632 |
+
-------
|
| 633 |
+
rate : int
|
| 634 |
+
Sample rate of WAV file.
|
| 635 |
+
data : numpy array
|
| 636 |
+
Data read from WAV file. Data-type is determined from the file;
|
| 637 |
+
see Notes. Data is 1-D for 1-channel WAV, or 2-D of shape
|
| 638 |
+
(Nsamples, Nchannels) otherwise. If a file-like input without a
|
| 639 |
+
C-like file descriptor (e.g., :class:`python:io.BytesIO`) is
|
| 640 |
+
passed, this will not be writeable.
|
| 641 |
+
|
| 642 |
+
Notes
|
| 643 |
+
-----
|
| 644 |
+
Common data types: [1]_
|
| 645 |
+
|
| 646 |
+
===================== =========== =========== =============
|
| 647 |
+
WAV format Min Max NumPy dtype
|
| 648 |
+
===================== =========== =========== =============
|
| 649 |
+
32-bit floating-point -1.0 +1.0 float32
|
| 650 |
+
32-bit integer PCM -2147483648 +2147483647 int32
|
| 651 |
+
24-bit integer PCM -2147483648 +2147483392 int32
|
| 652 |
+
16-bit integer PCM -32768 +32767 int16
|
| 653 |
+
8-bit integer PCM 0 255 uint8
|
| 654 |
+
===================== =========== =========== =============
|
| 655 |
+
|
| 656 |
+
WAV files can specify arbitrary bit depth, and this function supports
|
| 657 |
+
reading any integer PCM depth from 1 to 64 bits. Data is returned in the
|
| 658 |
+
smallest compatible numpy int type, in left-justified format. 8-bit and
|
| 659 |
+
lower is unsigned, while 9-bit and higher is signed.
|
| 660 |
+
|
| 661 |
+
For example, 24-bit data will be stored as int32, with the MSB of the
|
| 662 |
+
24-bit data stored at the MSB of the int32, and typically the least
|
| 663 |
+
significant byte is 0x00. (However, if a file actually contains data past
|
| 664 |
+
its specified bit depth, those bits will be read and output, too. [2]_)
|
| 665 |
+
|
| 666 |
+
This bit justification and sign matches WAV's native internal format, which
|
| 667 |
+
allows memory mapping of WAV files that use 1, 2, 4, or 8 bytes per sample
|
| 668 |
+
(so 24-bit files cannot be memory-mapped, but 32-bit can).
|
| 669 |
+
|
| 670 |
+
IEEE float PCM in 32- or 64-bit format is supported, with or without mmap.
|
| 671 |
+
Values exceeding [-1, +1] are not clipped.
|
| 672 |
+
|
| 673 |
+
Non-linear PCM (mu-law, A-law) is not supported.
|
| 674 |
+
|
| 675 |
+
References
|
| 676 |
+
----------
|
| 677 |
+
.. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
|
| 678 |
+
Interface and Data Specifications 1.0", section "Data Format of the
|
| 679 |
+
Samples", August 1991
|
| 680 |
+
http://www.tactilemedia.com/info/MCI_Control_Info.html
|
| 681 |
+
.. [2] Adobe Systems Incorporated, "Adobe Audition 3 User Guide", section
|
| 682 |
+
"Audio file formats: 24-bit Packed Int (type 1, 20-bit)", 2007
|
| 683 |
+
|
| 684 |
+
Examples
|
| 685 |
+
--------
|
| 686 |
+
>>> from os.path import dirname, join as pjoin
|
| 687 |
+
>>> from scipy.io import wavfile
|
| 688 |
+
>>> import scipy.io
|
| 689 |
+
|
| 690 |
+
Get the filename for an example .wav file from the tests/data directory.
|
| 691 |
+
|
| 692 |
+
>>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data')
|
| 693 |
+
>>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
|
| 694 |
+
|
| 695 |
+
Load the .wav file contents.
|
| 696 |
+
|
| 697 |
+
>>> samplerate, data = wavfile.read(wav_fname)
|
| 698 |
+
>>> print(f"number of channels = {data.shape[1]}")
|
| 699 |
+
number of channels = 2
|
| 700 |
+
>>> length = data.shape[0] / samplerate
|
| 701 |
+
>>> print(f"length = {length}s")
|
| 702 |
+
length = 0.01s
|
| 703 |
+
|
| 704 |
+
Plot the waveform.
|
| 705 |
+
|
| 706 |
+
>>> import matplotlib.pyplot as plt
|
| 707 |
+
>>> import numpy as np
|
| 708 |
+
>>> time = np.linspace(0., length, data.shape[0])
|
| 709 |
+
>>> plt.plot(time, data[:, 0], label="Left channel")
|
| 710 |
+
>>> plt.plot(time, data[:, 1], label="Right channel")
|
| 711 |
+
>>> plt.legend()
|
| 712 |
+
>>> plt.xlabel("Time [s]")
|
| 713 |
+
>>> plt.ylabel("Amplitude")
|
| 714 |
+
>>> plt.show()
|
| 715 |
+
|
| 716 |
+
"""
|
| 717 |
+
if hasattr(filename, 'read'):
|
| 718 |
+
fid = filename
|
| 719 |
+
mmap = False
|
| 720 |
+
else:
|
| 721 |
+
fid = open(filename, 'rb')
|
| 722 |
+
|
| 723 |
+
if not (was_seekable := fid.seekable()):
|
| 724 |
+
fid = SeekEmulatingReader(fid)
|
| 725 |
+
|
| 726 |
+
try:
|
| 727 |
+
file_size, is_big_endian, is_rf64, rf64_chunk_size = _read_riff_chunk(fid)
|
| 728 |
+
fmt_chunk_received = False
|
| 729 |
+
data_chunk_received = False
|
| 730 |
+
while fid.tell() < file_size:
|
| 731 |
+
# read the next chunk
|
| 732 |
+
chunk_id = fid.read(4)
|
| 733 |
+
|
| 734 |
+
if not chunk_id:
|
| 735 |
+
if data_chunk_received:
|
| 736 |
+
# End of file but data successfully read
|
| 737 |
+
warnings.warn(
|
| 738 |
+
f"Reached EOF prematurely; finished at {fid.tell():d} bytes, "
|
| 739 |
+
f"expected {file_size:d} bytes from header.",
|
| 740 |
+
WavFileWarning, stacklevel=2)
|
| 741 |
+
break
|
| 742 |
+
else:
|
| 743 |
+
raise ValueError("Unexpected end of file.")
|
| 744 |
+
elif len(chunk_id) < 4:
|
| 745 |
+
msg = f"Incomplete chunk ID: {repr(chunk_id)}"
|
| 746 |
+
# If we have the data, ignore the broken chunk
|
| 747 |
+
if fmt_chunk_received and data_chunk_received:
|
| 748 |
+
warnings.warn(msg + ", ignoring it.", WavFileWarning,
|
| 749 |
+
stacklevel=2)
|
| 750 |
+
else:
|
| 751 |
+
raise ValueError(msg)
|
| 752 |
+
|
| 753 |
+
if chunk_id == b'fmt ':
|
| 754 |
+
fmt_chunk_received = True
|
| 755 |
+
fmt_chunk = _read_fmt_chunk(fid, is_big_endian)
|
| 756 |
+
format_tag, channels, fs = fmt_chunk[1:4]
|
| 757 |
+
bit_depth = fmt_chunk[6]
|
| 758 |
+
block_align = fmt_chunk[5]
|
| 759 |
+
elif chunk_id == b'fact':
|
| 760 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 761 |
+
elif chunk_id == b'data':
|
| 762 |
+
data_chunk_received = True
|
| 763 |
+
if not fmt_chunk_received:
|
| 764 |
+
raise ValueError("No fmt chunk before data")
|
| 765 |
+
data = _read_data_chunk(fid, format_tag, channels, bit_depth,
|
| 766 |
+
is_big_endian, is_rf64, block_align,
|
| 767 |
+
mmap, rf64_chunk_size)
|
| 768 |
+
elif chunk_id == b'LIST':
|
| 769 |
+
# Someday this could be handled properly but for now skip it
|
| 770 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 771 |
+
elif chunk_id in {b'JUNK', b'Fake'}:
|
| 772 |
+
# Skip alignment chunks without warning
|
| 773 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 774 |
+
else:
|
| 775 |
+
warnings.warn("Chunk (non-data) not understood, skipping it.",
|
| 776 |
+
WavFileWarning, stacklevel=2)
|
| 777 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 778 |
+
finally:
|
| 779 |
+
if not hasattr(filename, 'read'):
|
| 780 |
+
fid.close()
|
| 781 |
+
elif was_seekable:
|
| 782 |
+
# Rewind, if we are able, so that caller can do something
|
| 783 |
+
# else with the raw WAV stream.
|
| 784 |
+
fid.seek(0)
|
| 785 |
+
|
| 786 |
+
return fs, data
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def write(filename, rate, data):
|
| 790 |
+
"""
|
| 791 |
+
Write a NumPy array as a WAV file.
|
| 792 |
+
|
| 793 |
+
Parameters
|
| 794 |
+
----------
|
| 795 |
+
filename : string or open file handle
|
| 796 |
+
Output wav file.
|
| 797 |
+
rate : int
|
| 798 |
+
The sample rate (in samples/sec).
|
| 799 |
+
data : ndarray
|
| 800 |
+
A 1-D or 2-D NumPy array of either integer or float data-type.
|
| 801 |
+
|
| 802 |
+
Notes
|
| 803 |
+
-----
|
| 804 |
+
* Writes a simple uncompressed WAV file.
|
| 805 |
+
* To write multiple-channels, use a 2-D array of shape
|
| 806 |
+
(Nsamples, Nchannels).
|
| 807 |
+
* The bits-per-sample and PCM/float will be determined by the data-type.
|
| 808 |
+
|
| 809 |
+
Common data types: [1]_
|
| 810 |
+
|
| 811 |
+
===================== =========== =========== =============
|
| 812 |
+
WAV format Min Max NumPy dtype
|
| 813 |
+
===================== =========== =========== =============
|
| 814 |
+
32-bit floating-point -1.0 +1.0 float32
|
| 815 |
+
32-bit PCM -2147483648 +2147483647 int32
|
| 816 |
+
16-bit PCM -32768 +32767 int16
|
| 817 |
+
8-bit PCM 0 255 uint8
|
| 818 |
+
===================== =========== =========== =============
|
| 819 |
+
|
| 820 |
+
Note that 8-bit PCM is unsigned.
|
| 821 |
+
|
| 822 |
+
References
|
| 823 |
+
----------
|
| 824 |
+
.. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
|
| 825 |
+
Interface and Data Specifications 1.0", section "Data Format of the
|
| 826 |
+
Samples", August 1991
|
| 827 |
+
http://www.tactilemedia.com/info/MCI_Control_Info.html
|
| 828 |
+
|
| 829 |
+
Examples
|
| 830 |
+
--------
|
| 831 |
+
Create a 100Hz sine wave, sampled at 44100Hz.
|
| 832 |
+
Write to 16-bit PCM, Mono.
|
| 833 |
+
|
| 834 |
+
>>> from scipy.io.wavfile import write
|
| 835 |
+
>>> import numpy as np
|
| 836 |
+
>>> samplerate = 44100; fs = 100
|
| 837 |
+
>>> t = np.linspace(0., 1., samplerate)
|
| 838 |
+
>>> amplitude = np.iinfo(np.int16).max
|
| 839 |
+
>>> data = amplitude * np.sin(2. * np.pi * fs * t)
|
| 840 |
+
>>> write("example.wav", samplerate, data.astype(np.int16))
|
| 841 |
+
|
| 842 |
+
"""
|
| 843 |
+
if hasattr(filename, 'write'):
|
| 844 |
+
fid = filename
|
| 845 |
+
else:
|
| 846 |
+
fid = open(filename, 'wb')
|
| 847 |
+
|
| 848 |
+
fs = rate
|
| 849 |
+
|
| 850 |
+
try:
|
| 851 |
+
dkind = data.dtype.kind
|
| 852 |
+
allowed_dtypes = ['float32', 'float64',
|
| 853 |
+
'uint8', 'int16', 'int32', 'int64']
|
| 854 |
+
if data.dtype.name not in allowed_dtypes:
|
| 855 |
+
raise ValueError(f"Unsupported data type '{data.dtype}'")
|
| 856 |
+
|
| 857 |
+
header_data = b''
|
| 858 |
+
|
| 859 |
+
header_data += b'RIFF'
|
| 860 |
+
header_data += b'\x00\x00\x00\x00'
|
| 861 |
+
header_data += b'WAVE'
|
| 862 |
+
|
| 863 |
+
# fmt chunk
|
| 864 |
+
header_data += b'fmt '
|
| 865 |
+
if dkind == 'f':
|
| 866 |
+
format_tag = WAVE_FORMAT.IEEE_FLOAT
|
| 867 |
+
else:
|
| 868 |
+
format_tag = WAVE_FORMAT.PCM
|
| 869 |
+
if data.ndim == 1:
|
| 870 |
+
channels = 1
|
| 871 |
+
else:
|
| 872 |
+
channels = data.shape[1]
|
| 873 |
+
bit_depth = data.dtype.itemsize * 8
|
| 874 |
+
bytes_per_second = fs*(bit_depth // 8)*channels
|
| 875 |
+
block_align = channels * (bit_depth // 8)
|
| 876 |
+
|
| 877 |
+
fmt_chunk_data = struct.pack('<HHIIHH', format_tag, channels, fs,
|
| 878 |
+
bytes_per_second, block_align, bit_depth)
|
| 879 |
+
if not (dkind == 'i' or dkind == 'u'):
|
| 880 |
+
# add cbSize field for non-PCM files
|
| 881 |
+
fmt_chunk_data += b'\x00\x00'
|
| 882 |
+
|
| 883 |
+
header_data += struct.pack('<I', len(fmt_chunk_data))
|
| 884 |
+
header_data += fmt_chunk_data
|
| 885 |
+
|
| 886 |
+
# check data size (needs to be immediately before the data chunk)
|
| 887 |
+
# if too large for standard RIFF, use RF64 instead
|
| 888 |
+
resulting_file_size = len(header_data) + 4 + 4 + data.nbytes
|
| 889 |
+
is_rf64 = (resulting_file_size - 8) > 0xFFFFFFFF
|
| 890 |
+
if is_rf64:
|
| 891 |
+
header_data = b''
|
| 892 |
+
header_data += b'RF64'
|
| 893 |
+
header_data += b'\xFF\xFF\xFF\xFF'
|
| 894 |
+
header_data += b'WAVE'
|
| 895 |
+
header_data += b'ds64'
|
| 896 |
+
# size of ds64 chunk
|
| 897 |
+
header_data += struct.pack('<I', 28)
|
| 898 |
+
# will be filled later with real file size
|
| 899 |
+
header_data += struct.pack('<Q', 0)
|
| 900 |
+
header_data += struct.pack('<Q', data.nbytes)
|
| 901 |
+
header_data += struct.pack('<Q', data.shape[0])
|
| 902 |
+
# ignore 'table' field for now
|
| 903 |
+
header_data += struct.pack('<I', 0)
|
| 904 |
+
header_data += b'fmt '
|
| 905 |
+
header_data += struct.pack('<I', len(fmt_chunk_data))
|
| 906 |
+
header_data += fmt_chunk_data
|
| 907 |
+
|
| 908 |
+
# fact chunk (non-PCM files)
|
| 909 |
+
if not (dkind == 'i' or dkind == 'u'):
|
| 910 |
+
header_data += b'fact'
|
| 911 |
+
header_data += struct.pack('<II', 4, data.shape[0])
|
| 912 |
+
|
| 913 |
+
fid.write(header_data)
|
| 914 |
+
|
| 915 |
+
# data chunk
|
| 916 |
+
fid.write(b'data')
|
| 917 |
+
# write data chunk size, unless its too big in which case 0xFFFFFFFF is written
|
| 918 |
+
fid.write(struct.pack('<I', min(data.nbytes, 4294967295)))
|
| 919 |
+
|
| 920 |
+
if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and
|
| 921 |
+
sys.byteorder == 'big'):
|
| 922 |
+
data = data.byteswap()
|
| 923 |
+
_array_tofile(fid, data)
|
| 924 |
+
|
| 925 |
+
# Determine file size and place it in correct
|
| 926 |
+
# position at start of the file or the data chunk.
|
| 927 |
+
size = fid.tell()
|
| 928 |
+
if not is_rf64:
|
| 929 |
+
fid.seek(4)
|
| 930 |
+
fid.write(struct.pack('<I', size-8))
|
| 931 |
+
else:
|
| 932 |
+
fid.seek(20)
|
| 933 |
+
fid.write(struct.pack('<Q', size-8))
|
| 934 |
+
|
| 935 |
+
finally:
|
| 936 |
+
if not hasattr(filename, 'write'):
|
| 937 |
+
fid.close()
|
| 938 |
+
else:
|
| 939 |
+
fid.seek(0)
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
def _array_tofile(fid, data):
|
| 943 |
+
# ravel gives a c-contiguous buffer
|
| 944 |
+
fid.write(data.ravel().view('b').data)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/linalg/__init__.pxd
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from scipy.linalg cimport cython_blas, cython_lapack
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/linalg/__init__.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
====================================
|
| 3 |
+
Linear algebra (:mod:`scipy.linalg`)
|
| 4 |
+
====================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.linalg
|
| 7 |
+
|
| 8 |
+
.. toctree::
|
| 9 |
+
:hidden:
|
| 10 |
+
|
| 11 |
+
linalg.blas
|
| 12 |
+
linalg.cython_blas
|
| 13 |
+
linalg.cython_lapack
|
| 14 |
+
linalg.interpolative
|
| 15 |
+
linalg.lapack
|
| 16 |
+
|
| 17 |
+
Linear algebra functions.
|
| 18 |
+
|
| 19 |
+
.. eventually, we should replace the numpy.linalg HTML link with just `numpy.linalg`
|
| 20 |
+
|
| 21 |
+
.. seealso::
|
| 22 |
+
|
| 23 |
+
`numpy.linalg <https://www.numpy.org/devdocs/reference/routines.linalg.html>`__
|
| 24 |
+
for more linear algebra functions. Note that identically named
|
| 25 |
+
functions from `scipy.linalg` may offer more or slightly differing
|
| 26 |
+
functionality.
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
Basics
|
| 30 |
+
======
|
| 31 |
+
|
| 32 |
+
.. autosummary::
|
| 33 |
+
:toctree: generated/
|
| 34 |
+
|
| 35 |
+
inv - Find the inverse of a square matrix
|
| 36 |
+
solve - Solve a linear system of equations
|
| 37 |
+
solve_banded - Solve a banded linear system
|
| 38 |
+
solveh_banded - Solve a Hermitian or symmetric banded system
|
| 39 |
+
solve_circulant - Solve a circulant system
|
| 40 |
+
solve_triangular - Solve a triangular matrix
|
| 41 |
+
solve_toeplitz - Solve a toeplitz matrix
|
| 42 |
+
matmul_toeplitz - Multiply a Toeplitz matrix with an array.
|
| 43 |
+
det - Find the determinant of a square matrix
|
| 44 |
+
norm - Matrix and vector norm
|
| 45 |
+
lstsq - Solve a linear least-squares problem
|
| 46 |
+
pinv - Pseudo-inverse (Moore-Penrose) using lstsq
|
| 47 |
+
pinvh - Pseudo-inverse of hermitian matrix
|
| 48 |
+
khatri_rao - Khatri-Rao product of two arrays
|
| 49 |
+
orthogonal_procrustes - Solve an orthogonal Procrustes problem
|
| 50 |
+
matrix_balance - Balance matrix entries with a similarity transformation
|
| 51 |
+
subspace_angles - Compute the subspace angles between two matrices
|
| 52 |
+
bandwidth - Return the lower and upper bandwidth of an array
|
| 53 |
+
issymmetric - Check if a square 2D array is symmetric
|
| 54 |
+
ishermitian - Check if a square 2D array is Hermitian
|
| 55 |
+
LinAlgError
|
| 56 |
+
LinAlgWarning
|
| 57 |
+
|
| 58 |
+
Eigenvalue Problems
|
| 59 |
+
===================
|
| 60 |
+
|
| 61 |
+
.. autosummary::
|
| 62 |
+
:toctree: generated/
|
| 63 |
+
|
| 64 |
+
eig - Find the eigenvalues and eigenvectors of a square matrix
|
| 65 |
+
eigvals - Find just the eigenvalues of a square matrix
|
| 66 |
+
eigh - Find the e-vals and e-vectors of a Hermitian or symmetric matrix
|
| 67 |
+
eigvalsh - Find just the eigenvalues of a Hermitian or symmetric matrix
|
| 68 |
+
eig_banded - Find the eigenvalues and eigenvectors of a banded matrix
|
| 69 |
+
eigvals_banded - Find just the eigenvalues of a banded matrix
|
| 70 |
+
eigh_tridiagonal - Find the eigenvalues and eigenvectors of a tridiagonal matrix
|
| 71 |
+
eigvalsh_tridiagonal - Find just the eigenvalues of a tridiagonal matrix
|
| 72 |
+
|
| 73 |
+
Decompositions
|
| 74 |
+
==============
|
| 75 |
+
|
| 76 |
+
.. autosummary::
|
| 77 |
+
:toctree: generated/
|
| 78 |
+
|
| 79 |
+
lu - LU decomposition of a matrix
|
| 80 |
+
lu_factor - LU decomposition returning unordered matrix and pivots
|
| 81 |
+
lu_solve - Solve Ax=b using back substitution with output of lu_factor
|
| 82 |
+
svd - Singular value decomposition of a matrix
|
| 83 |
+
svdvals - Singular values of a matrix
|
| 84 |
+
diagsvd - Construct matrix of singular values from output of svd
|
| 85 |
+
orth - Construct orthonormal basis for the range of A using svd
|
| 86 |
+
null_space - Construct orthonormal basis for the null space of A using svd
|
| 87 |
+
ldl - LDL.T decomposition of a Hermitian or a symmetric matrix.
|
| 88 |
+
cholesky - Cholesky decomposition of a matrix
|
| 89 |
+
cholesky_banded - Cholesky decomp. of a sym. or Hermitian banded matrix
|
| 90 |
+
cho_factor - Cholesky decomposition for use in solving a linear system
|
| 91 |
+
cho_solve - Solve previously factored linear system
|
| 92 |
+
cho_solve_banded - Solve previously factored banded linear system
|
| 93 |
+
polar - Compute the polar decomposition.
|
| 94 |
+
qr - QR decomposition of a matrix
|
| 95 |
+
qr_multiply - QR decomposition and multiplication by Q
|
| 96 |
+
qr_update - Rank k QR update
|
| 97 |
+
qr_delete - QR downdate on row or column deletion
|
| 98 |
+
qr_insert - QR update on row or column insertion
|
| 99 |
+
rq - RQ decomposition of a matrix
|
| 100 |
+
qz - QZ decomposition of a pair of matrices
|
| 101 |
+
ordqz - QZ decomposition of a pair of matrices with reordering
|
| 102 |
+
schur - Schur decomposition of a matrix
|
| 103 |
+
rsf2csf - Real to complex Schur form
|
| 104 |
+
hessenberg - Hessenberg form of a matrix
|
| 105 |
+
cdf2rdf - Complex diagonal form to real diagonal block form
|
| 106 |
+
cossin - Cosine sine decomposition of a unitary or orthogonal matrix
|
| 107 |
+
|
| 108 |
+
.. seealso::
|
| 109 |
+
|
| 110 |
+
`scipy.linalg.interpolative` -- Interpolative matrix decompositions
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
Matrix Functions
|
| 114 |
+
================
|
| 115 |
+
|
| 116 |
+
.. autosummary::
|
| 117 |
+
:toctree: generated/
|
| 118 |
+
|
| 119 |
+
expm - Matrix exponential
|
| 120 |
+
logm - Matrix logarithm
|
| 121 |
+
cosm - Matrix cosine
|
| 122 |
+
sinm - Matrix sine
|
| 123 |
+
tanm - Matrix tangent
|
| 124 |
+
coshm - Matrix hyperbolic cosine
|
| 125 |
+
sinhm - Matrix hyperbolic sine
|
| 126 |
+
tanhm - Matrix hyperbolic tangent
|
| 127 |
+
signm - Matrix sign
|
| 128 |
+
sqrtm - Matrix square root
|
| 129 |
+
funm - Evaluating an arbitrary matrix function
|
| 130 |
+
expm_frechet - Frechet derivative of the matrix exponential
|
| 131 |
+
expm_cond - Relative condition number of expm in the Frobenius norm
|
| 132 |
+
fractional_matrix_power - Fractional matrix power
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
Matrix Equation Solvers
|
| 136 |
+
=======================
|
| 137 |
+
|
| 138 |
+
.. autosummary::
|
| 139 |
+
:toctree: generated/
|
| 140 |
+
|
| 141 |
+
solve_sylvester - Solve the Sylvester matrix equation
|
| 142 |
+
solve_continuous_are - Solve the continuous-time algebraic Riccati equation
|
| 143 |
+
solve_discrete_are - Solve the discrete-time algebraic Riccati equation
|
| 144 |
+
solve_continuous_lyapunov - Solve the continuous-time Lyapunov equation
|
| 145 |
+
solve_discrete_lyapunov - Solve the discrete-time Lyapunov equation
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
Sketches and Random Projections
|
| 149 |
+
===============================
|
| 150 |
+
|
| 151 |
+
.. autosummary::
|
| 152 |
+
:toctree: generated/
|
| 153 |
+
|
| 154 |
+
clarkson_woodruff_transform - Applies the Clarkson Woodruff Sketch (a.k.a CountMin Sketch)
|
| 155 |
+
|
| 156 |
+
Special Matrices
|
| 157 |
+
================
|
| 158 |
+
|
| 159 |
+
.. autosummary::
|
| 160 |
+
:toctree: generated/
|
| 161 |
+
|
| 162 |
+
block_diag - Construct a block diagonal matrix from submatrices
|
| 163 |
+
circulant - Circulant matrix
|
| 164 |
+
companion - Companion matrix
|
| 165 |
+
convolution_matrix - Convolution matrix
|
| 166 |
+
dft - Discrete Fourier transform matrix
|
| 167 |
+
fiedler - Fiedler matrix
|
| 168 |
+
fiedler_companion - Fiedler companion matrix
|
| 169 |
+
hadamard - Hadamard matrix of order 2**n
|
| 170 |
+
hankel - Hankel matrix
|
| 171 |
+
helmert - Helmert matrix
|
| 172 |
+
hilbert - Hilbert matrix
|
| 173 |
+
invhilbert - Inverse Hilbert matrix
|
| 174 |
+
leslie - Leslie matrix
|
| 175 |
+
pascal - Pascal matrix
|
| 176 |
+
invpascal - Inverse Pascal matrix
|
| 177 |
+
toeplitz - Toeplitz matrix
|
| 178 |
+
|
| 179 |
+
Low-level routines
|
| 180 |
+
==================
|
| 181 |
+
|
| 182 |
+
.. autosummary::
|
| 183 |
+
:toctree: generated/
|
| 184 |
+
|
| 185 |
+
get_blas_funcs
|
| 186 |
+
get_lapack_funcs
|
| 187 |
+
find_best_blas_type
|
| 188 |
+
|
| 189 |
+
.. seealso::
|
| 190 |
+
|
| 191 |
+
`scipy.linalg.blas` -- Low-level BLAS functions
|
| 192 |
+
|
| 193 |
+
`scipy.linalg.lapack` -- Low-level LAPACK functions
|
| 194 |
+
|
| 195 |
+
`scipy.linalg.cython_blas` -- Low-level BLAS functions for Cython
|
| 196 |
+
|
| 197 |
+
`scipy.linalg.cython_lapack` -- Low-level LAPACK functions for Cython
|
| 198 |
+
|
| 199 |
+
""" # noqa: E501
|
| 200 |
+
|
| 201 |
+
from ._misc import *
|
| 202 |
+
from ._cythonized_array_utils import *
|
| 203 |
+
from ._basic import *
|
| 204 |
+
from ._decomp import *
|
| 205 |
+
from ._decomp_lu import *
|
| 206 |
+
from ._decomp_ldl import *
|
| 207 |
+
from ._decomp_cholesky import *
|
| 208 |
+
from ._decomp_qr import *
|
| 209 |
+
from ._decomp_qz import *
|
| 210 |
+
from ._decomp_svd import *
|
| 211 |
+
from ._decomp_schur import *
|
| 212 |
+
from ._decomp_polar import *
|
| 213 |
+
from ._matfuncs import *
|
| 214 |
+
from .blas import *
|
| 215 |
+
from .lapack import *
|
| 216 |
+
from ._special_matrices import *
|
| 217 |
+
from ._solvers import *
|
| 218 |
+
from ._procrustes import *
|
| 219 |
+
from ._decomp_update import *
|
| 220 |
+
from ._sketches import *
|
| 221 |
+
from ._decomp_cossin import *
|
| 222 |
+
|
| 223 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
| 224 |
+
from . import (
|
| 225 |
+
decomp, decomp_cholesky, decomp_lu, decomp_qr, decomp_svd, decomp_schur,
|
| 226 |
+
basic, misc, special_matrices, matfuncs,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
from scipy._lib._testutils import PytestTester
|
| 233 |
+
test = PytestTester(__name__)
|
| 234 |
+
del PytestTester
|