applied-ai-018 commited on
Commit
6f79a6f
·
verified ·
1 Parent(s): c5f0b3c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step40/zero/13.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step40/zero/13.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
  3. venv/lib/python3.10/site-packages/scipy/datasets/__init__.py +90 -0
  4. venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/__init__.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_download_all.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_registry.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_utils.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py +57 -0
  10. venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py +220 -0
  11. venv/lib/python3.10/site-packages/scipy/datasets/_registry.py +26 -0
  12. venv/lib/python3.10/site-packages/scipy/datasets/_utils.py +81 -0
  13. venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py +0 -0
  14. venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py +123 -0
  17. venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/_scipy_spectral_test_shim.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_result_type.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_savitzky_golay.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_signaltools.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_waveforms.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_wavelets.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py +52 -0
  25. venv/lib/python3.10/site-packages/scipy/signal/windows/__pycache__/__init__.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/scipy/signal/windows/__pycache__/_windows.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/scipy/signal/windows/__pycache__/windows.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py +2374 -0
  29. venv/lib/python3.10/site-packages/scipy/signal/windows/windows.py +24 -0
  30. venv/lib/python3.10/site-packages/scipy/special/__init__.py +863 -0
  31. venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/scipy/special/__pycache__/_basic.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/scipy/special/__pycache__/_testutils.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py +0 -0
  44. venv/lib/python3.10/site-packages/scipy/special/_basic.py +0 -0
  45. venv/lib/python3.10/site-packages/scipy/special/_cdflib.cpython-310-x86_64-linux-gnu.so +0 -0
  46. venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so +0 -0
  47. venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py +214 -0
  48. venv/lib/python3.10/site-packages/scipy/special/_ellip_harm_2.cpython-310-x86_64-linux-gnu.so +0 -0
  49. venv/lib/python3.10/site-packages/scipy/special/_lambertw.py +149 -0
  50. venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py +307 -0
ckpts/universal/global_step40/zero/13.mlp.dense_h_to_4h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dca47d9e08e05365f06d99de39e3906c525902dbfb9fd433f82336907ff8c8ee
3
+ size 33555627
ckpts/universal/global_step40/zero/13.mlp.dense_h_to_4h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:346836985993271f5166b56fa60162ce854d4b23350c1eadb9ad378f144cfdf9
3
+ size 33555533
venv/lib/python3.10/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
venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_download_all.cpython-310.pyc ADDED
Binary file (1.71 kB). View file
 
venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_fetchers.cpython-310.pyc ADDED
Binary file (6.31 kB). View file
 
venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_registry.cpython-310.pyc ADDED
Binary file (774 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/datasets/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Platform independent script to download all the
3
+ `scipy.datasets` module data files.
4
+ This doesn't require a full scipy build.
5
+
6
+ Run: python _download_all.py <download_dir>
7
+ """
8
+
9
+ import argparse
10
+ try:
11
+ import pooch
12
+ except ImportError:
13
+ pooch = None
14
+
15
+
16
+ if __package__ is None or __package__ == '':
17
+ # Running as python script, use absolute import
18
+ import _registry # type: ignore
19
+ else:
20
+ # Running as python module, use relative import
21
+ from . import _registry
22
+
23
+
24
+ def download_all(path=None):
25
+ """
26
+ Utility method to download all the dataset files
27
+ for `scipy.datasets` module.
28
+
29
+ Parameters
30
+ ----------
31
+ path : str, optional
32
+ Directory path to download all the dataset files.
33
+ If None, default to the system cache_dir detected by pooch.
34
+ """
35
+ if pooch is None:
36
+ raise ImportError("Missing optional dependency 'pooch' required "
37
+ "for scipy.datasets module. Please use pip or "
38
+ "conda to install 'pooch'.")
39
+ if path is None:
40
+ path = pooch.os_cache('scipy-data')
41
+ for dataset_name, dataset_hash in _registry.registry.items():
42
+ pooch.retrieve(url=_registry.registry_urls[dataset_name],
43
+ known_hash=dataset_hash,
44
+ fname=dataset_name, path=path)
45
+
46
+
47
+ def main():
48
+ parser = argparse.ArgumentParser(description='Download SciPy data files.')
49
+ parser.add_argument("path", nargs='?', type=str,
50
+ default=pooch.os_cache('scipy-data'),
51
+ help="Directory path to download all the data files.")
52
+ args = parser.parse_args()
53
+ download_all(args.path)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy import array, frombuffer, load
2
+ from ._registry import registry, registry_urls
3
+
4
+ try:
5
+ import pooch
6
+ except ImportError:
7
+ pooch = None
8
+ data_fetcher = None
9
+ else:
10
+ data_fetcher = pooch.create(
11
+ # Use the default cache folder for the operating system
12
+ # Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
13
+ # select an appropriate directory for the cache on each platform.
14
+ path=pooch.os_cache("scipy-data"),
15
+
16
+ # The remote data is on Github
17
+ # base_url is a required param, even though we override this
18
+ # using individual urls in the registry.
19
+ base_url="https://github.com/scipy/",
20
+ registry=registry,
21
+ urls=registry_urls
22
+ )
23
+
24
+
25
+ def fetch_data(dataset_name, data_fetcher=data_fetcher):
26
+ if data_fetcher is None:
27
+ raise ImportError("Missing optional dependency 'pooch' required "
28
+ "for scipy.datasets module. Please use pip or "
29
+ "conda to install 'pooch'.")
30
+ # The "fetch" method returns the full path to the downloaded data file.
31
+ return data_fetcher.fetch(dataset_name)
32
+
33
+
34
+ def ascent():
35
+ """
36
+ Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
37
+ use in demos.
38
+
39
+ The image is derived from accent-to-the-top.jpg at
40
+ http://www.public-domain-image.com/people-public-domain-images-pictures/
41
+
42
+ Parameters
43
+ ----------
44
+ None
45
+
46
+ Returns
47
+ -------
48
+ ascent : ndarray
49
+ convenient image to use for testing and demonstration
50
+
51
+ Examples
52
+ --------
53
+ >>> import scipy.datasets
54
+ >>> ascent = scipy.datasets.ascent()
55
+ >>> ascent.shape
56
+ (512, 512)
57
+ >>> ascent.max()
58
+ 255
59
+
60
+ >>> import matplotlib.pyplot as plt
61
+ >>> plt.gray()
62
+ >>> plt.imshow(ascent)
63
+ >>> plt.show()
64
+
65
+ """
66
+ import pickle
67
+
68
+ # The file will be downloaded automatically the first time this is run,
69
+ # returning the path to the downloaded file. Afterwards, Pooch finds
70
+ # it in the local cache and doesn't repeat the download.
71
+ fname = fetch_data("ascent.dat")
72
+ # Now we just need to load it with our standard Python tools.
73
+ with open(fname, 'rb') as f:
74
+ ascent = array(pickle.load(f))
75
+ return ascent
76
+
77
+
78
+ def electrocardiogram():
79
+ """
80
+ Load an electrocardiogram as an example for a 1-D signal.
81
+
82
+ The returned signal is a 5 minute long electrocardiogram (ECG), a medical
83
+ recording of the heart's electrical activity, sampled at 360 Hz.
84
+
85
+ Returns
86
+ -------
87
+ ecg : ndarray
88
+ The electrocardiogram in millivolt (mV) sampled at 360 Hz.
89
+
90
+ Notes
91
+ -----
92
+ The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
93
+ (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
94
+ PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
95
+ heartbeats as well as pathological changes.
96
+
97
+ .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
98
+
99
+ .. versionadded:: 1.1.0
100
+
101
+ References
102
+ ----------
103
+ .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
104
+ IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
105
+ (PMID: 11446209); :doi:`10.13026/C2F305`
106
+ .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
107
+ Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
108
+ PhysioToolkit, and PhysioNet: Components of a New Research Resource
109
+ for Complex Physiologic Signals. Circulation 101(23):e215-e220;
110
+ :doi:`10.1161/01.CIR.101.23.e215`
111
+
112
+ Examples
113
+ --------
114
+ >>> from scipy.datasets import electrocardiogram
115
+ >>> ecg = electrocardiogram()
116
+ >>> ecg
117
+ array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385])
118
+ >>> ecg.shape, ecg.mean(), ecg.std()
119
+ ((108000,), -0.16510875, 0.5992473991177294)
120
+
121
+ As stated the signal features several areas with a different morphology.
122
+ E.g., the first few seconds show the electrical activity of a heart in
123
+ normal sinus rhythm as seen below.
124
+
125
+ >>> import numpy as np
126
+ >>> import matplotlib.pyplot as plt
127
+ >>> fs = 360
128
+ >>> time = np.arange(ecg.size) / fs
129
+ >>> plt.plot(time, ecg)
130
+ >>> plt.xlabel("time in s")
131
+ >>> plt.ylabel("ECG in mV")
132
+ >>> plt.xlim(9, 10.2)
133
+ >>> plt.ylim(-1, 1.5)
134
+ >>> plt.show()
135
+
136
+ After second 16, however, the first premature ventricular contractions,
137
+ also called extrasystoles, appear. These have a different morphology
138
+ compared to typical heartbeats. The difference can easily be observed
139
+ in the following plot.
140
+
141
+ >>> plt.plot(time, ecg)
142
+ >>> plt.xlabel("time in s")
143
+ >>> plt.ylabel("ECG in mV")
144
+ >>> plt.xlim(46.5, 50)
145
+ >>> plt.ylim(-2, 1.5)
146
+ >>> plt.show()
147
+
148
+ At several points large artifacts disturb the recording, e.g.:
149
+
150
+ >>> plt.plot(time, ecg)
151
+ >>> plt.xlabel("time in s")
152
+ >>> plt.ylabel("ECG in mV")
153
+ >>> plt.xlim(207, 215)
154
+ >>> plt.ylim(-2, 3.5)
155
+ >>> plt.show()
156
+
157
+ Finally, examining the power spectrum reveals that most of the biosignal is
158
+ made up of lower frequencies. At 60 Hz the noise induced by the mains
159
+ electricity can be clearly observed.
160
+
161
+ >>> from scipy.signal import welch
162
+ >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
163
+ >>> plt.semilogy(f, Pxx)
164
+ >>> plt.xlabel("Frequency in Hz")
165
+ >>> plt.ylabel("Power spectrum of the ECG in mV**2")
166
+ >>> plt.xlim(f[[0, -1]])
167
+ >>> plt.show()
168
+ """
169
+ fname = fetch_data("ecg.dat")
170
+ with load(fname) as file:
171
+ ecg = file["ecg"].astype(int) # np.uint16 -> int
172
+ # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
173
+ ecg = (ecg - 1024) / 200.0
174
+ return ecg
175
+
176
+
177
+ def face(gray=False):
178
+ """
179
+ Get a 1024 x 768, color image of a raccoon face.
180
+
181
+ raccoon-procyon-lotor.jpg at http://www.public-domain-image.com
182
+
183
+ Parameters
184
+ ----------
185
+ gray : bool, optional
186
+ If True return 8-bit grey-scale image, otherwise return a color image
187
+
188
+ Returns
189
+ -------
190
+ face : ndarray
191
+ image of a raccoon face
192
+
193
+ Examples
194
+ --------
195
+ >>> import scipy.datasets
196
+ >>> face = scipy.datasets.face()
197
+ >>> face.shape
198
+ (768, 1024, 3)
199
+ >>> face.max()
200
+ 255
201
+ >>> face.dtype
202
+ dtype('uint8')
203
+
204
+ >>> import matplotlib.pyplot as plt
205
+ >>> plt.gray()
206
+ >>> plt.imshow(face)
207
+ >>> plt.show()
208
+
209
+ """
210
+ import bz2
211
+ fname = fetch_data("face.dat")
212
+ with open(fname, 'rb') as f:
213
+ rawdata = f.read()
214
+ face_data = bz2.decompress(rawdata)
215
+ face = frombuffer(face_data, dtype='uint8')
216
+ face.shape = (768, 1024, 3)
217
+ if gray is True:
218
+ face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
219
+ 0.07 * face[:, :, 2]).astype('uint8')
220
+ return face
venv/lib/python3.10/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
+ }
venv/lib/python3.10/site-packages/scipy/datasets/_utils.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from ._registry import method_files_map
4
+
5
+ try:
6
+ import platformdirs
7
+ except ImportError:
8
+ platformdirs = None # type: ignore[assignment]
9
+
10
+
11
+ def _clear_cache(datasets, cache_dir=None, method_map=None):
12
+ if method_map is None:
13
+ # Use SciPy Datasets method map
14
+ method_map = method_files_map
15
+ if cache_dir is None:
16
+ # Use default cache_dir path
17
+ if platformdirs is None:
18
+ # platformdirs is pooch dependency
19
+ raise ImportError("Missing optional dependency 'pooch' required "
20
+ "for scipy.datasets module. Please use pip or "
21
+ "conda to install 'pooch'.")
22
+ cache_dir = platformdirs.user_cache_dir("scipy-data")
23
+
24
+ if not os.path.exists(cache_dir):
25
+ print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
26
+ return
27
+
28
+ if datasets is None:
29
+ print(f"Cleaning the cache directory {cache_dir}!")
30
+ shutil.rmtree(cache_dir)
31
+ else:
32
+ if not isinstance(datasets, (list, tuple)):
33
+ # single dataset method passed should be converted to list
34
+ datasets = [datasets, ]
35
+ for dataset in datasets:
36
+ assert callable(dataset)
37
+ dataset_name = dataset.__name__ # Name of the dataset method
38
+ if dataset_name not in method_map:
39
+ raise ValueError(f"Dataset method {dataset_name} doesn't "
40
+ "exist. Please check if the passed dataset "
41
+ "is a subset of the following dataset "
42
+ f"methods: {list(method_map.keys())}")
43
+
44
+ data_files = method_map[dataset_name]
45
+ data_filepaths = [os.path.join(cache_dir, file)
46
+ for file in data_files]
47
+ for data_filepath in data_filepaths:
48
+ if os.path.exists(data_filepath):
49
+ print("Cleaning the file "
50
+ f"{os.path.split(data_filepath)[1]} "
51
+ f"for dataset {dataset_name}")
52
+ os.remove(data_filepath)
53
+ else:
54
+ print(f"Path {data_filepath} doesn't exist. "
55
+ "Nothing to clear.")
56
+
57
+
58
+ def clear_cache(datasets=None):
59
+ """
60
+ Cleans the scipy datasets cache directory.
61
+
62
+ If a scipy.datasets method or a list/tuple of the same is
63
+ provided, then clear_cache removes all the data files
64
+ associated to the passed dataset method callable(s).
65
+
66
+ By default, it removes all the cached data files.
67
+
68
+ Parameters
69
+ ----------
70
+ datasets : callable or list/tuple of callable or None
71
+
72
+ Examples
73
+ --------
74
+ >>> from scipy import datasets
75
+ >>> ascent_array = datasets.ascent()
76
+ >>> ascent_array.shape
77
+ (512, 512)
78
+ >>> datasets.clear_cache([datasets.ascent])
79
+ Cleaning the file ascent.dat for dataset ascent
80
+ """
81
+ _clear_cache(datasets)
venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/datasets/tests/__pycache__/test_data.cpython-310.pyc ADDED
Binary file (3.82 kB). View file
 
venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scipy.datasets._registry import registry
2
+ from scipy.datasets._fetchers import data_fetcher
3
+ from scipy.datasets._utils import _clear_cache
4
+ from scipy.datasets import ascent, face, electrocardiogram, download_all
5
+ from numpy.testing import assert_equal, assert_almost_equal
6
+ import os
7
+ import pytest
8
+
9
+ try:
10
+ import pooch
11
+ except ImportError:
12
+ raise ImportError("Missing optional dependency 'pooch' required "
13
+ "for scipy.datasets module. Please use pip or "
14
+ "conda to install 'pooch'.")
15
+
16
+
17
+ data_dir = data_fetcher.path # type: ignore
18
+
19
+
20
+ def _has_hash(path, expected_hash):
21
+ """Check if the provided path has the expected hash."""
22
+ if not os.path.exists(path):
23
+ return False
24
+ return pooch.file_hash(path) == expected_hash
25
+
26
+
27
+ class TestDatasets:
28
+
29
+ @pytest.fixture(scope='module', autouse=True)
30
+ def test_download_all(self):
31
+ # This fixture requires INTERNET CONNECTION
32
+
33
+ # test_setup phase
34
+ download_all()
35
+
36
+ yield
37
+
38
+ def test_existence_all(self):
39
+ assert len(os.listdir(data_dir)) >= len(registry)
40
+
41
+ def test_ascent(self):
42
+ assert_equal(ascent().shape, (512, 512))
43
+
44
+ # hash check
45
+ assert _has_hash(os.path.join(data_dir, "ascent.dat"),
46
+ registry["ascent.dat"])
47
+
48
+ def test_face(self):
49
+ assert_equal(face().shape, (768, 1024, 3))
50
+
51
+ # hash check
52
+ assert _has_hash(os.path.join(data_dir, "face.dat"),
53
+ registry["face.dat"])
54
+
55
+ def test_electrocardiogram(self):
56
+ # Test shape, dtype and stats of signal
57
+ ecg = electrocardiogram()
58
+ assert_equal(ecg.dtype, float)
59
+ assert_equal(ecg.shape, (108000,))
60
+ assert_almost_equal(ecg.mean(), -0.16510875)
61
+ assert_almost_equal(ecg.std(), 0.5992473991177294)
62
+
63
+ # hash check
64
+ assert _has_hash(os.path.join(data_dir, "ecg.dat"),
65
+ registry["ecg.dat"])
66
+
67
+
68
+ def test_clear_cache(tmp_path):
69
+ # Note: `tmp_path` is a pytest fixture, it handles cleanup
70
+ dummy_basepath = tmp_path / "dummy_cache_dir"
71
+ dummy_basepath.mkdir()
72
+
73
+ # Create three dummy dataset files for dummy dataset methods
74
+ dummy_method_map = {}
75
+ for i in range(4):
76
+ dummy_method_map[f"data{i}"] = [f"data{i}.dat"]
77
+ data_filepath = dummy_basepath / f"data{i}.dat"
78
+ data_filepath.write_text("")
79
+
80
+ # clear files associated to single dataset method data0
81
+ # also test callable argument instead of list of callables
82
+ def data0():
83
+ pass
84
+ _clear_cache(datasets=data0, cache_dir=dummy_basepath,
85
+ method_map=dummy_method_map)
86
+ assert not os.path.exists(dummy_basepath/"data0.dat")
87
+
88
+ # clear files associated to multiple dataset methods "data3" and "data4"
89
+ def data1():
90
+ pass
91
+
92
+ def data2():
93
+ pass
94
+ _clear_cache(datasets=[data1, data2], cache_dir=dummy_basepath,
95
+ method_map=dummy_method_map)
96
+ assert not os.path.exists(dummy_basepath/"data1.dat")
97
+ assert not os.path.exists(dummy_basepath/"data2.dat")
98
+
99
+ # clear multiple dataset files "data3_0.dat" and "data3_1.dat"
100
+ # associated with dataset method "data3"
101
+ def data4():
102
+ pass
103
+ # create files
104
+ (dummy_basepath / "data4_0.dat").write_text("")
105
+ (dummy_basepath / "data4_1.dat").write_text("")
106
+
107
+ dummy_method_map["data4"] = ["data4_0.dat", "data4_1.dat"]
108
+ _clear_cache(datasets=[data4], cache_dir=dummy_basepath,
109
+ method_map=dummy_method_map)
110
+ assert not os.path.exists(dummy_basepath/"data4_0.dat")
111
+ assert not os.path.exists(dummy_basepath/"data4_1.dat")
112
+
113
+ # wrong dataset method should raise ValueError since it
114
+ # doesn't exist in the dummy_method_map
115
+ def data5():
116
+ pass
117
+ with pytest.raises(ValueError):
118
+ _clear_cache(datasets=[data5], cache_dir=dummy_basepath,
119
+ method_map=dummy_method_map)
120
+
121
+ # remove all dataset cache
122
+ _clear_cache(datasets=None, cache_dir=dummy_basepath)
123
+ assert not os.path.exists(dummy_basepath)
venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/_scipy_spectral_test_shim.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_result_type.cpython-310.pyc ADDED
Binary file (1.77 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_savitzky_golay.cpython-310.pyc ADDED
Binary file (9.32 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_signaltools.cpython-310.pyc ADDED
Binary file (117 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_waveforms.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/tests/__pycache__/test_wavelets.cpython-310.pyc ADDED
Binary file (5.07 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Window functions (:mod:`scipy.signal.windows`)
3
+ ==============================================
4
+
5
+ The suite of window functions for filtering and spectral estimation.
6
+
7
+ .. currentmodule:: scipy.signal.windows
8
+
9
+ .. autosummary::
10
+ :toctree: generated/
11
+
12
+ get_window -- Return a window of a given length and type.
13
+
14
+ barthann -- Bartlett-Hann window
15
+ bartlett -- Bartlett window
16
+ blackman -- Blackman window
17
+ blackmanharris -- Minimum 4-term Blackman-Harris window
18
+ bohman -- Bohman window
19
+ boxcar -- Boxcar window
20
+ chebwin -- Dolph-Chebyshev window
21
+ cosine -- Cosine window
22
+ dpss -- Discrete prolate spheroidal sequences
23
+ exponential -- Exponential window
24
+ flattop -- Flat top window
25
+ gaussian -- Gaussian window
26
+ general_cosine -- Generalized Cosine window
27
+ general_gaussian -- Generalized Gaussian window
28
+ general_hamming -- Generalized Hamming window
29
+ hamming -- Hamming window
30
+ hann -- Hann window
31
+ kaiser -- Kaiser window
32
+ kaiser_bessel_derived -- Kaiser-Bessel derived window
33
+ lanczos -- Lanczos window also known as a sinc window
34
+ nuttall -- Nuttall's minimum 4-term Blackman-Harris window
35
+ parzen -- Parzen window
36
+ taylor -- Taylor window
37
+ triang -- Triangular window
38
+ tukey -- Tukey window
39
+
40
+ """
41
+
42
+ from ._windows import *
43
+
44
+ # Deprecated namespaces, to be removed in v2.0.0
45
+ from . import windows
46
+
47
+ __all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
48
+ 'blackmanharris', 'flattop', 'bartlett', 'barthann',
49
+ 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian',
50
+ 'general_gaussian', 'general_cosine', 'general_hamming',
51
+ 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor',
52
+ 'get_window', 'dpss', 'lanczos']
venv/lib/python3.10/site-packages/scipy/signal/windows/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.18 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/windows/__pycache__/_windows.cpython-310.pyc ADDED
Binary file (79.6 kB). View file
 
venv/lib/python3.10/site-packages/scipy/signal/windows/__pycache__/windows.cpython-310.pyc ADDED
Binary file (881 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py ADDED
@@ -0,0 +1,2374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The suite of window functions."""
2
+
3
+ import operator
4
+ import warnings
5
+
6
+ import numpy as np
7
+ from scipy import linalg, special, fft as sp_fft
8
+
9
+ __all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
10
+ 'blackmanharris', 'flattop', 'bartlett', 'barthann',
11
+ 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian',
12
+ 'general_cosine', 'general_gaussian', 'general_hamming',
13
+ 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor',
14
+ 'dpss', 'get_window', 'lanczos']
15
+
16
+
17
+ def _len_guards(M):
18
+ """Handle small or incorrect window lengths"""
19
+ if int(M) != M or M < 0:
20
+ raise ValueError('Window length M must be a non-negative integer')
21
+ return M <= 1
22
+
23
+
24
+ def _extend(M, sym):
25
+ """Extend window by 1 sample if needed for DFT-even symmetry"""
26
+ if not sym:
27
+ return M + 1, True
28
+ else:
29
+ return M, False
30
+
31
+
32
+ def _truncate(w, needed):
33
+ """Truncate window by 1 sample if needed for DFT-even symmetry"""
34
+ if needed:
35
+ return w[:-1]
36
+ else:
37
+ return w
38
+
39
+
40
+ def general_cosine(M, a, sym=True):
41
+ r"""
42
+ Generic weighted sum of cosine terms window
43
+
44
+ Parameters
45
+ ----------
46
+ M : int
47
+ Number of points in the output window
48
+ a : array_like
49
+ Sequence of weighting coefficients. This uses the convention of being
50
+ centered on the origin, so these will typically all be positive
51
+ numbers, not alternating sign.
52
+ sym : bool, optional
53
+ When True (default), generates a symmetric window, for use in filter
54
+ design.
55
+ When False, generates a periodic window, for use in spectral analysis.
56
+
57
+ Returns
58
+ -------
59
+ w : ndarray
60
+ The array of window values.
61
+
62
+ References
63
+ ----------
64
+ .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
65
+ Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
66
+ no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
67
+ .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
68
+ Discrete Fourier transform (DFT), including a comprehensive list of
69
+ window functions and some new flat-top windows", February 15, 2002
70
+ https://holometer.fnal.gov/GH_FFT.pdf
71
+
72
+ Examples
73
+ --------
74
+ Heinzel describes a flat-top window named "HFT90D" with formula: [2]_
75
+
76
+ .. math:: w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z)
77
+ - 0.440811 \cos(3z) + 0.043097 \cos(4z)
78
+
79
+ where
80
+
81
+ .. math:: z = \frac{2 \pi j}{N}, j = 0...N - 1
82
+
83
+ Since this uses the convention of starting at the origin, to reproduce the
84
+ window, we need to convert every other coefficient to a positive number:
85
+
86
+ >>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097]
87
+
88
+ The paper states that the highest sidelobe is at -90.2 dB. Reproduce
89
+ Figure 42 by plotting the window and its frequency response, and confirm
90
+ the sidelobe level in red:
91
+
92
+ >>> import numpy as np
93
+ >>> from scipy.signal.windows import general_cosine
94
+ >>> from scipy.fft import fft, fftshift
95
+ >>> import matplotlib.pyplot as plt
96
+
97
+ >>> window = general_cosine(1000, HFT90D, sym=False)
98
+ >>> plt.plot(window)
99
+ >>> plt.title("HFT90D window")
100
+ >>> plt.ylabel("Amplitude")
101
+ >>> plt.xlabel("Sample")
102
+
103
+ >>> plt.figure()
104
+ >>> A = fft(window, 10000) / (len(window)/2.0)
105
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
106
+ >>> response = np.abs(fftshift(A / abs(A).max()))
107
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
108
+ >>> plt.plot(freq, response)
109
+ >>> plt.axis([-50/1000, 50/1000, -140, 0])
110
+ >>> plt.title("Frequency response of the HFT90D window")
111
+ >>> plt.ylabel("Normalized magnitude [dB]")
112
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
113
+ >>> plt.axhline(-90.2, color='red')
114
+ >>> plt.show()
115
+ """
116
+ if _len_guards(M):
117
+ return np.ones(M)
118
+ M, needs_trunc = _extend(M, sym)
119
+
120
+ fac = np.linspace(-np.pi, np.pi, M)
121
+ w = np.zeros(M)
122
+ for k in range(len(a)):
123
+ w += a[k] * np.cos(k * fac)
124
+
125
+ return _truncate(w, needs_trunc)
126
+
127
+
128
+ def boxcar(M, sym=True):
129
+ """Return a boxcar or rectangular window.
130
+
131
+ Also known as a rectangular window or Dirichlet window, this is equivalent
132
+ to no window at all.
133
+
134
+ Parameters
135
+ ----------
136
+ M : int
137
+ Number of points in the output window. If zero, an empty array
138
+ is returned. An exception is thrown when it is negative.
139
+ sym : bool, optional
140
+ Whether the window is symmetric. (Has no effect for boxcar.)
141
+
142
+ Returns
143
+ -------
144
+ w : ndarray
145
+ The window, with the maximum value normalized to 1.
146
+
147
+ Examples
148
+ --------
149
+ Plot the window and its frequency response:
150
+
151
+ >>> import numpy as np
152
+ >>> from scipy import signal
153
+ >>> from scipy.fft import fft, fftshift
154
+ >>> import matplotlib.pyplot as plt
155
+
156
+ >>> window = signal.windows.boxcar(51)
157
+ >>> plt.plot(window)
158
+ >>> plt.title("Boxcar window")
159
+ >>> plt.ylabel("Amplitude")
160
+ >>> plt.xlabel("Sample")
161
+
162
+ >>> plt.figure()
163
+ >>> A = fft(window, 2048) / (len(window)/2.0)
164
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
165
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
166
+ >>> plt.plot(freq, response)
167
+ >>> plt.axis([-0.5, 0.5, -120, 0])
168
+ >>> plt.title("Frequency response of the boxcar window")
169
+ >>> plt.ylabel("Normalized magnitude [dB]")
170
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
171
+
172
+ """
173
+ if _len_guards(M):
174
+ return np.ones(M)
175
+ M, needs_trunc = _extend(M, sym)
176
+
177
+ w = np.ones(M, float)
178
+
179
+ return _truncate(w, needs_trunc)
180
+
181
+
182
+ def triang(M, sym=True):
183
+ """Return a triangular window.
184
+
185
+ Parameters
186
+ ----------
187
+ M : int
188
+ Number of points in the output window. If zero, an empty array
189
+ is returned. An exception is thrown when it is negative.
190
+ sym : bool, optional
191
+ When True (default), generates a symmetric window, for use in filter
192
+ design.
193
+ When False, generates a periodic window, for use in spectral analysis.
194
+
195
+ Returns
196
+ -------
197
+ w : ndarray
198
+ The window, with the maximum value normalized to 1 (though the value 1
199
+ does not appear if `M` is even and `sym` is True).
200
+
201
+ See Also
202
+ --------
203
+ bartlett : A triangular window that touches zero
204
+
205
+ Examples
206
+ --------
207
+ Plot the window and its frequency response:
208
+
209
+ >>> import numpy as np
210
+ >>> from scipy import signal
211
+ >>> from scipy.fft import fft, fftshift
212
+ >>> import matplotlib.pyplot as plt
213
+
214
+ >>> window = signal.windows.triang(51)
215
+ >>> plt.plot(window)
216
+ >>> plt.title("Triangular window")
217
+ >>> plt.ylabel("Amplitude")
218
+ >>> plt.xlabel("Sample")
219
+
220
+ >>> plt.figure()
221
+ >>> A = fft(window, 2048) / (len(window)/2.0)
222
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
223
+ >>> response = np.abs(fftshift(A / abs(A).max()))
224
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
225
+ >>> plt.plot(freq, response)
226
+ >>> plt.axis([-0.5, 0.5, -120, 0])
227
+ >>> plt.title("Frequency response of the triangular window")
228
+ >>> plt.ylabel("Normalized magnitude [dB]")
229
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
230
+
231
+ """
232
+ if _len_guards(M):
233
+ return np.ones(M)
234
+ M, needs_trunc = _extend(M, sym)
235
+
236
+ n = np.arange(1, (M + 1) // 2 + 1)
237
+ if M % 2 == 0:
238
+ w = (2 * n - 1.0) / M
239
+ w = np.r_[w, w[::-1]]
240
+ else:
241
+ w = 2 * n / (M + 1.0)
242
+ w = np.r_[w, w[-2::-1]]
243
+
244
+ return _truncate(w, needs_trunc)
245
+
246
+
247
+ def parzen(M, sym=True):
248
+ """Return a Parzen window.
249
+
250
+ Parameters
251
+ ----------
252
+ M : int
253
+ Number of points in the output window. If zero, an empty array
254
+ is returned. An exception is thrown when it is negative.
255
+ sym : bool, optional
256
+ When True (default), generates a symmetric window, for use in filter
257
+ design.
258
+ When False, generates a periodic window, for use in spectral analysis.
259
+
260
+ Returns
261
+ -------
262
+ w : ndarray
263
+ The window, with the maximum value normalized to 1 (though the value 1
264
+ does not appear if `M` is even and `sym` is True).
265
+
266
+ References
267
+ ----------
268
+ .. [1] E. Parzen, "Mathematical Considerations in the Estimation of
269
+ Spectra", Technometrics, Vol. 3, No. 2 (May, 1961), pp. 167-190
270
+
271
+ Examples
272
+ --------
273
+ Plot the window and its frequency response:
274
+
275
+ >>> import numpy as np
276
+ >>> from scipy import signal
277
+ >>> from scipy.fft import fft, fftshift
278
+ >>> import matplotlib.pyplot as plt
279
+
280
+ >>> window = signal.windows.parzen(51)
281
+ >>> plt.plot(window)
282
+ >>> plt.title("Parzen window")
283
+ >>> plt.ylabel("Amplitude")
284
+ >>> plt.xlabel("Sample")
285
+
286
+ >>> plt.figure()
287
+ >>> A = fft(window, 2048) / (len(window)/2.0)
288
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
289
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
290
+ >>> plt.plot(freq, response)
291
+ >>> plt.axis([-0.5, 0.5, -120, 0])
292
+ >>> plt.title("Frequency response of the Parzen window")
293
+ >>> plt.ylabel("Normalized magnitude [dB]")
294
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
295
+
296
+ """
297
+ if _len_guards(M):
298
+ return np.ones(M)
299
+ M, needs_trunc = _extend(M, sym)
300
+
301
+ n = np.arange(-(M - 1) / 2.0, (M - 1) / 2.0 + 0.5, 1.0)
302
+ na = np.extract(n < -(M - 1) / 4.0, n)
303
+ nb = np.extract(abs(n) <= (M - 1) / 4.0, n)
304
+ wa = 2 * (1 - np.abs(na) / (M / 2.0)) ** 3.0
305
+ wb = (1 - 6 * (np.abs(nb) / (M / 2.0)) ** 2.0 +
306
+ 6 * (np.abs(nb) / (M / 2.0)) ** 3.0)
307
+ w = np.r_[wa, wb, wa[::-1]]
308
+
309
+ return _truncate(w, needs_trunc)
310
+
311
+
312
+ def bohman(M, sym=True):
313
+ """Return a Bohman window.
314
+
315
+ Parameters
316
+ ----------
317
+ M : int
318
+ Number of points in the output window. If zero, an empty array
319
+ is returned. An exception is thrown when it is negative.
320
+ sym : bool, optional
321
+ When True (default), generates a symmetric window, for use in filter
322
+ design.
323
+ When False, generates a periodic window, for use in spectral analysis.
324
+
325
+ Returns
326
+ -------
327
+ w : ndarray
328
+ The window, with the maximum value normalized to 1 (though the value 1
329
+ does not appear if `M` is even and `sym` is True).
330
+
331
+ Examples
332
+ --------
333
+ Plot the window and its frequency response:
334
+
335
+ >>> import numpy as np
336
+ >>> from scipy import signal
337
+ >>> from scipy.fft import fft, fftshift
338
+ >>> import matplotlib.pyplot as plt
339
+
340
+ >>> window = signal.windows.bohman(51)
341
+ >>> plt.plot(window)
342
+ >>> plt.title("Bohman window")
343
+ >>> plt.ylabel("Amplitude")
344
+ >>> plt.xlabel("Sample")
345
+
346
+ >>> plt.figure()
347
+ >>> A = fft(window, 2047) / (len(window)/2.0)
348
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
349
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
350
+ >>> plt.plot(freq, response)
351
+ >>> plt.axis([-0.5, 0.5, -120, 0])
352
+ >>> plt.title("Frequency response of the Bohman window")
353
+ >>> plt.ylabel("Normalized magnitude [dB]")
354
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
355
+
356
+ """
357
+ if _len_guards(M):
358
+ return np.ones(M)
359
+ M, needs_trunc = _extend(M, sym)
360
+
361
+ fac = np.abs(np.linspace(-1, 1, M)[1:-1])
362
+ w = (1 - fac) * np.cos(np.pi * fac) + 1.0 / np.pi * np.sin(np.pi * fac)
363
+ w = np.r_[0, w, 0]
364
+
365
+ return _truncate(w, needs_trunc)
366
+
367
+
368
+ def blackman(M, sym=True):
369
+ r"""
370
+ Return a Blackman window.
371
+
372
+ The Blackman window is a taper formed by using the first three terms of
373
+ a summation of cosines. It was designed to have close to the minimal
374
+ leakage possible. It is close to optimal, only slightly worse than a
375
+ Kaiser window.
376
+
377
+ Parameters
378
+ ----------
379
+ M : int
380
+ Number of points in the output window. If zero, an empty array
381
+ is returned. An exception is thrown when it is negative.
382
+ sym : bool, optional
383
+ When True (default), generates a symmetric window, for use in filter
384
+ design.
385
+ When False, generates a periodic window, for use in spectral analysis.
386
+
387
+ Returns
388
+ -------
389
+ w : ndarray
390
+ The window, with the maximum value normalized to 1 (though the value 1
391
+ does not appear if `M` is even and `sym` is True).
392
+
393
+ Notes
394
+ -----
395
+ The Blackman window is defined as
396
+
397
+ .. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
398
+
399
+ The "exact Blackman" window was designed to null out the third and fourth
400
+ sidelobes, but has discontinuities at the boundaries, resulting in a
401
+ 6 dB/oct fall-off. This window is an approximation of the "exact" window,
402
+ which does not null the sidelobes as well, but is smooth at the edges,
403
+ improving the fall-off rate to 18 dB/oct. [3]_
404
+
405
+ Most references to the Blackman window come from the signal processing
406
+ literature, where it is used as one of many windowing functions for
407
+ smoothing values. It is also known as an apodization (which means
408
+ "removing the foot", i.e. smoothing discontinuities at the beginning
409
+ and end of the sampled signal) or tapering function. It is known as a
410
+ "near optimal" tapering function, almost as good (by some measures)
411
+ as the Kaiser window.
412
+
413
+ References
414
+ ----------
415
+ .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
416
+ spectra, Dover Publications, New York.
417
+ .. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
418
+ Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
419
+ .. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
420
+ Analysis with the Discrete Fourier Transform". Proceedings of the
421
+ IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`.
422
+
423
+ Examples
424
+ --------
425
+ Plot the window and its frequency response:
426
+
427
+ >>> import numpy as np
428
+ >>> from scipy import signal
429
+ >>> from scipy.fft import fft, fftshift
430
+ >>> import matplotlib.pyplot as plt
431
+
432
+ >>> window = signal.windows.blackman(51)
433
+ >>> plt.plot(window)
434
+ >>> plt.title("Blackman window")
435
+ >>> plt.ylabel("Amplitude")
436
+ >>> plt.xlabel("Sample")
437
+
438
+ >>> plt.figure()
439
+ >>> A = fft(window, 2048) / (len(window)/2.0)
440
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
441
+ >>> response = np.abs(fftshift(A / abs(A).max()))
442
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
443
+ >>> plt.plot(freq, response)
444
+ >>> plt.axis([-0.5, 0.5, -120, 0])
445
+ >>> plt.title("Frequency response of the Blackman window")
446
+ >>> plt.ylabel("Normalized magnitude [dB]")
447
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
448
+
449
+ """
450
+ # Docstring adapted from NumPy's blackman function
451
+ return general_cosine(M, [0.42, 0.50, 0.08], sym)
452
+
453
+
454
+ def nuttall(M, sym=True):
455
+ """Return a minimum 4-term Blackman-Harris window according to Nuttall.
456
+
457
+ This variation is called "Nuttall4c" by Heinzel. [2]_
458
+
459
+ Parameters
460
+ ----------
461
+ M : int
462
+ Number of points in the output window. If zero, an empty array
463
+ is returned. An exception is thrown when it is negative.
464
+ sym : bool, optional
465
+ When True (default), generates a symmetric window, for use in filter
466
+ design.
467
+ When False, generates a periodic window, for use in spectral analysis.
468
+
469
+ Returns
470
+ -------
471
+ w : ndarray
472
+ The window, with the maximum value normalized to 1 (though the value 1
473
+ does not appear if `M` is even and `sym` is True).
474
+
475
+ References
476
+ ----------
477
+ .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
478
+ Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
479
+ no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
480
+ .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
481
+ Discrete Fourier transform (DFT), including a comprehensive list of
482
+ window functions and some new flat-top windows", February 15, 2002
483
+ https://holometer.fnal.gov/GH_FFT.pdf
484
+
485
+ Examples
486
+ --------
487
+ Plot the window and its frequency response:
488
+
489
+ >>> import numpy as np
490
+ >>> from scipy import signal
491
+ >>> from scipy.fft import fft, fftshift
492
+ >>> import matplotlib.pyplot as plt
493
+
494
+ >>> window = signal.windows.nuttall(51)
495
+ >>> plt.plot(window)
496
+ >>> plt.title("Nuttall window")
497
+ >>> plt.ylabel("Amplitude")
498
+ >>> plt.xlabel("Sample")
499
+
500
+ >>> plt.figure()
501
+ >>> A = fft(window, 2048) / (len(window)/2.0)
502
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
503
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
504
+ >>> plt.plot(freq, response)
505
+ >>> plt.axis([-0.5, 0.5, -120, 0])
506
+ >>> plt.title("Frequency response of the Nuttall window")
507
+ >>> plt.ylabel("Normalized magnitude [dB]")
508
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
509
+
510
+ """
511
+ return general_cosine(M, [0.3635819, 0.4891775, 0.1365995, 0.0106411], sym)
512
+
513
+
514
+ def blackmanharris(M, sym=True):
515
+ """Return a minimum 4-term Blackman-Harris window.
516
+
517
+ Parameters
518
+ ----------
519
+ M : int
520
+ Number of points in the output window. If zero, an empty array
521
+ is returned. An exception is thrown when it is negative.
522
+ sym : bool, optional
523
+ When True (default), generates a symmetric window, for use in filter
524
+ design.
525
+ When False, generates a periodic window, for use in spectral analysis.
526
+
527
+ Returns
528
+ -------
529
+ w : ndarray
530
+ The window, with the maximum value normalized to 1 (though the value 1
531
+ does not appear if `M` is even and `sym` is True).
532
+
533
+ Examples
534
+ --------
535
+ Plot the window and its frequency response:
536
+
537
+ >>> import numpy as np
538
+ >>> from scipy import signal
539
+ >>> from scipy.fft import fft, fftshift
540
+ >>> import matplotlib.pyplot as plt
541
+
542
+ >>> window = signal.windows.blackmanharris(51)
543
+ >>> plt.plot(window)
544
+ >>> plt.title("Blackman-Harris window")
545
+ >>> plt.ylabel("Amplitude")
546
+ >>> plt.xlabel("Sample")
547
+
548
+ >>> plt.figure()
549
+ >>> A = fft(window, 2048) / (len(window)/2.0)
550
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
551
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
552
+ >>> plt.plot(freq, response)
553
+ >>> plt.axis([-0.5, 0.5, -120, 0])
554
+ >>> plt.title("Frequency response of the Blackman-Harris window")
555
+ >>> plt.ylabel("Normalized magnitude [dB]")
556
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
557
+
558
+ """
559
+ return general_cosine(M, [0.35875, 0.48829, 0.14128, 0.01168], sym)
560
+
561
+
562
+ def flattop(M, sym=True):
563
+ """Return a flat top window.
564
+
565
+ Parameters
566
+ ----------
567
+ M : int
568
+ Number of points in the output window. If zero, an empty array
569
+ is returned. An exception is thrown when it is negative.
570
+ sym : bool, optional
571
+ When True (default), generates a symmetric window, for use in filter
572
+ design.
573
+ When False, generates a periodic window, for use in spectral analysis.
574
+
575
+ Returns
576
+ -------
577
+ w : ndarray
578
+ The window, with the maximum value normalized to 1 (though the value 1
579
+ does not appear if `M` is even and `sym` is True).
580
+
581
+ Notes
582
+ -----
583
+ Flat top windows are used for taking accurate measurements of signal
584
+ amplitude in the frequency domain, with minimal scalloping error from the
585
+ center of a frequency bin to its edges, compared to others. This is a
586
+ 5th-order cosine window, with the 5 terms optimized to make the main lobe
587
+ maximally flat. [1]_
588
+
589
+ References
590
+ ----------
591
+ .. [1] D'Antona, Gabriele, and A. Ferrero, "Digital Signal Processing for
592
+ Measurement Systems", Springer Media, 2006, p. 70
593
+ :doi:`10.1007/0-387-28666-7`.
594
+
595
+ Examples
596
+ --------
597
+ Plot the window and its frequency response:
598
+
599
+ >>> import numpy as np
600
+ >>> from scipy import signal
601
+ >>> from scipy.fft import fft, fftshift
602
+ >>> import matplotlib.pyplot as plt
603
+
604
+ >>> window = signal.windows.flattop(51)
605
+ >>> plt.plot(window)
606
+ >>> plt.title("Flat top window")
607
+ >>> plt.ylabel("Amplitude")
608
+ >>> plt.xlabel("Sample")
609
+
610
+ >>> plt.figure()
611
+ >>> A = fft(window, 2048) / (len(window)/2.0)
612
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
613
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
614
+ >>> plt.plot(freq, response)
615
+ >>> plt.axis([-0.5, 0.5, -120, 0])
616
+ >>> plt.title("Frequency response of the flat top window")
617
+ >>> plt.ylabel("Normalized magnitude [dB]")
618
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
619
+
620
+ """
621
+ a = [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368]
622
+ return general_cosine(M, a, sym)
623
+
624
+
625
+ def bartlett(M, sym=True):
626
+ r"""
627
+ Return a Bartlett window.
628
+
629
+ The Bartlett window is very similar to a triangular window, except
630
+ that the end points are at zero. It is often used in signal
631
+ processing for tapering a signal, without generating too much
632
+ ripple in the frequency domain.
633
+
634
+ Parameters
635
+ ----------
636
+ M : int
637
+ Number of points in the output window. If zero, an empty array
638
+ is returned. An exception is thrown when it is negative.
639
+ sym : bool, optional
640
+ When True (default), generates a symmetric window, for use in filter
641
+ design.
642
+ When False, generates a periodic window, for use in spectral analysis.
643
+
644
+ Returns
645
+ -------
646
+ w : ndarray
647
+ The triangular window, with the first and last samples equal to zero
648
+ and the maximum value normalized to 1 (though the value 1 does not
649
+ appear if `M` is even and `sym` is True).
650
+
651
+ See Also
652
+ --------
653
+ triang : A triangular window that does not touch zero at the ends
654
+
655
+ Notes
656
+ -----
657
+ The Bartlett window is defined as
658
+
659
+ .. math:: w(n) = \frac{2}{M-1} \left(
660
+ \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
661
+ \right)
662
+
663
+ Most references to the Bartlett window come from the signal
664
+ processing literature, where it is used as one of many windowing
665
+ functions for smoothing values. Note that convolution with this
666
+ window produces linear interpolation. It is also known as an
667
+ apodization (which means"removing the foot", i.e. smoothing
668
+ discontinuities at the beginning and end of the sampled signal) or
669
+ tapering function. The Fourier transform of the Bartlett is the product
670
+ of two sinc functions.
671
+ Note the excellent discussion in Kanasewich. [2]_
672
+
673
+ References
674
+ ----------
675
+ .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
676
+ Biometrika 37, 1-16, 1950.
677
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
678
+ The University of Alberta Press, 1975, pp. 109-110.
679
+ .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
680
+ Processing", Prentice-Hall, 1999, pp. 468-471.
681
+ .. [4] Wikipedia, "Window function",
682
+ https://en.wikipedia.org/wiki/Window_function
683
+ .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
684
+ "Numerical Recipes", Cambridge University Press, 1986, page 429.
685
+
686
+ Examples
687
+ --------
688
+ Plot the window and its frequency response:
689
+
690
+ >>> import numpy as np
691
+ >>> from scipy import signal
692
+ >>> from scipy.fft import fft, fftshift
693
+ >>> import matplotlib.pyplot as plt
694
+
695
+ >>> window = signal.windows.bartlett(51)
696
+ >>> plt.plot(window)
697
+ >>> plt.title("Bartlett window")
698
+ >>> plt.ylabel("Amplitude")
699
+ >>> plt.xlabel("Sample")
700
+
701
+ >>> plt.figure()
702
+ >>> A = fft(window, 2048) / (len(window)/2.0)
703
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
704
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
705
+ >>> plt.plot(freq, response)
706
+ >>> plt.axis([-0.5, 0.5, -120, 0])
707
+ >>> plt.title("Frequency response of the Bartlett window")
708
+ >>> plt.ylabel("Normalized magnitude [dB]")
709
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
710
+
711
+ """
712
+ # Docstring adapted from NumPy's bartlett function
713
+ if _len_guards(M):
714
+ return np.ones(M)
715
+ M, needs_trunc = _extend(M, sym)
716
+
717
+ n = np.arange(0, M)
718
+ w = np.where(np.less_equal(n, (M - 1) / 2.0),
719
+ 2.0 * n / (M - 1), 2.0 - 2.0 * n / (M - 1))
720
+
721
+ return _truncate(w, needs_trunc)
722
+
723
+
724
+ def hann(M, sym=True):
725
+ r"""
726
+ Return a Hann window.
727
+
728
+ The Hann window is a taper formed by using a raised cosine or sine-squared
729
+ with ends that touch zero.
730
+
731
+ Parameters
732
+ ----------
733
+ M : int
734
+ Number of points in the output window. If zero, an empty array
735
+ is returned. An exception is thrown when it is negative.
736
+ sym : bool, optional
737
+ When True (default), generates a symmetric window, for use in filter
738
+ design.
739
+ When False, generates a periodic window, for use in spectral analysis.
740
+
741
+ Returns
742
+ -------
743
+ w : ndarray
744
+ The window, with the maximum value normalized to 1 (though the value 1
745
+ does not appear if `M` is even and `sym` is True).
746
+
747
+ Notes
748
+ -----
749
+ The Hann window is defined as
750
+
751
+ .. math:: w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi{n}}{M-1}\right)
752
+ \qquad 0 \leq n \leq M-1
753
+
754
+ The window was named for Julius von Hann, an Austrian meteorologist. It is
755
+ also known as the Cosine Bell. It is sometimes erroneously referred to as
756
+ the "Hanning" window, from the use of "hann" as a verb in the original
757
+ paper and confusion with the very similar Hamming window.
758
+
759
+ Most references to the Hann window come from the signal processing
760
+ literature, where it is used as one of many windowing functions for
761
+ smoothing values. It is also known as an apodization (which means
762
+ "removing the foot", i.e. smoothing discontinuities at the beginning
763
+ and end of the sampled signal) or tapering function.
764
+
765
+ References
766
+ ----------
767
+ .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
768
+ spectra, Dover Publications, New York.
769
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
770
+ The University of Alberta Press, 1975, pp. 106-108.
771
+ .. [3] Wikipedia, "Window function",
772
+ https://en.wikipedia.org/wiki/Window_function
773
+ .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
774
+ "Numerical Recipes", Cambridge University Press, 1986, page 425.
775
+
776
+ Examples
777
+ --------
778
+ Plot the window and its frequency response:
779
+
780
+ >>> import numpy as np
781
+ >>> from scipy import signal
782
+ >>> from scipy.fft import fft, fftshift
783
+ >>> import matplotlib.pyplot as plt
784
+
785
+ >>> window = signal.windows.hann(51)
786
+ >>> plt.plot(window)
787
+ >>> plt.title("Hann window")
788
+ >>> plt.ylabel("Amplitude")
789
+ >>> plt.xlabel("Sample")
790
+
791
+ >>> plt.figure()
792
+ >>> A = fft(window, 2048) / (len(window)/2.0)
793
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
794
+ >>> response = np.abs(fftshift(A / abs(A).max()))
795
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
796
+ >>> plt.plot(freq, response)
797
+ >>> plt.axis([-0.5, 0.5, -120, 0])
798
+ >>> plt.title("Frequency response of the Hann window")
799
+ >>> plt.ylabel("Normalized magnitude [dB]")
800
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
801
+
802
+ """
803
+ # Docstring adapted from NumPy's hanning function
804
+ return general_hamming(M, 0.5, sym)
805
+
806
+
807
+ def tukey(M, alpha=0.5, sym=True):
808
+ r"""Return a Tukey window, also known as a tapered cosine window.
809
+
810
+ Parameters
811
+ ----------
812
+ M : int
813
+ Number of points in the output window. If zero, an empty array
814
+ is returned. An exception is thrown when it is negative.
815
+ alpha : float, optional
816
+ Shape parameter of the Tukey window, representing the fraction of the
817
+ window inside the cosine tapered region.
818
+ If zero, the Tukey window is equivalent to a rectangular window.
819
+ If one, the Tukey window is equivalent to a Hann window.
820
+ sym : bool, optional
821
+ When True (default), generates a symmetric window, for use in filter
822
+ design.
823
+ When False, generates a periodic window, for use in spectral analysis.
824
+
825
+ Returns
826
+ -------
827
+ w : ndarray
828
+ The window, with the maximum value normalized to 1 (though the value 1
829
+ does not appear if `M` is even and `sym` is True).
830
+
831
+ References
832
+ ----------
833
+ .. [1] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
834
+ Analysis with the Discrete Fourier Transform". Proceedings of the
835
+ IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`
836
+ .. [2] Wikipedia, "Window function",
837
+ https://en.wikipedia.org/wiki/Window_function#Tukey_window
838
+
839
+ Examples
840
+ --------
841
+ Plot the window and its frequency response:
842
+
843
+ >>> import numpy as np
844
+ >>> from scipy import signal
845
+ >>> from scipy.fft import fft, fftshift
846
+ >>> import matplotlib.pyplot as plt
847
+
848
+ >>> window = signal.windows.tukey(51)
849
+ >>> plt.plot(window)
850
+ >>> plt.title("Tukey window")
851
+ >>> plt.ylabel("Amplitude")
852
+ >>> plt.xlabel("Sample")
853
+ >>> plt.ylim([0, 1.1])
854
+
855
+ >>> plt.figure()
856
+ >>> A = fft(window, 2048) / (len(window)/2.0)
857
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
858
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
859
+ >>> plt.plot(freq, response)
860
+ >>> plt.axis([-0.5, 0.5, -120, 0])
861
+ >>> plt.title("Frequency response of the Tukey window")
862
+ >>> plt.ylabel("Normalized magnitude [dB]")
863
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
864
+
865
+ """
866
+ if _len_guards(M):
867
+ return np.ones(M)
868
+
869
+ if alpha <= 0:
870
+ return np.ones(M, 'd')
871
+ elif alpha >= 1.0:
872
+ return hann(M, sym=sym)
873
+
874
+ M, needs_trunc = _extend(M, sym)
875
+
876
+ n = np.arange(0, M)
877
+ width = int(np.floor(alpha*(M-1)/2.0))
878
+ n1 = n[0:width+1]
879
+ n2 = n[width+1:M-width-1]
880
+ n3 = n[M-width-1:]
881
+
882
+ w1 = 0.5 * (1 + np.cos(np.pi * (-1 + 2.0*n1/alpha/(M-1))))
883
+ w2 = np.ones(n2.shape)
884
+ w3 = 0.5 * (1 + np.cos(np.pi * (-2.0/alpha + 1 + 2.0*n3/alpha/(M-1))))
885
+
886
+ w = np.concatenate((w1, w2, w3))
887
+
888
+ return _truncate(w, needs_trunc)
889
+
890
+
891
+ def barthann(M, sym=True):
892
+ """Return a modified Bartlett-Hann window.
893
+
894
+ Parameters
895
+ ----------
896
+ M : int
897
+ Number of points in the output window. If zero, an empty array
898
+ is returned. An exception is thrown when it is negative.
899
+ sym : bool, optional
900
+ When True (default), generates a symmetric window, for use in filter
901
+ design.
902
+ When False, generates a periodic window, for use in spectral analysis.
903
+
904
+ Returns
905
+ -------
906
+ w : ndarray
907
+ The window, with the maximum value normalized to 1 (though the value 1
908
+ does not appear if `M` is even and `sym` is True).
909
+
910
+ Examples
911
+ --------
912
+ Plot the window and its frequency response:
913
+
914
+ >>> import numpy as np
915
+ >>> from scipy import signal
916
+ >>> from scipy.fft import fft, fftshift
917
+ >>> import matplotlib.pyplot as plt
918
+
919
+ >>> window = signal.windows.barthann(51)
920
+ >>> plt.plot(window)
921
+ >>> plt.title("Bartlett-Hann window")
922
+ >>> plt.ylabel("Amplitude")
923
+ >>> plt.xlabel("Sample")
924
+
925
+ >>> plt.figure()
926
+ >>> A = fft(window, 2048) / (len(window)/2.0)
927
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
928
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
929
+ >>> plt.plot(freq, response)
930
+ >>> plt.axis([-0.5, 0.5, -120, 0])
931
+ >>> plt.title("Frequency response of the Bartlett-Hann window")
932
+ >>> plt.ylabel("Normalized magnitude [dB]")
933
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
934
+
935
+ """
936
+ if _len_guards(M):
937
+ return np.ones(M)
938
+ M, needs_trunc = _extend(M, sym)
939
+
940
+ n = np.arange(0, M)
941
+ fac = np.abs(n / (M - 1.0) - 0.5)
942
+ w = 0.62 - 0.48 * fac + 0.38 * np.cos(2 * np.pi * fac)
943
+
944
+ return _truncate(w, needs_trunc)
945
+
946
+
947
+ def general_hamming(M, alpha, sym=True):
948
+ r"""Return a generalized Hamming window.
949
+
950
+ The generalized Hamming window is constructed by multiplying a rectangular
951
+ window by one period of a cosine function [1]_.
952
+
953
+ Parameters
954
+ ----------
955
+ M : int
956
+ Number of points in the output window. If zero, an empty array
957
+ is returned. An exception is thrown when it is negative.
958
+ alpha : float
959
+ The window coefficient, :math:`\alpha`
960
+ sym : bool, optional
961
+ When True (default), generates a symmetric window, for use in filter
962
+ design.
963
+ When False, generates a periodic window, for use in spectral analysis.
964
+
965
+ Returns
966
+ -------
967
+ w : ndarray
968
+ The window, with the maximum value normalized to 1 (though the value 1
969
+ does not appear if `M` is even and `sym` is True).
970
+
971
+ See Also
972
+ --------
973
+ hamming, hann
974
+
975
+ Notes
976
+ -----
977
+ The generalized Hamming window is defined as
978
+
979
+ .. math:: w(n) = \alpha - \left(1 - \alpha\right)
980
+ \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1
981
+
982
+ Both the common Hamming window and Hann window are special cases of the
983
+ generalized Hamming window with :math:`\alpha` = 0.54 and :math:`\alpha` =
984
+ 0.5, respectively [2]_.
985
+
986
+ References
987
+ ----------
988
+ .. [1] DSPRelated, "Generalized Hamming Window Family",
989
+ https://www.dsprelated.com/freebooks/sasp/Generalized_Hamming_Window_Family.html
990
+ .. [2] Wikipedia, "Window function",
991
+ https://en.wikipedia.org/wiki/Window_function
992
+ .. [3] Riccardo Piantanida ESA, "Sentinel-1 Level 1 Detailed Algorithm
993
+ Definition",
994
+ https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Level-1-Detailed-Algorithm-Definition
995
+ .. [4] Matthieu Bourbigot ESA, "Sentinel-1 Product Definition",
996
+ https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Product-Definition
997
+
998
+ Examples
999
+ --------
1000
+ The Sentinel-1A/B Instrument Processing Facility uses generalized Hamming
1001
+ windows in the processing of spaceborne Synthetic Aperture Radar (SAR)
1002
+ data [3]_. The facility uses various values for the :math:`\alpha`
1003
+ parameter based on operating mode of the SAR instrument. Some common
1004
+ :math:`\alpha` values include 0.75, 0.7 and 0.52 [4]_. As an example, we
1005
+ plot these different windows.
1006
+
1007
+ >>> import numpy as np
1008
+ >>> from scipy.signal.windows import general_hamming
1009
+ >>> from scipy.fft import fft, fftshift
1010
+ >>> import matplotlib.pyplot as plt
1011
+
1012
+ >>> fig1, spatial_plot = plt.subplots()
1013
+ >>> spatial_plot.set_title("Generalized Hamming Windows")
1014
+ >>> spatial_plot.set_ylabel("Amplitude")
1015
+ >>> spatial_plot.set_xlabel("Sample")
1016
+
1017
+ >>> fig2, freq_plot = plt.subplots()
1018
+ >>> freq_plot.set_title("Frequency Responses")
1019
+ >>> freq_plot.set_ylabel("Normalized magnitude [dB]")
1020
+ >>> freq_plot.set_xlabel("Normalized frequency [cycles per sample]")
1021
+
1022
+ >>> for alpha in [0.75, 0.7, 0.52]:
1023
+ ... window = general_hamming(41, alpha)
1024
+ ... spatial_plot.plot(window, label="{:.2f}".format(alpha))
1025
+ ... A = fft(window, 2048) / (len(window)/2.0)
1026
+ ... freq = np.linspace(-0.5, 0.5, len(A))
1027
+ ... response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1028
+ ... freq_plot.plot(freq, response, label="{:.2f}".format(alpha))
1029
+ >>> freq_plot.legend(loc="upper right")
1030
+ >>> spatial_plot.legend(loc="upper right")
1031
+
1032
+ """
1033
+ return general_cosine(M, [alpha, 1. - alpha], sym)
1034
+
1035
+
1036
+ def hamming(M, sym=True):
1037
+ r"""Return a Hamming window.
1038
+
1039
+ The Hamming window is a taper formed by using a raised cosine with
1040
+ non-zero endpoints, optimized to minimize the nearest side lobe.
1041
+
1042
+ Parameters
1043
+ ----------
1044
+ M : int
1045
+ Number of points in the output window. If zero, an empty array
1046
+ is returned. An exception is thrown when it is negative.
1047
+ sym : bool, optional
1048
+ When True (default), generates a symmetric window, for use in filter
1049
+ design.
1050
+ When False, generates a periodic window, for use in spectral analysis.
1051
+
1052
+ Returns
1053
+ -------
1054
+ w : ndarray
1055
+ The window, with the maximum value normalized to 1 (though the value 1
1056
+ does not appear if `M` is even and `sym` is True).
1057
+
1058
+ Notes
1059
+ -----
1060
+ The Hamming window is defined as
1061
+
1062
+ .. math:: w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right)
1063
+ \qquad 0 \leq n \leq M-1
1064
+
1065
+ The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and
1066
+ is described in Blackman and Tukey. It was recommended for smoothing the
1067
+ truncated autocovariance function in the time domain.
1068
+ Most references to the Hamming window come from the signal processing
1069
+ literature, where it is used as one of many windowing functions for
1070
+ smoothing values. It is also known as an apodization (which means
1071
+ "removing the foot", i.e. smoothing discontinuities at the beginning
1072
+ and end of the sampled signal) or tapering function.
1073
+
1074
+ References
1075
+ ----------
1076
+ .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
1077
+ spectra, Dover Publications, New York.
1078
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
1079
+ University of Alberta Press, 1975, pp. 109-110.
1080
+ .. [3] Wikipedia, "Window function",
1081
+ https://en.wikipedia.org/wiki/Window_function
1082
+ .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
1083
+ "Numerical Recipes", Cambridge University Press, 1986, page 425.
1084
+
1085
+ Examples
1086
+ --------
1087
+ Plot the window and its frequency response:
1088
+
1089
+ >>> import numpy as np
1090
+ >>> from scipy import signal
1091
+ >>> from scipy.fft import fft, fftshift
1092
+ >>> import matplotlib.pyplot as plt
1093
+
1094
+ >>> window = signal.windows.hamming(51)
1095
+ >>> plt.plot(window)
1096
+ >>> plt.title("Hamming window")
1097
+ >>> plt.ylabel("Amplitude")
1098
+ >>> plt.xlabel("Sample")
1099
+
1100
+ >>> plt.figure()
1101
+ >>> A = fft(window, 2048) / (len(window)/2.0)
1102
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1103
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1104
+ >>> plt.plot(freq, response)
1105
+ >>> plt.axis([-0.5, 0.5, -120, 0])
1106
+ >>> plt.title("Frequency response of the Hamming window")
1107
+ >>> plt.ylabel("Normalized magnitude [dB]")
1108
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1109
+
1110
+ """
1111
+ # Docstring adapted from NumPy's hamming function
1112
+ return general_hamming(M, 0.54, sym)
1113
+
1114
+
1115
+ def kaiser(M, beta, sym=True):
1116
+ r"""Return a Kaiser window.
1117
+
1118
+ The Kaiser window is a taper formed by using a Bessel function.
1119
+
1120
+ Parameters
1121
+ ----------
1122
+ M : int
1123
+ Number of points in the output window. If zero, an empty array
1124
+ is returned. An exception is thrown when it is negative.
1125
+ beta : float
1126
+ Shape parameter, determines trade-off between main-lobe width and
1127
+ side lobe level. As beta gets large, the window narrows.
1128
+ sym : bool, optional
1129
+ When True (default), generates a symmetric window, for use in filter
1130
+ design.
1131
+ When False, generates a periodic window, for use in spectral analysis.
1132
+
1133
+ Returns
1134
+ -------
1135
+ w : ndarray
1136
+ The window, with the maximum value normalized to 1 (though the value 1
1137
+ does not appear if `M` is even and `sym` is True).
1138
+
1139
+ Notes
1140
+ -----
1141
+ The Kaiser window is defined as
1142
+
1143
+ .. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
1144
+ \right)/I_0(\beta)
1145
+
1146
+ with
1147
+
1148
+ .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},
1149
+
1150
+ where :math:`I_0` is the modified zeroth-order Bessel function.
1151
+
1152
+ The Kaiser was named for Jim Kaiser, who discovered a simple approximation
1153
+ to the DPSS window based on Bessel functions.
1154
+ The Kaiser window is a very good approximation to the Digital Prolate
1155
+ Spheroidal Sequence, or Slepian window, which is the transform which
1156
+ maximizes the energy in the main lobe of the window relative to total
1157
+ energy.
1158
+
1159
+ The Kaiser can approximate other windows by varying the beta parameter.
1160
+ (Some literature uses alpha = beta/pi.) [4]_
1161
+
1162
+ ==== =======================
1163
+ beta Window shape
1164
+ ==== =======================
1165
+ 0 Rectangular
1166
+ 5 Similar to a Hamming
1167
+ 6 Similar to a Hann
1168
+ 8.6 Similar to a Blackman
1169
+ ==== =======================
1170
+
1171
+ A beta value of 14 is probably a good starting point. Note that as beta
1172
+ gets large, the window narrows, and so the number of samples needs to be
1173
+ large enough to sample the increasingly narrow spike, otherwise NaNs will
1174
+ be returned.
1175
+
1176
+ Most references to the Kaiser window come from the signal processing
1177
+ literature, where it is used as one of many windowing functions for
1178
+ smoothing values. It is also known as an apodization (which means
1179
+ "removing the foot", i.e. smoothing discontinuities at the beginning
1180
+ and end of the sampled signal) or tapering function.
1181
+
1182
+ References
1183
+ ----------
1184
+ .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
1185
+ digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
1186
+ John Wiley and Sons, New York, (1966).
1187
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
1188
+ University of Alberta Press, 1975, pp. 177-178.
1189
+ .. [3] Wikipedia, "Window function",
1190
+ https://en.wikipedia.org/wiki/Window_function
1191
+ .. [4] F. J. Harris, "On the use of windows for harmonic analysis with the
1192
+ discrete Fourier transform," Proceedings of the IEEE, vol. 66,
1193
+ no. 1, pp. 51-83, Jan. 1978. :doi:`10.1109/PROC.1978.10837`.
1194
+
1195
+ Examples
1196
+ --------
1197
+ Plot the window and its frequency response:
1198
+
1199
+ >>> import numpy as np
1200
+ >>> from scipy import signal
1201
+ >>> from scipy.fft import fft, fftshift
1202
+ >>> import matplotlib.pyplot as plt
1203
+
1204
+ >>> window = signal.windows.kaiser(51, beta=14)
1205
+ >>> plt.plot(window)
1206
+ >>> plt.title(r"Kaiser window ($\beta$=14)")
1207
+ >>> plt.ylabel("Amplitude")
1208
+ >>> plt.xlabel("Sample")
1209
+
1210
+ >>> plt.figure()
1211
+ >>> A = fft(window, 2048) / (len(window)/2.0)
1212
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1213
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1214
+ >>> plt.plot(freq, response)
1215
+ >>> plt.axis([-0.5, 0.5, -120, 0])
1216
+ >>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)")
1217
+ >>> plt.ylabel("Normalized magnitude [dB]")
1218
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1219
+
1220
+ """
1221
+ # Docstring adapted from NumPy's kaiser function
1222
+ if _len_guards(M):
1223
+ return np.ones(M)
1224
+ M, needs_trunc = _extend(M, sym)
1225
+
1226
+ n = np.arange(0, M)
1227
+ alpha = (M - 1) / 2.0
1228
+ w = (special.i0(beta * np.sqrt(1 - ((n - alpha) / alpha) ** 2.0)) /
1229
+ special.i0(beta))
1230
+
1231
+ return _truncate(w, needs_trunc)
1232
+
1233
+
1234
+ def kaiser_bessel_derived(M, beta, *, sym=True):
1235
+ """Return a Kaiser-Bessel derived window.
1236
+
1237
+ Parameters
1238
+ ----------
1239
+ M : int
1240
+ Number of points in the output window. If zero, an empty array
1241
+ is returned. An exception is thrown when it is negative.
1242
+ Note that this window is only defined for an even
1243
+ number of points.
1244
+ beta : float
1245
+ Kaiser window shape parameter.
1246
+ sym : bool, optional
1247
+ This parameter only exists to comply with the interface offered by
1248
+ the other window functions and to be callable by `get_window`.
1249
+ When True (default), generates a symmetric window, for use in filter
1250
+ design.
1251
+
1252
+ Returns
1253
+ -------
1254
+ w : ndarray
1255
+ The window, normalized to fulfil the Princen-Bradley condition.
1256
+
1257
+ See Also
1258
+ --------
1259
+ kaiser
1260
+
1261
+ Notes
1262
+ -----
1263
+ It is designed to be suitable for use with the modified discrete cosine
1264
+ transform (MDCT) and is mainly used in audio signal processing and
1265
+ audio coding.
1266
+
1267
+ .. versionadded:: 1.9.0
1268
+
1269
+ References
1270
+ ----------
1271
+ .. [1] Bosi, Marina, and Richard E. Goldberg. Introduction to Digital
1272
+ Audio Coding and Standards. Dordrecht: Kluwer, 2003.
1273
+ .. [2] Wikipedia, "Kaiser window",
1274
+ https://en.wikipedia.org/wiki/Kaiser_window
1275
+
1276
+ Examples
1277
+ --------
1278
+ Plot the Kaiser-Bessel derived window based on the wikipedia
1279
+ reference [2]_:
1280
+
1281
+ >>> import numpy as np
1282
+ >>> from scipy import signal
1283
+ >>> import matplotlib.pyplot as plt
1284
+ >>> fig, ax = plt.subplots()
1285
+ >>> N = 50
1286
+ >>> for alpha in [0.64, 2.55, 7.64, 31.83]:
1287
+ ... ax.plot(signal.windows.kaiser_bessel_derived(2*N, np.pi*alpha),
1288
+ ... label=f"{alpha=}")
1289
+ >>> ax.grid(True)
1290
+ >>> ax.set_title("Kaiser-Bessel derived window")
1291
+ >>> ax.set_ylabel("Amplitude")
1292
+ >>> ax.set_xlabel("Sample")
1293
+ >>> ax.set_xticks([0, N, 2*N-1])
1294
+ >>> ax.set_xticklabels(["0", "N", "2N+1"]) # doctest: +SKIP
1295
+ >>> ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.707, 0.8, 1.0])
1296
+ >>> fig.legend(loc="center")
1297
+ >>> fig.tight_layout()
1298
+ >>> fig.show()
1299
+ """
1300
+ if not sym:
1301
+ raise ValueError(
1302
+ "Kaiser-Bessel Derived windows are only defined for symmetric "
1303
+ "shapes"
1304
+ )
1305
+ elif M < 1:
1306
+ return np.array([])
1307
+ elif M % 2:
1308
+ raise ValueError(
1309
+ "Kaiser-Bessel Derived windows are only defined for even number "
1310
+ "of points"
1311
+ )
1312
+
1313
+ kaiser_window = kaiser(M // 2 + 1, beta)
1314
+ csum = np.cumsum(kaiser_window)
1315
+ half_window = np.sqrt(csum[:-1] / csum[-1])
1316
+ w = np.concatenate((half_window, half_window[::-1]), axis=0)
1317
+ return w
1318
+
1319
+
1320
+ def gaussian(M, std, sym=True):
1321
+ r"""Return a Gaussian window.
1322
+
1323
+ Parameters
1324
+ ----------
1325
+ M : int
1326
+ Number of points in the output window. If zero, an empty array
1327
+ is returned. An exception is thrown when it is negative.
1328
+ std : float
1329
+ The standard deviation, sigma.
1330
+ sym : bool, optional
1331
+ When True (default), generates a symmetric window, for use in filter
1332
+ design.
1333
+ When False, generates a periodic window, for use in spectral analysis.
1334
+
1335
+ Returns
1336
+ -------
1337
+ w : ndarray
1338
+ The window, with the maximum value normalized to 1 (though the value 1
1339
+ does not appear if `M` is even and `sym` is True).
1340
+
1341
+ Notes
1342
+ -----
1343
+ The Gaussian window is defined as
1344
+
1345
+ .. math:: w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 }
1346
+
1347
+ Examples
1348
+ --------
1349
+ Plot the window and its frequency response:
1350
+
1351
+ >>> import numpy as np
1352
+ >>> from scipy import signal
1353
+ >>> from scipy.fft import fft, fftshift
1354
+ >>> import matplotlib.pyplot as plt
1355
+
1356
+ >>> window = signal.windows.gaussian(51, std=7)
1357
+ >>> plt.plot(window)
1358
+ >>> plt.title(r"Gaussian window ($\sigma$=7)")
1359
+ >>> plt.ylabel("Amplitude")
1360
+ >>> plt.xlabel("Sample")
1361
+
1362
+ >>> plt.figure()
1363
+ >>> A = fft(window, 2048) / (len(window)/2.0)
1364
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1365
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1366
+ >>> plt.plot(freq, response)
1367
+ >>> plt.axis([-0.5, 0.5, -120, 0])
1368
+ >>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)")
1369
+ >>> plt.ylabel("Normalized magnitude [dB]")
1370
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1371
+
1372
+ """
1373
+ if _len_guards(M):
1374
+ return np.ones(M)
1375
+ M, needs_trunc = _extend(M, sym)
1376
+
1377
+ n = np.arange(0, M) - (M - 1.0) / 2.0
1378
+ sig2 = 2 * std * std
1379
+ w = np.exp(-n ** 2 / sig2)
1380
+
1381
+ return _truncate(w, needs_trunc)
1382
+
1383
+
1384
+ def general_gaussian(M, p, sig, sym=True):
1385
+ r"""Return a window with a generalized Gaussian shape.
1386
+
1387
+ Parameters
1388
+ ----------
1389
+ M : int
1390
+ Number of points in the output window. If zero, an empty array
1391
+ is returned. An exception is thrown when it is negative.
1392
+ p : float
1393
+ Shape parameter. p = 1 is identical to `gaussian`, p = 0.5 is
1394
+ the same shape as the Laplace distribution.
1395
+ sig : float
1396
+ The standard deviation, sigma.
1397
+ sym : bool, optional
1398
+ When True (default), generates a symmetric window, for use in filter
1399
+ design.
1400
+ When False, generates a periodic window, for use in spectral analysis.
1401
+
1402
+ Returns
1403
+ -------
1404
+ w : ndarray
1405
+ The window, with the maximum value normalized to 1 (though the value 1
1406
+ does not appear if `M` is even and `sym` is True).
1407
+
1408
+ Notes
1409
+ -----
1410
+ The generalized Gaussian window is defined as
1411
+
1412
+ .. math:: w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} }
1413
+
1414
+ the half-power point is at
1415
+
1416
+ .. math:: (2 \log(2))^{1/(2 p)} \sigma
1417
+
1418
+ Examples
1419
+ --------
1420
+ Plot the window and its frequency response:
1421
+
1422
+ >>> import numpy as np
1423
+ >>> from scipy import signal
1424
+ >>> from scipy.fft import fft, fftshift
1425
+ >>> import matplotlib.pyplot as plt
1426
+
1427
+ >>> window = signal.windows.general_gaussian(51, p=1.5, sig=7)
1428
+ >>> plt.plot(window)
1429
+ >>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)")
1430
+ >>> plt.ylabel("Amplitude")
1431
+ >>> plt.xlabel("Sample")
1432
+
1433
+ >>> plt.figure()
1434
+ >>> A = fft(window, 2048) / (len(window)/2.0)
1435
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1436
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1437
+ >>> plt.plot(freq, response)
1438
+ >>> plt.axis([-0.5, 0.5, -120, 0])
1439
+ >>> plt.title(r"Freq. resp. of the gen. Gaussian "
1440
+ ... r"window (p=1.5, $\sigma$=7)")
1441
+ >>> plt.ylabel("Normalized magnitude [dB]")
1442
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1443
+
1444
+ """
1445
+ if _len_guards(M):
1446
+ return np.ones(M)
1447
+ M, needs_trunc = _extend(M, sym)
1448
+
1449
+ n = np.arange(0, M) - (M - 1.0) / 2.0
1450
+ w = np.exp(-0.5 * np.abs(n / sig) ** (2 * p))
1451
+
1452
+ return _truncate(w, needs_trunc)
1453
+
1454
+
1455
+ # `chebwin` contributed by Kumar Appaiah.
1456
+ def chebwin(M, at, sym=True):
1457
+ r"""Return a Dolph-Chebyshev window.
1458
+
1459
+ Parameters
1460
+ ----------
1461
+ M : int
1462
+ Number of points in the output window. If zero, an empty array
1463
+ is returned. An exception is thrown when it is negative.
1464
+ at : float
1465
+ Attenuation (in dB).
1466
+ sym : bool, optional
1467
+ When True (default), generates a symmetric window, for use in filter
1468
+ design.
1469
+ When False, generates a periodic window, for use in spectral analysis.
1470
+
1471
+ Returns
1472
+ -------
1473
+ w : ndarray
1474
+ The window, with the maximum value always normalized to 1
1475
+
1476
+ Notes
1477
+ -----
1478
+ This window optimizes for the narrowest main lobe width for a given order
1479
+ `M` and sidelobe equiripple attenuation `at`, using Chebyshev
1480
+ polynomials. It was originally developed by Dolph to optimize the
1481
+ directionality of radio antenna arrays.
1482
+
1483
+ Unlike most windows, the Dolph-Chebyshev is defined in terms of its
1484
+ frequency response:
1485
+
1486
+ .. math:: W(k) = \frac
1487
+ {\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}}
1488
+ {\cosh[M \cosh^{-1}(\beta)]}
1489
+
1490
+ where
1491
+
1492
+ .. math:: \beta = \cosh \left [\frac{1}{M}
1493
+ \cosh^{-1}(10^\frac{A}{20}) \right ]
1494
+
1495
+ and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`).
1496
+
1497
+ The time domain window is then generated using the IFFT, so
1498
+ power-of-two `M` are the fastest to generate, and prime number `M` are
1499
+ the slowest.
1500
+
1501
+ The equiripple condition in the frequency domain creates impulses in the
1502
+ time domain, which appear at the ends of the window.
1503
+
1504
+ References
1505
+ ----------
1506
+ .. [1] C. Dolph, "A current distribution for broadside arrays which
1507
+ optimizes the relationship between beam width and side-lobe level",
1508
+ Proceedings of the IEEE, Vol. 34, Issue 6
1509
+ .. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter",
1510
+ American Meteorological Society (April 1997)
1511
+ http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf
1512
+ .. [3] F. J. Harris, "On the use of windows for harmonic analysis with the
1513
+ discrete Fourier transforms", Proceedings of the IEEE, Vol. 66,
1514
+ No. 1, January 1978
1515
+
1516
+ Examples
1517
+ --------
1518
+ Plot the window and its frequency response:
1519
+
1520
+ >>> import numpy as np
1521
+ >>> from scipy import signal
1522
+ >>> from scipy.fft import fft, fftshift
1523
+ >>> import matplotlib.pyplot as plt
1524
+
1525
+ >>> window = signal.windows.chebwin(51, at=100)
1526
+ >>> plt.plot(window)
1527
+ >>> plt.title("Dolph-Chebyshev window (100 dB)")
1528
+ >>> plt.ylabel("Amplitude")
1529
+ >>> plt.xlabel("Sample")
1530
+
1531
+ >>> plt.figure()
1532
+ >>> A = fft(window, 2048) / (len(window)/2.0)
1533
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1534
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1535
+ >>> plt.plot(freq, response)
1536
+ >>> plt.axis([-0.5, 0.5, -120, 0])
1537
+ >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)")
1538
+ >>> plt.ylabel("Normalized magnitude [dB]")
1539
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1540
+
1541
+ """
1542
+ if np.abs(at) < 45:
1543
+ warnings.warn("This window is not suitable for spectral analysis "
1544
+ "for attenuation values lower than about 45dB because "
1545
+ "the equivalent noise bandwidth of a Chebyshev window "
1546
+ "does not grow monotonically with increasing sidelobe "
1547
+ "attenuation when the attenuation is smaller than "
1548
+ "about 45 dB.",
1549
+ stacklevel=2)
1550
+ if _len_guards(M):
1551
+ return np.ones(M)
1552
+ M, needs_trunc = _extend(M, sym)
1553
+
1554
+ # compute the parameter beta
1555
+ order = M - 1.0
1556
+ beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.)))
1557
+ k = np.r_[0:M] * 1.0
1558
+ x = beta * np.cos(np.pi * k / M)
1559
+ # Find the window's DFT coefficients
1560
+ # Use analytic definition of Chebyshev polynomial instead of expansion
1561
+ # from scipy.special. Using the expansion in scipy.special leads to errors.
1562
+ p = np.zeros(x.shape)
1563
+ p[x > 1] = np.cosh(order * np.arccosh(x[x > 1]))
1564
+ p[x < -1] = (2 * (M % 2) - 1) * np.cosh(order * np.arccosh(-x[x < -1]))
1565
+ p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1]))
1566
+
1567
+ # Appropriate IDFT and filling up
1568
+ # depending on even/odd M
1569
+ if M % 2:
1570
+ w = np.real(sp_fft.fft(p))
1571
+ n = (M + 1) // 2
1572
+ w = w[:n]
1573
+ w = np.concatenate((w[n - 1:0:-1], w))
1574
+ else:
1575
+ p = p * np.exp(1.j * np.pi / M * np.r_[0:M])
1576
+ w = np.real(sp_fft.fft(p))
1577
+ n = M // 2 + 1
1578
+ w = np.concatenate((w[n - 1:0:-1], w[1:n]))
1579
+ w = w / max(w)
1580
+
1581
+ return _truncate(w, needs_trunc)
1582
+
1583
+
1584
+ def cosine(M, sym=True):
1585
+ """Return a window with a simple cosine shape.
1586
+
1587
+ Parameters
1588
+ ----------
1589
+ M : int
1590
+ Number of points in the output window. If zero, an empty array
1591
+ is returned. An exception is thrown when it is negative.
1592
+ sym : bool, optional
1593
+ When True (default), generates a symmetric window, for use in filter
1594
+ design.
1595
+ When False, generates a periodic window, for use in spectral analysis.
1596
+
1597
+ Returns
1598
+ -------
1599
+ w : ndarray
1600
+ The window, with the maximum value normalized to 1 (though the value 1
1601
+ does not appear if `M` is even and `sym` is True).
1602
+
1603
+ Notes
1604
+ -----
1605
+
1606
+ .. versionadded:: 0.13.0
1607
+
1608
+ Examples
1609
+ --------
1610
+ Plot the window and its frequency response:
1611
+
1612
+ >>> import numpy as np
1613
+ >>> from scipy import signal
1614
+ >>> from scipy.fft import fft, fftshift
1615
+ >>> import matplotlib.pyplot as plt
1616
+
1617
+ >>> window = signal.windows.cosine(51)
1618
+ >>> plt.plot(window)
1619
+ >>> plt.title("Cosine window")
1620
+ >>> plt.ylabel("Amplitude")
1621
+ >>> plt.xlabel("Sample")
1622
+
1623
+ >>> plt.figure()
1624
+ >>> A = fft(window, 2047) / (len(window)/2.0)
1625
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1626
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1627
+ >>> plt.plot(freq, response)
1628
+ >>> plt.axis([-0.5, 0.5, -120, 0])
1629
+ >>> plt.title("Frequency response of the cosine window")
1630
+ >>> plt.ylabel("Normalized magnitude [dB]")
1631
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1632
+ >>> plt.show()
1633
+
1634
+ """
1635
+ if _len_guards(M):
1636
+ return np.ones(M)
1637
+ M, needs_trunc = _extend(M, sym)
1638
+
1639
+ w = np.sin(np.pi / M * (np.arange(0, M) + .5))
1640
+
1641
+ return _truncate(w, needs_trunc)
1642
+
1643
+
1644
+ def exponential(M, center=None, tau=1., sym=True):
1645
+ r"""Return an exponential (or Poisson) window.
1646
+
1647
+ Parameters
1648
+ ----------
1649
+ M : int
1650
+ Number of points in the output window. If zero, an empty array
1651
+ is returned. An exception is thrown when it is negative.
1652
+ center : float, optional
1653
+ Parameter defining the center location of the window function.
1654
+ The default value if not given is ``center = (M-1) / 2``. This
1655
+ parameter must take its default value for symmetric windows.
1656
+ tau : float, optional
1657
+ Parameter defining the decay. For ``center = 0`` use
1658
+ ``tau = -(M-1) / ln(x)`` if ``x`` is the fraction of the window
1659
+ remaining at the end.
1660
+ sym : bool, optional
1661
+ When True (default), generates a symmetric window, for use in filter
1662
+ design.
1663
+ When False, generates a periodic window, for use in spectral analysis.
1664
+
1665
+ Returns
1666
+ -------
1667
+ w : ndarray
1668
+ The window, with the maximum value normalized to 1 (though the value 1
1669
+ does not appear if `M` is even and `sym` is True).
1670
+
1671
+ Notes
1672
+ -----
1673
+ The Exponential window is defined as
1674
+
1675
+ .. math:: w(n) = e^{-|n-center| / \tau}
1676
+
1677
+ References
1678
+ ----------
1679
+ .. [1] S. Gade and H. Herlufsen, "Windows to FFT analysis (Part I)",
1680
+ Technical Review 3, Bruel & Kjaer, 1987.
1681
+
1682
+ Examples
1683
+ --------
1684
+ Plot the symmetric window and its frequency response:
1685
+
1686
+ >>> import numpy as np
1687
+ >>> from scipy import signal
1688
+ >>> from scipy.fft import fft, fftshift
1689
+ >>> import matplotlib.pyplot as plt
1690
+
1691
+ >>> M = 51
1692
+ >>> tau = 3.0
1693
+ >>> window = signal.windows.exponential(M, tau=tau)
1694
+ >>> plt.plot(window)
1695
+ >>> plt.title("Exponential Window (tau=3.0)")
1696
+ >>> plt.ylabel("Amplitude")
1697
+ >>> plt.xlabel("Sample")
1698
+
1699
+ >>> plt.figure()
1700
+ >>> A = fft(window, 2048) / (len(window)/2.0)
1701
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1702
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1703
+ >>> plt.plot(freq, response)
1704
+ >>> plt.axis([-0.5, 0.5, -35, 0])
1705
+ >>> plt.title("Frequency response of the Exponential window (tau=3.0)")
1706
+ >>> plt.ylabel("Normalized magnitude [dB]")
1707
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1708
+
1709
+ This function can also generate non-symmetric windows:
1710
+
1711
+ >>> tau2 = -(M-1) / np.log(0.01)
1712
+ >>> window2 = signal.windows.exponential(M, 0, tau2, False)
1713
+ >>> plt.figure()
1714
+ >>> plt.plot(window2)
1715
+ >>> plt.ylabel("Amplitude")
1716
+ >>> plt.xlabel("Sample")
1717
+ """
1718
+ if sym and center is not None:
1719
+ raise ValueError("If sym==True, center must be None.")
1720
+ if _len_guards(M):
1721
+ return np.ones(M)
1722
+ M, needs_trunc = _extend(M, sym)
1723
+
1724
+ if center is None:
1725
+ center = (M-1) / 2
1726
+
1727
+ n = np.arange(0, M)
1728
+ w = np.exp(-np.abs(n-center) / tau)
1729
+
1730
+ return _truncate(w, needs_trunc)
1731
+
1732
+
1733
+ def taylor(M, nbar=4, sll=30, norm=True, sym=True):
1734
+ """
1735
+ Return a Taylor window.
1736
+
1737
+ The Taylor window taper function approximates the Dolph-Chebyshev window's
1738
+ constant sidelobe level for a parameterized number of near-in sidelobes,
1739
+ but then allows a taper beyond [2]_.
1740
+
1741
+ The SAR (synthetic aperture radar) community commonly uses Taylor
1742
+ weighting for image formation processing because it provides strong,
1743
+ selectable sidelobe suppression with minimum broadening of the
1744
+ mainlobe [1]_.
1745
+
1746
+ Parameters
1747
+ ----------
1748
+ M : int
1749
+ Number of points in the output window. If zero, an empty array
1750
+ is returned. An exception is thrown when it is negative.
1751
+ nbar : int, optional
1752
+ Number of nearly constant level sidelobes adjacent to the mainlobe.
1753
+ sll : float, optional
1754
+ Desired suppression of sidelobe level in decibels (dB) relative to the
1755
+ DC gain of the mainlobe. This should be a positive number.
1756
+ norm : bool, optional
1757
+ When True (default), divides the window by the largest (middle) value
1758
+ for odd-length windows or the value that would occur between the two
1759
+ repeated middle values for even-length windows such that all values
1760
+ are less than or equal to 1. When False the DC gain will remain at 1
1761
+ (0 dB) and the sidelobes will be `sll` dB down.
1762
+ sym : bool, optional
1763
+ When True (default), generates a symmetric window, for use in filter
1764
+ design.
1765
+ When False, generates a periodic window, for use in spectral analysis.
1766
+
1767
+ Returns
1768
+ -------
1769
+ out : array
1770
+ The window. When `norm` is True (default), the maximum value is
1771
+ normalized to 1 (though the value 1 does not appear if `M` is
1772
+ even and `sym` is True).
1773
+
1774
+ See Also
1775
+ --------
1776
+ chebwin, kaiser, bartlett, blackman, hamming, hann
1777
+
1778
+ References
1779
+ ----------
1780
+ .. [1] W. Carrara, R. Goodman, and R. Majewski, "Spotlight Synthetic
1781
+ Aperture Radar: Signal Processing Algorithms" Pages 512-513,
1782
+ July 1995.
1783
+ .. [2] Armin Doerry, "Catalog of Window Taper Functions for
1784
+ Sidelobe Control", 2017.
1785
+ https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf
1786
+
1787
+ Examples
1788
+ --------
1789
+ Plot the window and its frequency response:
1790
+
1791
+ >>> import numpy as np
1792
+ >>> from scipy import signal
1793
+ >>> from scipy.fft import fft, fftshift
1794
+ >>> import matplotlib.pyplot as plt
1795
+
1796
+ >>> window = signal.windows.taylor(51, nbar=20, sll=100, norm=False)
1797
+ >>> plt.plot(window)
1798
+ >>> plt.title("Taylor window (100 dB)")
1799
+ >>> plt.ylabel("Amplitude")
1800
+ >>> plt.xlabel("Sample")
1801
+
1802
+ >>> plt.figure()
1803
+ >>> A = fft(window, 2048) / (len(window)/2.0)
1804
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
1805
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
1806
+ >>> plt.plot(freq, response)
1807
+ >>> plt.axis([-0.5, 0.5, -120, 0])
1808
+ >>> plt.title("Frequency response of the Taylor window (100 dB)")
1809
+ >>> plt.ylabel("Normalized magnitude [dB]")
1810
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
1811
+
1812
+ """ # noqa: E501
1813
+ if _len_guards(M):
1814
+ return np.ones(M)
1815
+ M, needs_trunc = _extend(M, sym)
1816
+
1817
+ # Original text uses a negative sidelobe level parameter and then negates
1818
+ # it in the calculation of B. To keep consistent with other methods we
1819
+ # assume the sidelobe level parameter to be positive.
1820
+ B = 10**(sll / 20)
1821
+ A = np.arccosh(B) / np.pi
1822
+ s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)
1823
+ ma = np.arange(1, nbar)
1824
+
1825
+ Fm = np.empty(nbar-1)
1826
+ signs = np.empty_like(ma)
1827
+ signs[::2] = 1
1828
+ signs[1::2] = -1
1829
+ m2 = ma*ma
1830
+ for mi, m in enumerate(ma):
1831
+ numer = signs[mi] * np.prod(1 - m2[mi]/s2/(A**2 + (ma - 0.5)**2))
1832
+ denom = 2 * np.prod(1 - m2[mi]/m2[:mi]) * np.prod(1 - m2[mi]/m2[mi+1:])
1833
+ Fm[mi] = numer / denom
1834
+
1835
+ def W(n):
1836
+ return 1 + 2*np.dot(Fm, np.cos(
1837
+ 2*np.pi*ma[:, np.newaxis]*(n-M/2.+0.5)/M))
1838
+
1839
+ w = W(np.arange(M))
1840
+
1841
+ # normalize (Note that this is not described in the original text [1])
1842
+ if norm:
1843
+ scale = 1.0 / W((M - 1) / 2)
1844
+ w *= scale
1845
+
1846
+ return _truncate(w, needs_trunc)
1847
+
1848
+
1849
+ def dpss(M, NW, Kmax=None, sym=True, norm=None, return_ratios=False):
1850
+ """
1851
+ Compute the Discrete Prolate Spheroidal Sequences (DPSS).
1852
+
1853
+ DPSS (or Slepian sequences) are often used in multitaper power spectral
1854
+ density estimation (see [1]_). The first window in the sequence can be
1855
+ used to maximize the energy concentration in the main lobe, and is also
1856
+ called the Slepian window.
1857
+
1858
+ Parameters
1859
+ ----------
1860
+ M : int
1861
+ Window length.
1862
+ NW : float
1863
+ Standardized half bandwidth corresponding to ``2*NW = BW/f0 = BW*M*dt``
1864
+ where ``dt`` is taken as 1.
1865
+ Kmax : int | None, optional
1866
+ Number of DPSS windows to return (orders ``0`` through ``Kmax-1``).
1867
+ If None (default), return only a single window of shape ``(M,)``
1868
+ instead of an array of windows of shape ``(Kmax, M)``.
1869
+ sym : bool, optional
1870
+ When True (default), generates a symmetric window, for use in filter
1871
+ design.
1872
+ When False, generates a periodic window, for use in spectral analysis.
1873
+ norm : {2, 'approximate', 'subsample'} | None, optional
1874
+ If 'approximate' or 'subsample', then the windows are normalized by the
1875
+ maximum, and a correction scale-factor for even-length windows
1876
+ is applied either using ``M**2/(M**2+NW)`` ("approximate") or
1877
+ a FFT-based subsample shift ("subsample"), see Notes for details.
1878
+ If None, then "approximate" is used when ``Kmax=None`` and 2 otherwise
1879
+ (which uses the l2 norm).
1880
+ return_ratios : bool, optional
1881
+ If True, also return the concentration ratios in addition to the
1882
+ windows.
1883
+
1884
+ Returns
1885
+ -------
1886
+ v : ndarray, shape (Kmax, M) or (M,)
1887
+ The DPSS windows. Will be 1D if `Kmax` is None.
1888
+ r : ndarray, shape (Kmax,) or float, optional
1889
+ The concentration ratios for the windows. Only returned if
1890
+ `return_ratios` evaluates to True. Will be 0D if `Kmax` is None.
1891
+
1892
+ Notes
1893
+ -----
1894
+ This computation uses the tridiagonal eigenvector formulation given
1895
+ in [2]_.
1896
+
1897
+ The default normalization for ``Kmax=None``, i.e. window-generation mode,
1898
+ simply using the l-infinity norm would create a window with two unity
1899
+ values, which creates slight normalization differences between even and odd
1900
+ orders. The approximate correction of ``M**2/float(M**2+NW)`` for even
1901
+ sample numbers is used to counteract this effect (see Examples below).
1902
+
1903
+ For very long signals (e.g., 1e6 elements), it can be useful to compute
1904
+ windows orders of magnitude shorter and use interpolation (e.g.,
1905
+ `scipy.interpolate.interp1d`) to obtain tapers of length `M`,
1906
+ but this in general will not preserve orthogonality between the tapers.
1907
+
1908
+ .. versionadded:: 1.1
1909
+
1910
+ References
1911
+ ----------
1912
+ .. [1] Percival DB, Walden WT. Spectral Analysis for Physical Applications:
1913
+ Multitaper and Conventional Univariate Techniques.
1914
+ Cambridge University Press; 1993.
1915
+ .. [2] Slepian, D. Prolate spheroidal wave functions, Fourier analysis, and
1916
+ uncertainty V: The discrete case. Bell System Technical Journal,
1917
+ Volume 57 (1978), 1371430.
1918
+ .. [3] Kaiser, JF, Schafer RW. On the Use of the I0-Sinh Window for
1919
+ Spectrum Analysis. IEEE Transactions on Acoustics, Speech and
1920
+ Signal Processing. ASSP-28 (1): 105-107; 1980.
1921
+
1922
+ Examples
1923
+ --------
1924
+ We can compare the window to `kaiser`, which was invented as an alternative
1925
+ that was easier to calculate [3]_ (example adapted from
1926
+ `here <https://ccrma.stanford.edu/~jos/sasp/Kaiser_DPSS_Windows_Compared.html>`_):
1927
+
1928
+ >>> import numpy as np
1929
+ >>> import matplotlib.pyplot as plt
1930
+ >>> from scipy.signal import windows, freqz
1931
+ >>> M = 51
1932
+ >>> fig, axes = plt.subplots(3, 2, figsize=(5, 7))
1933
+ >>> for ai, alpha in enumerate((1, 3, 5)):
1934
+ ... win_dpss = windows.dpss(M, alpha)
1935
+ ... beta = alpha*np.pi
1936
+ ... win_kaiser = windows.kaiser(M, beta)
1937
+ ... for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')):
1938
+ ... win /= win.sum()
1939
+ ... axes[ai, 0].plot(win, color=c, lw=1.)
1940
+ ... axes[ai, 0].set(xlim=[0, M-1], title=r'$\\alpha$ = %s' % alpha,
1941
+ ... ylabel='Amplitude')
1942
+ ... w, h = freqz(win)
1943
+ ... axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.)
1944
+ ... axes[ai, 1].set(xlim=[0, np.pi],
1945
+ ... title=r'$\\beta$ = %0.2f' % beta,
1946
+ ... ylabel='Magnitude (dB)')
1947
+ >>> for ax in axes.ravel():
1948
+ ... ax.grid(True)
1949
+ >>> axes[2, 1].legend(['DPSS', 'Kaiser'])
1950
+ >>> fig.tight_layout()
1951
+ >>> plt.show()
1952
+
1953
+ And here are examples of the first four windows, along with their
1954
+ concentration ratios:
1955
+
1956
+ >>> M = 512
1957
+ >>> NW = 2.5
1958
+ >>> win, eigvals = windows.dpss(M, NW, 4, return_ratios=True)
1959
+ >>> fig, ax = plt.subplots(1)
1960
+ >>> ax.plot(win.T, linewidth=1.)
1961
+ >>> ax.set(xlim=[0, M-1], ylim=[-0.1, 0.1], xlabel='Samples',
1962
+ ... title='DPSS, M=%d, NW=%0.1f' % (M, NW))
1963
+ >>> ax.legend(['win[%d] (%0.4f)' % (ii, ratio)
1964
+ ... for ii, ratio in enumerate(eigvals)])
1965
+ >>> fig.tight_layout()
1966
+ >>> plt.show()
1967
+
1968
+ Using a standard :math:`l_{\\infty}` norm would produce two unity values
1969
+ for even `M`, but only one unity value for odd `M`. This produces uneven
1970
+ window power that can be counteracted by the approximate correction
1971
+ ``M**2/float(M**2+NW)``, which can be selected by using
1972
+ ``norm='approximate'`` (which is the same as ``norm=None`` when
1973
+ ``Kmax=None``, as is the case here). Alternatively, the slower
1974
+ ``norm='subsample'`` can be used, which uses subsample shifting in the
1975
+ frequency domain (FFT) to compute the correction:
1976
+
1977
+ >>> Ms = np.arange(1, 41)
1978
+ >>> factors = (50, 20, 10, 5, 2.0001)
1979
+ >>> energy = np.empty((3, len(Ms), len(factors)))
1980
+ >>> for mi, M in enumerate(Ms):
1981
+ ... for fi, factor in enumerate(factors):
1982
+ ... NW = M / float(factor)
1983
+ ... # Corrected using empirical approximation (default)
1984
+ ... win = windows.dpss(M, NW)
1985
+ ... energy[0, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
1986
+ ... # Corrected using subsample shifting
1987
+ ... win = windows.dpss(M, NW, norm='subsample')
1988
+ ... energy[1, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
1989
+ ... # Uncorrected (using l-infinity norm)
1990
+ ... win /= win.max()
1991
+ ... energy[2, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
1992
+ >>> fig, ax = plt.subplots(1)
1993
+ >>> hs = ax.plot(Ms, energy[2], '-o', markersize=4,
1994
+ ... markeredgecolor='none')
1995
+ >>> leg = [hs[-1]]
1996
+ >>> for hi, hh in enumerate(hs):
1997
+ ... h1 = ax.plot(Ms, energy[0, :, hi], '-o', markersize=4,
1998
+ ... color=hh.get_color(), markeredgecolor='none',
1999
+ ... alpha=0.66)
2000
+ ... h2 = ax.plot(Ms, energy[1, :, hi], '-o', markersize=4,
2001
+ ... color=hh.get_color(), markeredgecolor='none',
2002
+ ... alpha=0.33)
2003
+ ... if hi == len(hs) - 1:
2004
+ ... leg.insert(0, h1[0])
2005
+ ... leg.insert(0, h2[0])
2006
+ >>> ax.set(xlabel='M (samples)', ylabel=r'Power / $\\sqrt{M}$')
2007
+ >>> ax.legend(leg, ['Uncorrected', r'Corrected: $\\frac{M^2}{M^2+NW}$',
2008
+ ... 'Corrected (subsample)'])
2009
+ >>> fig.tight_layout()
2010
+
2011
+ """
2012
+ if _len_guards(M):
2013
+ return np.ones(M)
2014
+ if norm is None:
2015
+ norm = 'approximate' if Kmax is None else 2
2016
+ known_norms = (2, 'approximate', 'subsample')
2017
+ if norm not in known_norms:
2018
+ raise ValueError(f'norm must be one of {known_norms}, got {norm}')
2019
+ if Kmax is None:
2020
+ singleton = True
2021
+ Kmax = 1
2022
+ else:
2023
+ singleton = False
2024
+ Kmax = operator.index(Kmax)
2025
+ if not 0 < Kmax <= M:
2026
+ raise ValueError('Kmax must be greater than 0 and less than M')
2027
+ if NW >= M/2.:
2028
+ raise ValueError('NW must be less than M/2.')
2029
+ if NW <= 0:
2030
+ raise ValueError('NW must be positive')
2031
+ M, needs_trunc = _extend(M, sym)
2032
+ W = float(NW) / M
2033
+ nidx = np.arange(M)
2034
+
2035
+ # Here we want to set up an optimization problem to find a sequence
2036
+ # whose energy is maximally concentrated within band [-W,W].
2037
+ # Thus, the measure lambda(T,W) is the ratio between the energy within
2038
+ # that band, and the total energy. This leads to the eigen-system
2039
+ # (A - (l1)I)v = 0, where the eigenvector corresponding to the largest
2040
+ # eigenvalue is the sequence with maximally concentrated energy. The
2041
+ # collection of eigenvectors of this system are called Slepian
2042
+ # sequences, or discrete prolate spheroidal sequences (DPSS). Only the
2043
+ # first K, K = 2NW/dt orders of DPSS will exhibit good spectral
2044
+ # concentration
2045
+ # [see https://en.wikipedia.org/wiki/Spectral_concentration_problem]
2046
+
2047
+ # Here we set up an alternative symmetric tri-diagonal eigenvalue
2048
+ # problem such that
2049
+ # (B - (l2)I)v = 0, and v are our DPSS (but eigenvalues l2 != l1)
2050
+ # the main diagonal = ([M-1-2*t]/2)**2 cos(2PIW), t=[0,1,2,...,M-1]
2051
+ # and the first off-diagonal = t(M-t)/2, t=[1,2,...,M-1]
2052
+ # [see Percival and Walden, 1993]
2053
+ d = ((M - 1 - 2 * nidx) / 2.) ** 2 * np.cos(2 * np.pi * W)
2054
+ e = nidx[1:] * (M - nidx[1:]) / 2.
2055
+
2056
+ # only calculate the highest Kmax eigenvalues
2057
+ w, windows = linalg.eigh_tridiagonal(
2058
+ d, e, select='i', select_range=(M - Kmax, M - 1))
2059
+ w = w[::-1]
2060
+ windows = windows[:, ::-1].T
2061
+
2062
+ # By convention (Percival and Walden, 1993 pg 379)
2063
+ # * symmetric tapers (k=0,2,4,...) should have a positive average.
2064
+ fix_even = (windows[::2].sum(axis=1) < 0)
2065
+ for i, f in enumerate(fix_even):
2066
+ if f:
2067
+ windows[2 * i] *= -1
2068
+ # * antisymmetric tapers should begin with a positive lobe
2069
+ # (this depends on the definition of "lobe", here we'll take the first
2070
+ # point above the numerical noise, which should be good enough for
2071
+ # sufficiently smooth functions, and more robust than relying on an
2072
+ # algorithm that uses max(abs(w)), which is susceptible to numerical
2073
+ # noise problems)
2074
+ thresh = max(1e-7, 1. / M)
2075
+ for i, w in enumerate(windows[1::2]):
2076
+ if w[w * w > thresh][0] < 0:
2077
+ windows[2 * i + 1] *= -1
2078
+
2079
+ # Now find the eigenvalues of the original spectral concentration problem
2080
+ # Use the autocorr sequence technique from Percival and Walden, 1993 pg 390
2081
+ if return_ratios:
2082
+ dpss_rxx = _fftautocorr(windows)
2083
+ r = 4 * W * np.sinc(2 * W * nidx)
2084
+ r[0] = 2 * W
2085
+ ratios = np.dot(dpss_rxx, r)
2086
+ if singleton:
2087
+ ratios = ratios[0]
2088
+ # Deal with sym and Kmax=None
2089
+ if norm != 2:
2090
+ windows /= windows.max()
2091
+ if M % 2 == 0:
2092
+ if norm == 'approximate':
2093
+ correction = M**2 / float(M**2 + NW)
2094
+ else:
2095
+ s = sp_fft.rfft(windows[0])
2096
+ shift = -(1 - 1./M) * np.arange(1, M//2 + 1)
2097
+ s[1:] *= 2 * np.exp(-1j * np.pi * shift)
2098
+ correction = M / s.real.sum()
2099
+ windows *= correction
2100
+ # else we're already l2 normed, so do nothing
2101
+ if needs_trunc:
2102
+ windows = windows[:, :-1]
2103
+ if singleton:
2104
+ windows = windows[0]
2105
+ return (windows, ratios) if return_ratios else windows
2106
+
2107
+
2108
+ def lanczos(M, *, sym=True):
2109
+ r"""Return a Lanczos window also known as a sinc window.
2110
+
2111
+ Parameters
2112
+ ----------
2113
+ M : int
2114
+ Number of points in the output window. If zero, an empty array
2115
+ is returned. An exception is thrown when it is negative.
2116
+ sym : bool, optional
2117
+ When True (default), generates a symmetric window, for use in filter
2118
+ design.
2119
+ When False, generates a periodic window, for use in spectral analysis.
2120
+
2121
+ Returns
2122
+ -------
2123
+ w : ndarray
2124
+ The window, with the maximum value normalized to 1 (though the value 1
2125
+ does not appear if `M` is even and `sym` is True).
2126
+
2127
+ Notes
2128
+ -----
2129
+ The Lanczos window is defined as
2130
+
2131
+ .. math:: w(n) = sinc \left( \frac{2n}{M - 1} - 1 \right)
2132
+
2133
+ where
2134
+
2135
+ .. math:: sinc(x) = \frac{\sin(\pi x)}{\pi x}
2136
+
2137
+ The Lanczos window has reduced Gibbs oscillations and is widely used for
2138
+ filtering climate timeseries with good properties in the physical and
2139
+ spectral domains.
2140
+
2141
+ .. versionadded:: 1.10
2142
+
2143
+ References
2144
+ ----------
2145
+ .. [1] Lanczos, C., and Teichmann, T. (1957). Applied analysis.
2146
+ Physics Today, 10, 44.
2147
+ .. [2] Duchon C. E. (1979) Lanczos Filtering in One and Two Dimensions.
2148
+ Journal of Applied Meteorology, Vol 18, pp 1016-1022.
2149
+ .. [3] Thomson, R. E. and Emery, W. J. (2014) Data Analysis Methods in
2150
+ Physical Oceanography (Third Edition), Elsevier, pp 593-637.
2151
+ .. [4] Wikipedia, "Window function",
2152
+ http://en.wikipedia.org/wiki/Window_function
2153
+
2154
+ Examples
2155
+ --------
2156
+ Plot the window
2157
+
2158
+ >>> import numpy as np
2159
+ >>> from scipy.signal.windows import lanczos
2160
+ >>> from scipy.fft import fft, fftshift
2161
+ >>> import matplotlib.pyplot as plt
2162
+ >>> fig, ax = plt.subplots(1)
2163
+ >>> window = lanczos(51)
2164
+ >>> ax.plot(window)
2165
+ >>> ax.set_title("Lanczos window")
2166
+ >>> ax.set_ylabel("Amplitude")
2167
+ >>> ax.set_xlabel("Sample")
2168
+ >>> fig.tight_layout()
2169
+ >>> plt.show()
2170
+
2171
+ and its frequency response:
2172
+
2173
+ >>> fig, ax = plt.subplots(1)
2174
+ >>> A = fft(window, 2048) / (len(window)/2.0)
2175
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
2176
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
2177
+ >>> ax.plot(freq, response)
2178
+ >>> ax.set_xlim(-0.5, 0.5)
2179
+ >>> ax.set_ylim(-120, 0)
2180
+ >>> ax.set_title("Frequency response of the lanczos window")
2181
+ >>> ax.set_ylabel("Normalized magnitude [dB]")
2182
+ >>> ax.set_xlabel("Normalized frequency [cycles per sample]")
2183
+ >>> fig.tight_layout()
2184
+ >>> plt.show()
2185
+ """
2186
+ if _len_guards(M):
2187
+ return np.ones(M)
2188
+ M, needs_trunc = _extend(M, sym)
2189
+
2190
+ # To make sure that the window is symmetric, we concatenate the right hand
2191
+ # half of the window and the flipped one which is the left hand half of
2192
+ # the window.
2193
+ def _calc_right_side_lanczos(n, m):
2194
+ return np.sinc(2. * np.arange(n, m) / (m - 1) - 1.0)
2195
+
2196
+ if M % 2 == 0:
2197
+ wh = _calc_right_side_lanczos(M/2, M)
2198
+ w = np.r_[np.flip(wh), wh]
2199
+ else:
2200
+ wh = _calc_right_side_lanczos((M+1)/2, M)
2201
+ w = np.r_[np.flip(wh), 1.0, wh]
2202
+
2203
+ return _truncate(w, needs_trunc)
2204
+
2205
+
2206
+ def _fftautocorr(x):
2207
+ """Compute the autocorrelation of a real array and crop the result."""
2208
+ N = x.shape[-1]
2209
+ use_N = sp_fft.next_fast_len(2*N-1)
2210
+ x_fft = sp_fft.rfft(x, use_N, axis=-1)
2211
+ cxy = sp_fft.irfft(x_fft * x_fft.conj(), n=use_N)[:, :N]
2212
+ # Or equivalently (but in most cases slower):
2213
+ # cxy = np.array([np.convolve(xx, yy[::-1], mode='full')
2214
+ # for xx, yy in zip(x, x)])[:, N-1:2*N-1]
2215
+ return cxy
2216
+
2217
+
2218
+ _win_equiv_raw = {
2219
+ ('barthann', 'brthan', 'bth'): (barthann, False),
2220
+ ('bartlett', 'bart', 'brt'): (bartlett, False),
2221
+ ('blackman', 'black', 'blk'): (blackman, False),
2222
+ ('blackmanharris', 'blackharr', 'bkh'): (blackmanharris, False),
2223
+ ('bohman', 'bman', 'bmn'): (bohman, False),
2224
+ ('boxcar', 'box', 'ones',
2225
+ 'rect', 'rectangular'): (boxcar, False),
2226
+ ('chebwin', 'cheb'): (chebwin, True),
2227
+ ('cosine', 'halfcosine'): (cosine, False),
2228
+ ('dpss',): (dpss, True),
2229
+ ('exponential', 'poisson'): (exponential, False),
2230
+ ('flattop', 'flat', 'flt'): (flattop, False),
2231
+ ('gaussian', 'gauss', 'gss'): (gaussian, True),
2232
+ ('general cosine', 'general_cosine'): (general_cosine, True),
2233
+ ('general gaussian', 'general_gaussian',
2234
+ 'general gauss', 'general_gauss', 'ggs'): (general_gaussian, True),
2235
+ ('general hamming', 'general_hamming'): (general_hamming, True),
2236
+ ('hamming', 'hamm', 'ham'): (hamming, False),
2237
+ ('hann', 'han'): (hann, False),
2238
+ ('kaiser', 'ksr'): (kaiser, True),
2239
+ ('kaiser bessel derived', 'kbd'): (kaiser_bessel_derived, True),
2240
+ ('lanczos', 'sinc'): (lanczos, False),
2241
+ ('nuttall', 'nutl', 'nut'): (nuttall, False),
2242
+ ('parzen', 'parz', 'par'): (parzen, False),
2243
+ ('taylor', 'taylorwin'): (taylor, False),
2244
+ ('triangle', 'triang', 'tri'): (triang, False),
2245
+ ('tukey', 'tuk'): (tukey, False),
2246
+ }
2247
+
2248
+ # Fill dict with all valid window name strings
2249
+ _win_equiv = {}
2250
+ for k, v in _win_equiv_raw.items():
2251
+ for key in k:
2252
+ _win_equiv[key] = v[0]
2253
+
2254
+ # Keep track of which windows need additional parameters
2255
+ _needs_param = set()
2256
+ for k, v in _win_equiv_raw.items():
2257
+ if v[1]:
2258
+ _needs_param.update(k)
2259
+
2260
+
2261
+ def get_window(window, Nx, fftbins=True):
2262
+ """
2263
+ Return a window of a given length and type.
2264
+
2265
+ Parameters
2266
+ ----------
2267
+ window : string, float, or tuple
2268
+ The type of window to create. See below for more details.
2269
+ Nx : int
2270
+ The number of samples in the window.
2271
+ fftbins : bool, optional
2272
+ If True (default), create a "periodic" window, ready to use with
2273
+ `ifftshift` and be multiplied by the result of an FFT (see also
2274
+ :func:`~scipy.fft.fftfreq`).
2275
+ If False, create a "symmetric" window, for use in filter design.
2276
+
2277
+ Returns
2278
+ -------
2279
+ get_window : ndarray
2280
+ Returns a window of length `Nx` and type `window`
2281
+
2282
+ Notes
2283
+ -----
2284
+ Window types:
2285
+
2286
+ - `~scipy.signal.windows.boxcar`
2287
+ - `~scipy.signal.windows.triang`
2288
+ - `~scipy.signal.windows.blackman`
2289
+ - `~scipy.signal.windows.hamming`
2290
+ - `~scipy.signal.windows.hann`
2291
+ - `~scipy.signal.windows.bartlett`
2292
+ - `~scipy.signal.windows.flattop`
2293
+ - `~scipy.signal.windows.parzen`
2294
+ - `~scipy.signal.windows.bohman`
2295
+ - `~scipy.signal.windows.blackmanharris`
2296
+ - `~scipy.signal.windows.nuttall`
2297
+ - `~scipy.signal.windows.barthann`
2298
+ - `~scipy.signal.windows.cosine`
2299
+ - `~scipy.signal.windows.exponential`
2300
+ - `~scipy.signal.windows.tukey`
2301
+ - `~scipy.signal.windows.taylor`
2302
+ - `~scipy.signal.windows.lanczos`
2303
+ - `~scipy.signal.windows.kaiser` (needs beta)
2304
+ - `~scipy.signal.windows.kaiser_bessel_derived` (needs beta)
2305
+ - `~scipy.signal.windows.gaussian` (needs standard deviation)
2306
+ - `~scipy.signal.windows.general_cosine` (needs weighting coefficients)
2307
+ - `~scipy.signal.windows.general_gaussian` (needs power, width)
2308
+ - `~scipy.signal.windows.general_hamming` (needs window coefficient)
2309
+ - `~scipy.signal.windows.dpss` (needs normalized half-bandwidth)
2310
+ - `~scipy.signal.windows.chebwin` (needs attenuation)
2311
+
2312
+
2313
+ If the window requires no parameters, then `window` can be a string.
2314
+
2315
+ If the window requires parameters, then `window` must be a tuple
2316
+ with the first argument the string name of the window, and the next
2317
+ arguments the needed parameters.
2318
+
2319
+ If `window` is a floating point number, it is interpreted as the beta
2320
+ parameter of the `~scipy.signal.windows.kaiser` window.
2321
+
2322
+ Each of the window types listed above is also the name of
2323
+ a function that can be called directly to create a window of
2324
+ that type.
2325
+
2326
+ Examples
2327
+ --------
2328
+ >>> from scipy import signal
2329
+ >>> signal.get_window('triang', 7)
2330
+ array([ 0.125, 0.375, 0.625, 0.875, 0.875, 0.625, 0.375])
2331
+ >>> signal.get_window(('kaiser', 4.0), 9)
2332
+ array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093,
2333
+ 0.97885093, 0.82160913, 0.56437221, 0.29425961])
2334
+ >>> signal.get_window(('exponential', None, 1.), 9)
2335
+ array([ 0.011109 , 0.03019738, 0.082085 , 0.22313016, 0.60653066,
2336
+ 0.60653066, 0.22313016, 0.082085 , 0.03019738])
2337
+ >>> signal.get_window(4.0, 9)
2338
+ array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093,
2339
+ 0.97885093, 0.82160913, 0.56437221, 0.29425961])
2340
+
2341
+ """
2342
+ sym = not fftbins
2343
+ try:
2344
+ beta = float(window)
2345
+ except (TypeError, ValueError) as e:
2346
+ args = ()
2347
+ if isinstance(window, tuple):
2348
+ winstr = window[0]
2349
+ if len(window) > 1:
2350
+ args = window[1:]
2351
+ elif isinstance(window, str):
2352
+ if window in _needs_param:
2353
+ raise ValueError("The '" + window + "' window needs one or "
2354
+ "more parameters -- pass a tuple.") from e
2355
+ else:
2356
+ winstr = window
2357
+ else:
2358
+ raise ValueError("%s as window type is not supported." %
2359
+ str(type(window))) from e
2360
+
2361
+ try:
2362
+ winfunc = _win_equiv[winstr]
2363
+ except KeyError as e:
2364
+ raise ValueError("Unknown window type.") from e
2365
+
2366
+ if winfunc is dpss:
2367
+ params = (Nx,) + args + (None,)
2368
+ else:
2369
+ params = (Nx,) + args
2370
+ else:
2371
+ winfunc = kaiser
2372
+ params = (Nx, beta)
2373
+
2374
+ return winfunc(*params, sym=sym)
venv/lib/python3.10/site-packages/scipy/signal/windows/windows.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.signal.windows` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
9
+ 'blackmanharris', 'flattop', 'bartlett', 'barthann',
10
+ 'hamming', 'kaiser', 'gaussian', 'general_cosine',
11
+ 'general_gaussian', 'general_hamming', 'chebwin', 'cosine',
12
+ 'hann', 'exponential', 'tukey', 'taylor', 'dpss', 'get_window',
13
+ 'linalg', 'sp_fft', 'k', 'v', 'key'
14
+ ]
15
+
16
+
17
+ def __dir__():
18
+ return __all__
19
+
20
+
21
+ def __getattr__(name):
22
+ return _sub_module_deprecation(sub_package="signal.windows", module="windows",
23
+ private_modules=["_windows"], all=__all__,
24
+ attribute=name)
venv/lib/python3.10/site-packages/scipy/special/__init__.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ========================================
3
+ Special functions (:mod:`scipy.special`)
4
+ ========================================
5
+
6
+ .. currentmodule:: scipy.special
7
+
8
+ Almost all of the functions below accept NumPy arrays as input
9
+ arguments as well as single numbers. This means they follow
10
+ broadcasting and automatic array-looping rules. Technically,
11
+ they are `NumPy universal functions
12
+ <https://numpy.org/doc/stable/user/basics.ufuncs.html#ufuncs-basics>`_.
13
+ Functions which do not accept NumPy arrays are marked by a warning
14
+ in the section description.
15
+
16
+ .. seealso::
17
+
18
+ `scipy.special.cython_special` -- Typed Cython versions of special functions
19
+
20
+
21
+ Error handling
22
+ ==============
23
+
24
+ Errors are handled by returning NaNs or other appropriate values.
25
+ Some of the special function routines can emit warnings or raise
26
+ exceptions when an error occurs. By default this is disabled; to
27
+ query and control the current error handling state the following
28
+ functions are provided.
29
+
30
+ .. autosummary::
31
+ :toctree: generated/
32
+
33
+ geterr -- Get the current way of handling special-function errors.
34
+ seterr -- Set how special-function errors are handled.
35
+ errstate -- Context manager for special-function error handling.
36
+ SpecialFunctionWarning -- Warning that can be emitted by special functions.
37
+ SpecialFunctionError -- Exception that can be raised by special functions.
38
+
39
+ Available functions
40
+ ===================
41
+
42
+ Airy functions
43
+ --------------
44
+
45
+ .. autosummary::
46
+ :toctree: generated/
47
+
48
+ airy -- Airy functions and their derivatives.
49
+ airye -- Exponentially scaled Airy functions and their derivatives.
50
+ ai_zeros -- Compute `nt` zeros and values of the Airy function Ai and its derivative.
51
+ bi_zeros -- Compute `nt` zeros and values of the Airy function Bi and its derivative.
52
+ itairy -- Integrals of Airy functions
53
+
54
+
55
+ Elliptic functions and integrals
56
+ --------------------------------
57
+
58
+ .. autosummary::
59
+ :toctree: generated/
60
+
61
+ ellipj -- Jacobian elliptic functions.
62
+ ellipk -- Complete elliptic integral of the first kind.
63
+ ellipkm1 -- Complete elliptic integral of the first kind around `m` = 1.
64
+ ellipkinc -- Incomplete elliptic integral of the first kind.
65
+ ellipe -- Complete elliptic integral of the second kind.
66
+ ellipeinc -- Incomplete elliptic integral of the second kind.
67
+ elliprc -- Degenerate symmetric integral RC.
68
+ elliprd -- Symmetric elliptic integral of the second kind.
69
+ elliprf -- Completely-symmetric elliptic integral of the first kind.
70
+ elliprg -- Completely-symmetric elliptic integral of the second kind.
71
+ elliprj -- Symmetric elliptic integral of the third kind.
72
+
73
+ Bessel functions
74
+ ----------------
75
+
76
+ .. autosummary::
77
+ :toctree: generated/
78
+
79
+ jv -- Bessel function of the first kind of real order and \
80
+ complex argument.
81
+ jve -- Exponentially scaled Bessel function of order `v`.
82
+ yn -- Bessel function of the second kind of integer order and \
83
+ real argument.
84
+ yv -- Bessel function of the second kind of real order and \
85
+ complex argument.
86
+ yve -- Exponentially scaled Bessel function of the second kind \
87
+ of real order.
88
+ kn -- Modified Bessel function of the second kind of integer \
89
+ order `n`
90
+ kv -- Modified Bessel function of the second kind of real order \
91
+ `v`
92
+ kve -- Exponentially scaled modified Bessel function of the \
93
+ second kind.
94
+ iv -- Modified Bessel function of the first kind of real order.
95
+ ive -- Exponentially scaled modified Bessel function of the \
96
+ first kind.
97
+ hankel1 -- Hankel function of the first kind.
98
+ hankel1e -- Exponentially scaled Hankel function of the first kind.
99
+ hankel2 -- Hankel function of the second kind.
100
+ hankel2e -- Exponentially scaled Hankel function of the second kind.
101
+ wright_bessel -- Wright's generalized Bessel function.
102
+
103
+ The following function does not accept NumPy arrays (it is not a
104
+ universal function):
105
+
106
+ .. autosummary::
107
+ :toctree: generated/
108
+
109
+ lmbda -- Jahnke-Emden Lambda function, Lambdav(x).
110
+
111
+ Zeros of Bessel functions
112
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
113
+
114
+ The following functions do not accept NumPy arrays (they are not
115
+ universal functions):
116
+
117
+ .. autosummary::
118
+ :toctree: generated/
119
+
120
+ jnjnp_zeros -- Compute zeros of integer-order Bessel functions Jn and Jn'.
121
+ jnyn_zeros -- Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
122
+ jn_zeros -- Compute zeros of integer-order Bessel function Jn(x).
123
+ jnp_zeros -- Compute zeros of integer-order Bessel function derivative Jn'(x).
124
+ yn_zeros -- Compute zeros of integer-order Bessel function Yn(x).
125
+ ynp_zeros -- Compute zeros of integer-order Bessel function derivative Yn'(x).
126
+ y0_zeros -- Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
127
+ y1_zeros -- Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
128
+ y1p_zeros -- Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
129
+
130
+ Faster versions of common Bessel functions
131
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
132
+
133
+ .. autosummary::
134
+ :toctree: generated/
135
+
136
+ j0 -- Bessel function of the first kind of order 0.
137
+ j1 -- Bessel function of the first kind of order 1.
138
+ y0 -- Bessel function of the second kind of order 0.
139
+ y1 -- Bessel function of the second kind of order 1.
140
+ i0 -- Modified Bessel function of order 0.
141
+ i0e -- Exponentially scaled modified Bessel function of order 0.
142
+ i1 -- Modified Bessel function of order 1.
143
+ i1e -- Exponentially scaled modified Bessel function of order 1.
144
+ k0 -- Modified Bessel function of the second kind of order 0, :math:`K_0`.
145
+ k0e -- Exponentially scaled modified Bessel function K of order 0
146
+ k1 -- Modified Bessel function of the second kind of order 1, :math:`K_1(x)`.
147
+ k1e -- Exponentially scaled modified Bessel function K of order 1.
148
+
149
+ Integrals of Bessel functions
150
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
151
+
152
+ .. autosummary::
153
+ :toctree: generated/
154
+
155
+ itj0y0 -- Integrals of Bessel functions of order 0.
156
+ it2j0y0 -- Integrals related to Bessel functions of order 0.
157
+ iti0k0 -- Integrals of modified Bessel functions of order 0.
158
+ it2i0k0 -- Integrals related to modified Bessel functions of order 0.
159
+ besselpoly -- Weighted integral of a Bessel function.
160
+
161
+ Derivatives of Bessel functions
162
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
163
+
164
+ .. autosummary::
165
+ :toctree: generated/
166
+
167
+ jvp -- Compute nth derivative of Bessel function Jv(z) with respect to `z`.
168
+ yvp -- Compute nth derivative of Bessel function Yv(z) with respect to `z`.
169
+ kvp -- Compute nth derivative of real-order modified Bessel function Kv(z)
170
+ ivp -- Compute nth derivative of modified Bessel function Iv(z) with respect to `z`.
171
+ h1vp -- Compute nth derivative of Hankel function H1v(z) with respect to `z`.
172
+ h2vp -- Compute nth derivative of Hankel function H2v(z) with respect to `z`.
173
+
174
+ Spherical Bessel functions
175
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
176
+
177
+ .. autosummary::
178
+ :toctree: generated/
179
+
180
+ spherical_jn -- Spherical Bessel function of the first kind or its derivative.
181
+ spherical_yn -- Spherical Bessel function of the second kind or its derivative.
182
+ spherical_in -- Modified spherical Bessel function of the first kind or its derivative.
183
+ spherical_kn -- Modified spherical Bessel function of the second kind or its derivative.
184
+
185
+ Riccati-Bessel functions
186
+ ^^^^^^^^^^^^^^^^^^^^^^^^
187
+
188
+ The following functions do not accept NumPy arrays (they are not
189
+ universal functions):
190
+
191
+ .. autosummary::
192
+ :toctree: generated/
193
+
194
+ riccati_jn -- Compute Ricatti-Bessel function of the first kind and its derivative.
195
+ riccati_yn -- Compute Ricatti-Bessel function of the second kind and its derivative.
196
+
197
+ Struve functions
198
+ ----------------
199
+
200
+ .. autosummary::
201
+ :toctree: generated/
202
+
203
+ struve -- Struve function.
204
+ modstruve -- Modified Struve function.
205
+ itstruve0 -- Integral of the Struve function of order 0.
206
+ it2struve0 -- Integral related to the Struve function of order 0.
207
+ itmodstruve0 -- Integral of the modified Struve function of order 0.
208
+
209
+
210
+ Raw statistical functions
211
+ -------------------------
212
+
213
+ .. seealso:: :mod:`scipy.stats`: Friendly versions of these functions.
214
+
215
+ Binomial distribution
216
+ ^^^^^^^^^^^^^^^^^^^^^
217
+
218
+ .. autosummary::
219
+ :toctree: generated/
220
+
221
+ bdtr -- Binomial distribution cumulative distribution function.
222
+ bdtrc -- Binomial distribution survival function.
223
+ bdtri -- Inverse function to `bdtr` with respect to `p`.
224
+ bdtrik -- Inverse function to `bdtr` with respect to `k`.
225
+ bdtrin -- Inverse function to `bdtr` with respect to `n`.
226
+
227
+ Beta distribution
228
+ ^^^^^^^^^^^^^^^^^
229
+
230
+ .. autosummary::
231
+ :toctree: generated/
232
+
233
+ btdtr -- Cumulative distribution function of the beta distribution.
234
+ btdtri -- The `p`-th quantile of the beta distribution.
235
+ btdtria -- Inverse of `btdtr` with respect to `a`.
236
+ btdtrib -- btdtria(a, p, x).
237
+
238
+ F distribution
239
+ ^^^^^^^^^^^^^^
240
+
241
+ .. autosummary::
242
+ :toctree: generated/
243
+
244
+ fdtr -- F cumulative distribution function.
245
+ fdtrc -- F survival function.
246
+ fdtri -- The `p`-th quantile of the F-distribution.
247
+ fdtridfd -- Inverse to `fdtr` vs dfd.
248
+
249
+ Gamma distribution
250
+ ^^^^^^^^^^^^^^^^^^
251
+
252
+ .. autosummary::
253
+ :toctree: generated/
254
+
255
+ gdtr -- Gamma distribution cumulative distribution function.
256
+ gdtrc -- Gamma distribution survival function.
257
+ gdtria -- Inverse of `gdtr` vs a.
258
+ gdtrib -- Inverse of `gdtr` vs b.
259
+ gdtrix -- Inverse of `gdtr` vs x.
260
+
261
+ Negative binomial distribution
262
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
263
+
264
+ .. autosummary::
265
+ :toctree: generated/
266
+
267
+ nbdtr -- Negative binomial cumulative distribution function.
268
+ nbdtrc -- Negative binomial survival function.
269
+ nbdtri -- Inverse of `nbdtr` vs `p`.
270
+ nbdtrik -- Inverse of `nbdtr` vs `k`.
271
+ nbdtrin -- Inverse of `nbdtr` vs `n`.
272
+
273
+ Noncentral F distribution
274
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
275
+
276
+ .. autosummary::
277
+ :toctree: generated/
278
+
279
+ ncfdtr -- Cumulative distribution function of the non-central F distribution.
280
+ ncfdtridfd -- Calculate degrees of freedom (denominator) for the noncentral F-distribution.
281
+ ncfdtridfn -- Calculate degrees of freedom (numerator) for the noncentral F-distribution.
282
+ ncfdtri -- Inverse cumulative distribution function of the non-central F distribution.
283
+ ncfdtrinc -- Calculate non-centrality parameter for non-central F distribution.
284
+
285
+ Noncentral t distribution
286
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
287
+
288
+ .. autosummary::
289
+ :toctree: generated/
290
+
291
+ nctdtr -- Cumulative distribution function of the non-central `t` distribution.
292
+ nctdtridf -- Calculate degrees of freedom for non-central t distribution.
293
+ nctdtrit -- Inverse cumulative distribution function of the non-central t distribution.
294
+ nctdtrinc -- Calculate non-centrality parameter for non-central t distribution.
295
+
296
+ Normal distribution
297
+ ^^^^^^^^^^^^^^^^^^^
298
+
299
+ .. autosummary::
300
+ :toctree: generated/
301
+
302
+ nrdtrimn -- Calculate mean of normal distribution given other params.
303
+ nrdtrisd -- Calculate standard deviation of normal distribution given other params.
304
+ ndtr -- Normal cumulative distribution function.
305
+ log_ndtr -- Logarithm of normal cumulative distribution function.
306
+ ndtri -- Inverse of `ndtr` vs x.
307
+ ndtri_exp -- Inverse of `log_ndtr` vs x.
308
+
309
+ Poisson distribution
310
+ ^^^^^^^^^^^^^^^^^^^^
311
+
312
+ .. autosummary::
313
+ :toctree: generated/
314
+
315
+ pdtr -- Poisson cumulative distribution function.
316
+ pdtrc -- Poisson survival function.
317
+ pdtri -- Inverse to `pdtr` vs m.
318
+ pdtrik -- Inverse to `pdtr` vs k.
319
+
320
+ Student t distribution
321
+ ^^^^^^^^^^^^^^^^^^^^^^
322
+
323
+ .. autosummary::
324
+ :toctree: generated/
325
+
326
+ stdtr -- Student t distribution cumulative distribution function.
327
+ stdtridf -- Inverse of `stdtr` vs df.
328
+ stdtrit -- Inverse of `stdtr` vs `t`.
329
+
330
+ Chi square distribution
331
+ ^^^^^^^^^^^^^^^^^^^^^^^
332
+
333
+ .. autosummary::
334
+ :toctree: generated/
335
+
336
+ chdtr -- Chi square cumulative distribution function.
337
+ chdtrc -- Chi square survival function.
338
+ chdtri -- Inverse to `chdtrc`.
339
+ chdtriv -- Inverse to `chdtr` vs `v`.
340
+
341
+ Non-central chi square distribution
342
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
343
+
344
+ .. autosummary::
345
+ :toctree: generated/
346
+
347
+ chndtr -- Non-central chi square cumulative distribution function.
348
+ chndtridf -- Inverse to `chndtr` vs `df`.
349
+ chndtrinc -- Inverse to `chndtr` vs `nc`.
350
+ chndtrix -- Inverse to `chndtr` vs `x`.
351
+
352
+ Kolmogorov distribution
353
+ ^^^^^^^^^^^^^^^^^^^^^^^
354
+
355
+ .. autosummary::
356
+ :toctree: generated/
357
+
358
+ smirnov -- Kolmogorov-Smirnov complementary cumulative distribution function.
359
+ smirnovi -- Inverse to `smirnov`.
360
+ kolmogorov -- Complementary cumulative distribution function of Kolmogorov distribution.
361
+ kolmogi -- Inverse function to `kolmogorov`.
362
+
363
+ Box-Cox transformation
364
+ ^^^^^^^^^^^^^^^^^^^^^^
365
+
366
+ .. autosummary::
367
+ :toctree: generated/
368
+
369
+ boxcox -- Compute the Box-Cox transformation.
370
+ boxcox1p -- Compute the Box-Cox transformation of 1 + `x`.
371
+ inv_boxcox -- Compute the inverse of the Box-Cox transformation.
372
+ inv_boxcox1p -- Compute the inverse of the Box-Cox transformation.
373
+
374
+
375
+ Sigmoidal functions
376
+ ^^^^^^^^^^^^^^^^^^^
377
+
378
+ .. autosummary::
379
+ :toctree: generated/
380
+
381
+ logit -- Logit ufunc for ndarrays.
382
+ expit -- Logistic sigmoid function.
383
+ log_expit -- Logarithm of the logistic sigmoid function.
384
+
385
+ Miscellaneous
386
+ ^^^^^^^^^^^^^
387
+
388
+ .. autosummary::
389
+ :toctree: generated/
390
+
391
+ tklmbda -- Tukey-Lambda cumulative distribution function.
392
+ owens_t -- Owen's T Function.
393
+
394
+
395
+ Information Theory functions
396
+ ----------------------------
397
+
398
+ .. autosummary::
399
+ :toctree: generated/
400
+
401
+ entr -- Elementwise function for computing entropy.
402
+ rel_entr -- Elementwise function for computing relative entropy.
403
+ kl_div -- Elementwise function for computing Kullback-Leibler divergence.
404
+ huber -- Huber loss function.
405
+ pseudo_huber -- Pseudo-Huber loss function.
406
+
407
+
408
+ Gamma and related functions
409
+ ---------------------------
410
+
411
+ .. autosummary::
412
+ :toctree: generated/
413
+
414
+ gamma -- Gamma function.
415
+ gammaln -- Logarithm of the absolute value of the Gamma function for real inputs.
416
+ loggamma -- Principal branch of the logarithm of the Gamma function.
417
+ gammasgn -- Sign of the gamma function.
418
+ gammainc -- Regularized lower incomplete gamma function.
419
+ gammaincinv -- Inverse to `gammainc`.
420
+ gammaincc -- Regularized upper incomplete gamma function.
421
+ gammainccinv -- Inverse to `gammaincc`.
422
+ beta -- Beta function.
423
+ betaln -- Natural logarithm of absolute value of beta function.
424
+ betainc -- Incomplete beta integral.
425
+ betaincc -- Complemented incomplete beta integral.
426
+ betaincinv -- Inverse function to beta integral.
427
+ betainccinv -- Inverse of the complemented incomplete beta integral.
428
+ psi -- The digamma function.
429
+ rgamma -- Gamma function inverted.
430
+ polygamma -- Polygamma function n.
431
+ multigammaln -- Returns the log of multivariate gamma, also sometimes called the generalized gamma.
432
+ digamma -- psi(x[, out]).
433
+ poch -- Rising factorial (z)_m.
434
+
435
+
436
+ Error function and Fresnel integrals
437
+ ------------------------------------
438
+
439
+ .. autosummary::
440
+ :toctree: generated/
441
+
442
+ erf -- Returns the error function of complex argument.
443
+ erfc -- Complementary error function, ``1 - erf(x)``.
444
+ erfcx -- Scaled complementary error function, ``exp(x**2) * erfc(x)``.
445
+ erfi -- Imaginary error function, ``-i erf(i z)``.
446
+ erfinv -- Inverse function for erf.
447
+ erfcinv -- Inverse function for erfc.
448
+ wofz -- Faddeeva function.
449
+ dawsn -- Dawson's integral.
450
+ fresnel -- Fresnel sin and cos integrals.
451
+ fresnel_zeros -- Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
452
+ modfresnelp -- Modified Fresnel positive integrals.
453
+ modfresnelm -- Modified Fresnel negative integrals.
454
+ voigt_profile -- Voigt profile.
455
+
456
+ The following functions do not accept NumPy arrays (they are not
457
+ universal functions):
458
+
459
+ .. autosummary::
460
+ :toctree: generated/
461
+
462
+ erf_zeros -- Compute nt complex zeros of error function erf(z).
463
+ fresnelc_zeros -- Compute nt complex zeros of cosine Fresnel integral C(z).
464
+ fresnels_zeros -- Compute nt complex zeros of sine Fresnel integral S(z).
465
+
466
+ Legendre functions
467
+ ------------------
468
+
469
+ .. autosummary::
470
+ :toctree: generated/
471
+
472
+ lpmv -- Associated Legendre function of integer order and real degree.
473
+ sph_harm -- Compute spherical harmonics.
474
+
475
+ The following functions do not accept NumPy arrays (they are not
476
+ universal functions):
477
+
478
+ .. autosummary::
479
+ :toctree: generated/
480
+
481
+ clpmn -- Associated Legendre function of the first kind for complex arguments.
482
+ lpn -- Legendre function of the first kind.
483
+ lqn -- Legendre function of the second kind.
484
+ lpmn -- Sequence of associated Legendre functions of the first kind.
485
+ lqmn -- Sequence of associated Legendre functions of the second kind.
486
+
487
+ Ellipsoidal harmonics
488
+ ---------------------
489
+
490
+ .. autosummary::
491
+ :toctree: generated/
492
+
493
+ ellip_harm -- Ellipsoidal harmonic functions E^p_n(l).
494
+ ellip_harm_2 -- Ellipsoidal harmonic functions F^p_n(l).
495
+ ellip_normal -- Ellipsoidal harmonic normalization constants gamma^p_n.
496
+
497
+ Orthogonal polynomials
498
+ ----------------------
499
+
500
+ The following functions evaluate values of orthogonal polynomials:
501
+
502
+ .. autosummary::
503
+ :toctree: generated/
504
+
505
+ assoc_laguerre -- Compute the generalized (associated) Laguerre polynomial of degree n and order k.
506
+ eval_legendre -- Evaluate Legendre polynomial at a point.
507
+ eval_chebyt -- Evaluate Chebyshev polynomial of the first kind at a point.
508
+ eval_chebyu -- Evaluate Chebyshev polynomial of the second kind at a point.
509
+ eval_chebyc -- Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a point.
510
+ eval_chebys -- Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a point.
511
+ eval_jacobi -- Evaluate Jacobi polynomial at a point.
512
+ eval_laguerre -- Evaluate Laguerre polynomial at a point.
513
+ eval_genlaguerre -- Evaluate generalized Laguerre polynomial at a point.
514
+ eval_hermite -- Evaluate physicist's Hermite polynomial at a point.
515
+ eval_hermitenorm -- Evaluate probabilist's (normalized) Hermite polynomial at a point.
516
+ eval_gegenbauer -- Evaluate Gegenbauer polynomial at a point.
517
+ eval_sh_legendre -- Evaluate shifted Legendre polynomial at a point.
518
+ eval_sh_chebyt -- Evaluate shifted Chebyshev polynomial of the first kind at a point.
519
+ eval_sh_chebyu -- Evaluate shifted Chebyshev polynomial of the second kind at a point.
520
+ eval_sh_jacobi -- Evaluate shifted Jacobi polynomial at a point.
521
+
522
+ The following functions compute roots and quadrature weights for
523
+ orthogonal polynomials:
524
+
525
+ .. autosummary::
526
+ :toctree: generated/
527
+
528
+ roots_legendre -- Gauss-Legendre quadrature.
529
+ roots_chebyt -- Gauss-Chebyshev (first kind) quadrature.
530
+ roots_chebyu -- Gauss-Chebyshev (second kind) quadrature.
531
+ roots_chebyc -- Gauss-Chebyshev (first kind) quadrature.
532
+ roots_chebys -- Gauss-Chebyshev (second kind) quadrature.
533
+ roots_jacobi -- Gauss-Jacobi quadrature.
534
+ roots_laguerre -- Gauss-Laguerre quadrature.
535
+ roots_genlaguerre -- Gauss-generalized Laguerre quadrature.
536
+ roots_hermite -- Gauss-Hermite (physicst's) quadrature.
537
+ roots_hermitenorm -- Gauss-Hermite (statistician's) quadrature.
538
+ roots_gegenbauer -- Gauss-Gegenbauer quadrature.
539
+ roots_sh_legendre -- Gauss-Legendre (shifted) quadrature.
540
+ roots_sh_chebyt -- Gauss-Chebyshev (first kind, shifted) quadrature.
541
+ roots_sh_chebyu -- Gauss-Chebyshev (second kind, shifted) quadrature.
542
+ roots_sh_jacobi -- Gauss-Jacobi (shifted) quadrature.
543
+
544
+ The functions below, in turn, return the polynomial coefficients in
545
+ ``orthopoly1d`` objects, which function similarly as `numpy.poly1d`.
546
+ The ``orthopoly1d`` class also has an attribute ``weights``, which returns
547
+ the roots, weights, and total weights for the appropriate form of Gaussian
548
+ quadrature. These are returned in an ``n x 3`` array with roots in the first
549
+ column, weights in the second column, and total weights in the final column.
550
+ Note that ``orthopoly1d`` objects are converted to `~numpy.poly1d` when doing
551
+ arithmetic, and lose information of the original orthogonal polynomial.
552
+
553
+ .. autosummary::
554
+ :toctree: generated/
555
+
556
+ legendre -- Legendre polynomial.
557
+ chebyt -- Chebyshev polynomial of the first kind.
558
+ chebyu -- Chebyshev polynomial of the second kind.
559
+ chebyc -- Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
560
+ chebys -- Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
561
+ jacobi -- Jacobi polynomial.
562
+ laguerre -- Laguerre polynomial.
563
+ genlaguerre -- Generalized (associated) Laguerre polynomial.
564
+ hermite -- Physicist's Hermite polynomial.
565
+ hermitenorm -- Normalized (probabilist's) Hermite polynomial.
566
+ gegenbauer -- Gegenbauer (ultraspherical) polynomial.
567
+ sh_legendre -- Shifted Legendre polynomial.
568
+ sh_chebyt -- Shifted Chebyshev polynomial of the first kind.
569
+ sh_chebyu -- Shifted Chebyshev polynomial of the second kind.
570
+ sh_jacobi -- Shifted Jacobi polynomial.
571
+
572
+ .. warning::
573
+
574
+ Computing values of high-order polynomials (around ``order > 20``) using
575
+ polynomial coefficients is numerically unstable. To evaluate polynomial
576
+ values, the ``eval_*`` functions should be used instead.
577
+
578
+
579
+ Hypergeometric functions
580
+ ------------------------
581
+
582
+ .. autosummary::
583
+ :toctree: generated/
584
+
585
+ hyp2f1 -- Gauss hypergeometric function 2F1(a, b; c; z).
586
+ hyp1f1 -- Confluent hypergeometric function 1F1(a, b; x).
587
+ hyperu -- Confluent hypergeometric function U(a, b, x) of the second kind.
588
+ hyp0f1 -- Confluent hypergeometric limit function 0F1.
589
+
590
+
591
+ Parabolic cylinder functions
592
+ ----------------------------
593
+
594
+ .. autosummary::
595
+ :toctree: generated/
596
+
597
+ pbdv -- Parabolic cylinder function D.
598
+ pbvv -- Parabolic cylinder function V.
599
+ pbwa -- Parabolic cylinder function W.
600
+
601
+ The following functions do not accept NumPy arrays (they are not
602
+ universal functions):
603
+
604
+ .. autosummary::
605
+ :toctree: generated/
606
+
607
+ pbdv_seq -- Parabolic cylinder functions Dv(x) and derivatives.
608
+ pbvv_seq -- Parabolic cylinder functions Vv(x) and derivatives.
609
+ pbdn_seq -- Parabolic cylinder functions Dn(z) and derivatives.
610
+
611
+ Mathieu and related functions
612
+ -----------------------------
613
+
614
+ .. autosummary::
615
+ :toctree: generated/
616
+
617
+ mathieu_a -- Characteristic value of even Mathieu functions.
618
+ mathieu_b -- Characteristic value of odd Mathieu functions.
619
+
620
+ The following functions do not accept NumPy arrays (they are not
621
+ universal functions):
622
+
623
+ .. autosummary::
624
+ :toctree: generated/
625
+
626
+ mathieu_even_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions.
627
+ mathieu_odd_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions.
628
+
629
+ The following return both function and first derivative:
630
+
631
+ .. autosummary::
632
+ :toctree: generated/
633
+
634
+ mathieu_cem -- Even Mathieu function and its derivative.
635
+ mathieu_sem -- Odd Mathieu function and its derivative.
636
+ mathieu_modcem1 -- Even modified Mathieu function of the first kind and its derivative.
637
+ mathieu_modcem2 -- Even modified Mathieu function of the second kind and its derivative.
638
+ mathieu_modsem1 -- Odd modified Mathieu function of the first kind and its derivative.
639
+ mathieu_modsem2 -- Odd modified Mathieu function of the second kind and its derivative.
640
+
641
+ Spheroidal wave functions
642
+ -------------------------
643
+
644
+ .. autosummary::
645
+ :toctree: generated/
646
+
647
+ pro_ang1 -- Prolate spheroidal angular function of the first kind and its derivative.
648
+ pro_rad1 -- Prolate spheroidal radial function of the first kind and its derivative.
649
+ pro_rad2 -- Prolate spheroidal radial function of the second kind and its derivative.
650
+ obl_ang1 -- Oblate spheroidal angular function of the first kind and its derivative.
651
+ obl_rad1 -- Oblate spheroidal radial function of the first kind and its derivative.
652
+ obl_rad2 -- Oblate spheroidal radial function of the second kind and its derivative.
653
+ pro_cv -- Characteristic value of prolate spheroidal function.
654
+ obl_cv -- Characteristic value of oblate spheroidal function.
655
+ pro_cv_seq -- Characteristic values for prolate spheroidal wave functions.
656
+ obl_cv_seq -- Characteristic values for oblate spheroidal wave functions.
657
+
658
+ The following functions require pre-computed characteristic value:
659
+
660
+ .. autosummary::
661
+ :toctree: generated/
662
+
663
+ pro_ang1_cv -- Prolate spheroidal angular function pro_ang1 for precomputed characteristic value.
664
+ pro_rad1_cv -- Prolate spheroidal radial function pro_rad1 for precomputed characteristic value.
665
+ pro_rad2_cv -- Prolate spheroidal radial function pro_rad2 for precomputed characteristic value.
666
+ obl_ang1_cv -- Oblate spheroidal angular function obl_ang1 for precomputed characteristic value.
667
+ obl_rad1_cv -- Oblate spheroidal radial function obl_rad1 for precomputed characteristic value.
668
+ obl_rad2_cv -- Oblate spheroidal radial function obl_rad2 for precomputed characteristic value.
669
+
670
+ Kelvin functions
671
+ ----------------
672
+
673
+ .. autosummary::
674
+ :toctree: generated/
675
+
676
+ kelvin -- Kelvin functions as complex numbers.
677
+ kelvin_zeros -- Compute nt zeros of all Kelvin functions.
678
+ ber -- Kelvin function ber.
679
+ bei -- Kelvin function bei
680
+ berp -- Derivative of the Kelvin function `ber`.
681
+ beip -- Derivative of the Kelvin function `bei`.
682
+ ker -- Kelvin function ker.
683
+ kei -- Kelvin function ker.
684
+ kerp -- Derivative of the Kelvin function ker.
685
+ keip -- Derivative of the Kelvin function kei.
686
+
687
+ The following functions do not accept NumPy arrays (they are not
688
+ universal functions):
689
+
690
+ .. autosummary::
691
+ :toctree: generated/
692
+
693
+ ber_zeros -- Compute nt zeros of the Kelvin function ber(x).
694
+ bei_zeros -- Compute nt zeros of the Kelvin function bei(x).
695
+ berp_zeros -- Compute nt zeros of the Kelvin function ber'(x).
696
+ beip_zeros -- Compute nt zeros of the Kelvin function bei'(x).
697
+ ker_zeros -- Compute nt zeros of the Kelvin function ker(x).
698
+ kei_zeros -- Compute nt zeros of the Kelvin function kei(x).
699
+ kerp_zeros -- Compute nt zeros of the Kelvin function ker'(x).
700
+ keip_zeros -- Compute nt zeros of the Kelvin function kei'(x).
701
+
702
+ Combinatorics
703
+ -------------
704
+
705
+ .. autosummary::
706
+ :toctree: generated/
707
+
708
+ comb -- The number of combinations of N things taken k at a time.
709
+ perm -- Permutations of N things taken k at a time, i.e., k-permutations of N.
710
+ stirling2 -- Stirling numbers of the second kind.
711
+
712
+ Lambert W and related functions
713
+ -------------------------------
714
+
715
+ .. autosummary::
716
+ :toctree: generated/
717
+
718
+ lambertw -- Lambert W function.
719
+ wrightomega -- Wright Omega function.
720
+
721
+ Other special functions
722
+ -----------------------
723
+
724
+ .. autosummary::
725
+ :toctree: generated/
726
+
727
+ agm -- Arithmetic, Geometric Mean.
728
+ bernoulli -- Bernoulli numbers B0..Bn (inclusive).
729
+ binom -- Binomial coefficient
730
+ diric -- Periodic sinc function, also called the Dirichlet function.
731
+ euler -- Euler numbers E0..En (inclusive).
732
+ expn -- Exponential integral E_n.
733
+ exp1 -- Exponential integral E_1 of complex argument z.
734
+ expi -- Exponential integral Ei.
735
+ factorial -- The factorial of a number or array of numbers.
736
+ factorial2 -- Double factorial.
737
+ factorialk -- Multifactorial of n of order k, n(!!...!).
738
+ shichi -- Hyperbolic sine and cosine integrals.
739
+ sici -- Sine and cosine integrals.
740
+ softmax -- Softmax function.
741
+ log_softmax -- Logarithm of softmax function.
742
+ spence -- Spence's function, also known as the dilogarithm.
743
+ zeta -- Riemann zeta function.
744
+ zetac -- Riemann zeta function minus 1.
745
+
746
+ Convenience functions
747
+ ---------------------
748
+
749
+ .. autosummary::
750
+ :toctree: generated/
751
+
752
+ cbrt -- Cube root of `x`.
753
+ exp10 -- 10**x.
754
+ exp2 -- 2**x.
755
+ radian -- Convert from degrees to radians.
756
+ cosdg -- Cosine of the angle `x` given in degrees.
757
+ sindg -- Sine of angle given in degrees.
758
+ tandg -- Tangent of angle x given in degrees.
759
+ cotdg -- Cotangent of the angle `x` given in degrees.
760
+ log1p -- Calculates log(1+x) for use when `x` is near zero.
761
+ expm1 -- ``exp(x) - 1`` for use when `x` is near zero.
762
+ cosm1 -- ``cos(x) - 1`` for use when `x` is near zero.
763
+ powm1 -- ``x**y - 1`` for use when `y` is near zero or `x` is near 1.
764
+ round -- Round to nearest integer.
765
+ xlogy -- Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
766
+ xlog1py -- Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
767
+ logsumexp -- Compute the log of the sum of exponentials of input elements.
768
+ exprel -- Relative error exponential, (exp(x)-1)/x, for use when `x` is near zero.
769
+ sinc -- Return the sinc function.
770
+
771
+ """ # noqa: E501
772
+
773
+ import warnings
774
+
775
+ from ._sf_error import SpecialFunctionWarning, SpecialFunctionError
776
+
777
+ from . import _ufuncs
778
+ from ._ufuncs import *
779
+
780
+ # Replace some function definitions from _ufuncs to add Array API support
781
+ from ._support_alternative_backends import (
782
+ log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e,
783
+ gammaln, gammainc, gammaincc, logit, expit)
784
+
785
+ from . import _basic
786
+ from ._basic import *
787
+
788
+ from ._logsumexp import logsumexp, softmax, log_softmax
789
+
790
+ from . import _orthogonal
791
+ from ._orthogonal import *
792
+
793
+ from ._spfun_stats import multigammaln
794
+ from ._ellip_harm import (
795
+ ellip_harm,
796
+ ellip_harm_2,
797
+ ellip_normal
798
+ )
799
+ from ._lambertw import lambertw
800
+ from ._spherical_bessel import (
801
+ spherical_jn,
802
+ spherical_yn,
803
+ spherical_in,
804
+ spherical_kn
805
+ )
806
+
807
+ # Deprecated namespaces, to be removed in v2.0.0
808
+ from . import add_newdocs, basic, orthogonal, specfun, sf_error, spfun_stats
809
+
810
+ # We replace some function definitions from _ufuncs with those from
811
+ # _support_alternative_backends above, but those are all listed in _ufuncs.__all__,
812
+ # so there is no need to consider _support_alternative_backends.__all__ here.
813
+ __all__ = _ufuncs.__all__ + _basic.__all__ + _orthogonal.__all__
814
+ __all__ += [
815
+ 'SpecialFunctionWarning',
816
+ 'SpecialFunctionError',
817
+ 'logsumexp',
818
+ 'softmax',
819
+ 'log_softmax',
820
+ 'multigammaln',
821
+ 'ellip_harm',
822
+ 'ellip_harm_2',
823
+ 'ellip_normal',
824
+ 'lambertw',
825
+ 'spherical_jn',
826
+ 'spherical_yn',
827
+ 'spherical_in',
828
+ 'spherical_kn',
829
+ ]
830
+
831
+ from scipy._lib._testutils import PytestTester
832
+ test = PytestTester(__name__)
833
+ del PytestTester
834
+
835
+ _depr_msg = ('\nThis function was deprecated in SciPy 1.12.0, and will be '
836
+ 'removed in SciPy 1.14.0. Use scipy.special.{} instead.')
837
+
838
+
839
+ def btdtr(*args, **kwargs): # type: ignore [no-redef]
840
+ warnings.warn(_depr_msg.format('betainc'), category=DeprecationWarning,
841
+ stacklevel=2)
842
+ return _ufuncs.btdtr(*args, **kwargs)
843
+
844
+
845
+ btdtr.__doc__ = _ufuncs.btdtr.__doc__ # type: ignore [misc]
846
+
847
+
848
+ def btdtri(*args, **kwargs): # type: ignore [no-redef]
849
+ warnings.warn(_depr_msg.format('betaincinv'), category=DeprecationWarning,
850
+ stacklevel=2)
851
+ return _ufuncs.btdtri(*args, **kwargs)
852
+
853
+
854
+ btdtri.__doc__ = _ufuncs.btdtri.__doc__ # type: ignore [misc]
855
+
856
+
857
+ def _get_include():
858
+ """This function is for development purposes only.
859
+
860
+ This function could disappear or its behavior could change at any time.
861
+ """
862
+ import os
863
+ return os.path.dirname(__file__)
venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (31.7 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-310.pyc ADDED
Binary file (396 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/_basic.cpython-310.pyc ADDED
Binary file (95.7 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc ADDED
Binary file (5.81 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc ADDED
Binary file (4.15 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc ADDED
Binary file (762 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/_testutils.cpython-310.pyc ADDED
Binary file (8.57 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc ADDED
Binary file (635 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc ADDED
Binary file (1.26 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc ADDED
Binary file (648 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc ADDED
Binary file (760 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/scipy/special/_basic.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/scipy/special/_cdflib.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (188 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (63.5 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ._ufuncs import _ellip_harm
4
+ from ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm
5
+
6
+
7
+ def ellip_harm(h2, k2, n, p, s, signm=1, signn=1):
8
+ r"""
9
+ Ellipsoidal harmonic functions E^p_n(l)
10
+
11
+ These are also known as Lame functions of the first kind, and are
12
+ solutions to the Lame equation:
13
+
14
+ .. math:: (s^2 - h^2)(s^2 - k^2)E''(s)
15
+ + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
16
+
17
+ where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
18
+ returned) corresponding to the solutions.
19
+
20
+ Parameters
21
+ ----------
22
+ h2 : float
23
+ ``h**2``
24
+ k2 : float
25
+ ``k**2``; should be larger than ``h**2``
26
+ n : int
27
+ Degree
28
+ s : float
29
+ Coordinate
30
+ p : int
31
+ Order, can range between [1,2n+1]
32
+ signm : {1, -1}, optional
33
+ Sign of prefactor of functions. Can be +/-1. See Notes.
34
+ signn : {1, -1}, optional
35
+ Sign of prefactor of functions. Can be +/-1. See Notes.
36
+
37
+ Returns
38
+ -------
39
+ E : float
40
+ the harmonic :math:`E^p_n(s)`
41
+
42
+ See Also
43
+ --------
44
+ ellip_harm_2, ellip_normal
45
+
46
+ Notes
47
+ -----
48
+ The geometric interpretation of the ellipsoidal functions is
49
+ explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the
50
+ sign of prefactors for functions according to their type::
51
+
52
+ K : +1
53
+ L : signm
54
+ M : signn
55
+ N : signm*signn
56
+
57
+ .. versionadded:: 0.15.0
58
+
59
+ References
60
+ ----------
61
+ .. [1] Digital Library of Mathematical Functions 29.12
62
+ https://dlmf.nist.gov/29.12
63
+ .. [2] Bardhan and Knepley, "Computational science and
64
+ re-discovery: open-source implementations of
65
+ ellipsoidal harmonics for problems in potential theory",
66
+ Comput. Sci. Disc. 5, 014006 (2012)
67
+ :doi:`10.1088/1749-4699/5/1/014006`.
68
+ .. [3] David J.and Dechambre P, "Computation of Ellipsoidal
69
+ Gravity Field Harmonics for small solar system bodies"
70
+ pp. 30-36, 2000
71
+ .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
72
+ pp. 418, 2012
73
+
74
+ Examples
75
+ --------
76
+ >>> from scipy.special import ellip_harm
77
+ >>> w = ellip_harm(5,8,1,1,2.5)
78
+ >>> w
79
+ 2.5
80
+
81
+ Check that the functions indeed are solutions to the Lame equation:
82
+
83
+ >>> import numpy as np
84
+ >>> from scipy.interpolate import UnivariateSpline
85
+ >>> def eigenvalue(f, df, ddf):
86
+ ... r = (((s**2 - h**2) * (s**2 - k**2) * ddf
87
+ ... + s * (2*s**2 - h**2 - k**2) * df
88
+ ... - n * (n + 1)*s**2*f) / f)
89
+ ... return -r.mean(), r.std()
90
+ >>> s = np.linspace(0.1, 10, 200)
91
+ >>> k, h, n, p = 8.0, 2.2, 3, 2
92
+ >>> E = ellip_harm(h**2, k**2, n, p, s)
93
+ >>> E_spl = UnivariateSpline(s, E)
94
+ >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
95
+ >>> a, a_err
96
+ (583.44366156701483, 6.4580890640310646e-11)
97
+
98
+ """ # noqa: E501
99
+ return _ellip_harm(h2, k2, n, p, s, signm, signn)
100
+
101
+
102
+ _ellip_harm_2_vec = np.vectorize(_ellipsoid, otypes='d')
103
+
104
+
105
+ def ellip_harm_2(h2, k2, n, p, s):
106
+ r"""
107
+ Ellipsoidal harmonic functions F^p_n(l)
108
+
109
+ These are also known as Lame functions of the second kind, and are
110
+ solutions to the Lame equation:
111
+
112
+ .. math:: (s^2 - h^2)(s^2 - k^2)F''(s)
113
+ + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0
114
+
115
+ where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
116
+ returned) corresponding to the solutions.
117
+
118
+ Parameters
119
+ ----------
120
+ h2 : float
121
+ ``h**2``
122
+ k2 : float
123
+ ``k**2``; should be larger than ``h**2``
124
+ n : int
125
+ Degree.
126
+ p : int
127
+ Order, can range between [1,2n+1].
128
+ s : float
129
+ Coordinate
130
+
131
+ Returns
132
+ -------
133
+ F : float
134
+ The harmonic :math:`F^p_n(s)`
135
+
136
+ See Also
137
+ --------
138
+ ellip_harm, ellip_normal
139
+
140
+ Notes
141
+ -----
142
+ Lame functions of the second kind are related to the functions of the first kind:
143
+
144
+ .. math::
145
+
146
+ F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s}
147
+ \frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}}
148
+
149
+ .. versionadded:: 0.15.0
150
+
151
+ Examples
152
+ --------
153
+ >>> from scipy.special import ellip_harm_2
154
+ >>> w = ellip_harm_2(5,8,2,1,10)
155
+ >>> w
156
+ 0.00108056853382
157
+
158
+ """
159
+ with np.errstate(all='ignore'):
160
+ return _ellip_harm_2_vec(h2, k2, n, p, s)
161
+
162
+
163
+ def _ellip_normal_vec(h2, k2, n, p):
164
+ return _ellipsoid_norm(h2, k2, n, p)
165
+
166
+
167
+ _ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d')
168
+
169
+
170
+ def ellip_normal(h2, k2, n, p):
171
+ r"""
172
+ Ellipsoidal harmonic normalization constants gamma^p_n
173
+
174
+ The normalization constant is defined as
175
+
176
+ .. math::
177
+
178
+ \gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy
179
+ \frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)}
180
+
181
+ Parameters
182
+ ----------
183
+ h2 : float
184
+ ``h**2``
185
+ k2 : float
186
+ ``k**2``; should be larger than ``h**2``
187
+ n : int
188
+ Degree.
189
+ p : int
190
+ Order, can range between [1,2n+1].
191
+
192
+ Returns
193
+ -------
194
+ gamma : float
195
+ The normalization constant :math:`\gamma^p_n`
196
+
197
+ See Also
198
+ --------
199
+ ellip_harm, ellip_harm_2
200
+
201
+ Notes
202
+ -----
203
+ .. versionadded:: 0.15.0
204
+
205
+ Examples
206
+ --------
207
+ >>> from scipy.special import ellip_normal
208
+ >>> w = ellip_normal(5,8,3,7)
209
+ >>> w
210
+ 1723.38796997
211
+
212
+ """
213
+ with np.errstate(all='ignore'):
214
+ return _ellip_normal_vec(h2, k2, n, p)
venv/lib/python3.10/site-packages/scipy/special/_ellip_harm_2.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (138 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_lambertw.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._ufuncs import _lambertw
2
+
3
+ import numpy as np
4
+
5
+
6
+ def lambertw(z, k=0, tol=1e-8):
7
+ r"""
8
+ lambertw(z, k=0, tol=1e-8)
9
+
10
+ Lambert W function.
11
+
12
+ The Lambert W function `W(z)` is defined as the inverse function
13
+ of ``w * exp(w)``. In other words, the value of ``W(z)`` is
14
+ such that ``z = W(z) * exp(W(z))`` for any complex number
15
+ ``z``.
16
+
17
+ The Lambert W function is a multivalued function with infinitely
18
+ many branches. Each branch gives a separate solution of the
19
+ equation ``z = w exp(w)``. Here, the branches are indexed by the
20
+ integer `k`.
21
+
22
+ Parameters
23
+ ----------
24
+ z : array_like
25
+ Input argument.
26
+ k : int, optional
27
+ Branch index.
28
+ tol : float, optional
29
+ Evaluation tolerance.
30
+
31
+ Returns
32
+ -------
33
+ w : array
34
+ `w` will have the same shape as `z`.
35
+
36
+ See Also
37
+ --------
38
+ wrightomega : the Wright Omega function
39
+
40
+ Notes
41
+ -----
42
+ All branches are supported by `lambertw`:
43
+
44
+ * ``lambertw(z)`` gives the principal solution (branch 0)
45
+ * ``lambertw(z, k)`` gives the solution on branch `k`
46
+
47
+ The Lambert W function has two partially real branches: the
48
+ principal branch (`k = 0`) is real for real ``z > -1/e``, and the
49
+ ``k = -1`` branch is real for ``-1/e < z < 0``. All branches except
50
+ ``k = 0`` have a logarithmic singularity at ``z = 0``.
51
+
52
+ **Possible issues**
53
+
54
+ The evaluation can become inaccurate very close to the branch point
55
+ at ``-1/e``. In some corner cases, `lambertw` might currently
56
+ fail to converge, or can end up on the wrong branch.
57
+
58
+ **Algorithm**
59
+
60
+ Halley's iteration is used to invert ``w * exp(w)``, using a first-order
61
+ asymptotic approximation (O(log(w)) or `O(w)`) as the initial estimate.
62
+
63
+ The definition, implementation and choice of branches is based on [2]_.
64
+
65
+ References
66
+ ----------
67
+ .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
68
+ .. [2] Corless et al, "On the Lambert W function", Adv. Comp. Math. 5
69
+ (1996) 329-359.
70
+ https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
71
+
72
+ Examples
73
+ --------
74
+ The Lambert W function is the inverse of ``w exp(w)``:
75
+
76
+ >>> import numpy as np
77
+ >>> from scipy.special import lambertw
78
+ >>> w = lambertw(1)
79
+ >>> w
80
+ (0.56714329040978384+0j)
81
+ >>> w * np.exp(w)
82
+ (1.0+0j)
83
+
84
+ Any branch gives a valid inverse:
85
+
86
+ >>> w = lambertw(1, k=3)
87
+ >>> w
88
+ (-2.8535817554090377+17.113535539412148j)
89
+ >>> w*np.exp(w)
90
+ (1.0000000000000002+1.609823385706477e-15j)
91
+
92
+ **Applications to equation-solving**
93
+
94
+ The Lambert W function may be used to solve various kinds of
95
+ equations. We give two examples here.
96
+
97
+ First, the function can be used to solve implicit equations of the
98
+ form
99
+
100
+ :math:`x = a + b e^{c x}`
101
+
102
+ for :math:`x`. We assume :math:`c` is not zero. After a little
103
+ algebra, the equation may be written
104
+
105
+ :math:`z e^z = -b c e^{a c}`
106
+
107
+ where :math:`z = c (a - x)`. :math:`z` may then be expressed using
108
+ the Lambert W function
109
+
110
+ :math:`z = W(-b c e^{a c})`
111
+
112
+ giving
113
+
114
+ :math:`x = a - W(-b c e^{a c})/c`
115
+
116
+ For example,
117
+
118
+ >>> a = 3
119
+ >>> b = 2
120
+ >>> c = -0.5
121
+
122
+ The solution to :math:`x = a + b e^{c x}` is:
123
+
124
+ >>> x = a - lambertw(-b*c*np.exp(a*c))/c
125
+ >>> x
126
+ (3.3707498368978794+0j)
127
+
128
+ Verify that it solves the equation:
129
+
130
+ >>> a + b*np.exp(c*x)
131
+ (3.37074983689788+0j)
132
+
133
+ The Lambert W function may also be used find the value of the infinite
134
+ power tower :math:`z^{z^{z^{\ldots}}}`:
135
+
136
+ >>> def tower(z, n):
137
+ ... if n == 0:
138
+ ... return z
139
+ ... return z ** tower(z, n-1)
140
+ ...
141
+ >>> tower(0.5, 100)
142
+ 0.641185744504986
143
+ >>> -lambertw(-np.log(0.5)) / np.log(0.5)
144
+ (0.64118574450498589+0j)
145
+ """
146
+ # TODO: special expert should inspect this
147
+ # interception; better place to do it?
148
+ k = np.asarray(k, dtype=np.dtype("long"))
149
+ return _lambertw(z, k, tol)
venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy._lib._util import _asarray_validated
3
+
4
+ __all__ = ["logsumexp", "softmax", "log_softmax"]
5
+
6
+
7
+ def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):
8
+ """Compute the log of the sum of exponentials of input elements.
9
+
10
+ Parameters
11
+ ----------
12
+ a : array_like
13
+ Input array.
14
+ axis : None or int or tuple of ints, optional
15
+ Axis or axes over which the sum is taken. By default `axis` is None,
16
+ and all elements are summed.
17
+
18
+ .. versionadded:: 0.11.0
19
+ b : array-like, optional
20
+ Scaling factor for exp(`a`) must be of the same shape as `a` or
21
+ broadcastable to `a`. These values may be negative in order to
22
+ implement subtraction.
23
+
24
+ .. versionadded:: 0.12.0
25
+ keepdims : bool, optional
26
+ If this is set to True, the axes which are reduced are left in the
27
+ result as dimensions with size one. With this option, the result
28
+ will broadcast correctly against the original array.
29
+
30
+ .. versionadded:: 0.15.0
31
+ return_sign : bool, optional
32
+ If this is set to True, the result will be a pair containing sign
33
+ information; if False, results that are negative will be returned
34
+ as NaN. Default is False (no sign information).
35
+
36
+ .. versionadded:: 0.16.0
37
+
38
+ Returns
39
+ -------
40
+ res : ndarray
41
+ The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically
42
+ more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))``
43
+ is returned. If ``return_sign`` is True, ``res`` contains the log of
44
+ the absolute value of the argument.
45
+ sgn : ndarray
46
+ If ``return_sign`` is True, this will be an array of floating-point
47
+ numbers matching res containing +1, 0, -1 (for real-valued inputs)
48
+ or a complex phase (for complex inputs). This gives the sign of the
49
+ argument of the logarithm in ``res``.
50
+ If ``return_sign`` is False, only one result is returned.
51
+
52
+ See Also
53
+ --------
54
+ numpy.logaddexp, numpy.logaddexp2
55
+
56
+ Notes
57
+ -----
58
+ NumPy has a logaddexp function which is very similar to `logsumexp`, but
59
+ only handles two arguments. `logaddexp.reduce` is similar to this
60
+ function, but may be less stable.
61
+
62
+ Examples
63
+ --------
64
+ >>> import numpy as np
65
+ >>> from scipy.special import logsumexp
66
+ >>> a = np.arange(10)
67
+ >>> logsumexp(a)
68
+ 9.4586297444267107
69
+ >>> np.log(np.sum(np.exp(a)))
70
+ 9.4586297444267107
71
+
72
+ With weights
73
+
74
+ >>> a = np.arange(10)
75
+ >>> b = np.arange(10, 0, -1)
76
+ >>> logsumexp(a, b=b)
77
+ 9.9170178533034665
78
+ >>> np.log(np.sum(b*np.exp(a)))
79
+ 9.9170178533034647
80
+
81
+ Returning a sign flag
82
+
83
+ >>> logsumexp([1,2],b=[1,-1],return_sign=True)
84
+ (1.5413248546129181, -1.0)
85
+
86
+ Notice that `logsumexp` does not directly support masked arrays. To use it
87
+ on a masked array, convert the mask into zero weights:
88
+
89
+ >>> a = np.ma.array([np.log(2), 2, np.log(3)],
90
+ ... mask=[False, True, False])
91
+ >>> b = (~a.mask).astype(int)
92
+ >>> logsumexp(a.data, b=b), np.log(5)
93
+ 1.6094379124341005, 1.6094379124341005
94
+
95
+ """
96
+ a = _asarray_validated(a, check_finite=False)
97
+ if b is not None:
98
+ a, b = np.broadcast_arrays(a, b)
99
+ if np.any(b == 0):
100
+ a = a + 0. # promote to at least float
101
+ a[b == 0] = -np.inf
102
+
103
+ # Scale by real part for complex inputs, because this affects
104
+ # the magnitude of the exponential.
105
+ a_max = np.amax(a.real, axis=axis, keepdims=True)
106
+
107
+ if a_max.ndim > 0:
108
+ a_max[~np.isfinite(a_max)] = 0
109
+ elif not np.isfinite(a_max):
110
+ a_max = 0
111
+
112
+ if b is not None:
113
+ b = np.asarray(b)
114
+ tmp = b * np.exp(a - a_max)
115
+ else:
116
+ tmp = np.exp(a - a_max)
117
+
118
+ # suppress warnings about log of zero
119
+ with np.errstate(divide='ignore'):
120
+ s = np.sum(tmp, axis=axis, keepdims=keepdims)
121
+ if return_sign:
122
+ # For complex, use the numpy>=2.0 convention for sign.
123
+ if np.issubdtype(s.dtype, np.complexfloating):
124
+ sgn = s / np.where(s == 0, 1, abs(s))
125
+ else:
126
+ sgn = np.sign(s)
127
+ s = abs(s)
128
+ out = np.log(s)
129
+
130
+ if not keepdims:
131
+ a_max = np.squeeze(a_max, axis=axis)
132
+ out += a_max
133
+
134
+ if return_sign:
135
+ return out, sgn
136
+ else:
137
+ return out
138
+
139
+
140
+ def softmax(x, axis=None):
141
+ r"""Compute the softmax function.
142
+
143
+ The softmax function transforms each element of a collection by
144
+ computing the exponential of each element divided by the sum of the
145
+ exponentials of all the elements. That is, if `x` is a one-dimensional
146
+ numpy array::
147
+
148
+ softmax(x) = np.exp(x)/sum(np.exp(x))
149
+
150
+ Parameters
151
+ ----------
152
+ x : array_like
153
+ Input array.
154
+ axis : int or tuple of ints, optional
155
+ Axis to compute values along. Default is None and softmax will be
156
+ computed over the entire array `x`.
157
+
158
+ Returns
159
+ -------
160
+ s : ndarray
161
+ An array the same shape as `x`. The result will sum to 1 along the
162
+ specified axis.
163
+
164
+ Notes
165
+ -----
166
+ The formula for the softmax function :math:`\sigma(x)` for a vector
167
+ :math:`x = \{x_0, x_1, ..., x_{n-1}\}` is
168
+
169
+ .. math:: \sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}
170
+
171
+ The `softmax` function is the gradient of `logsumexp`.
172
+
173
+ The implementation uses shifting to avoid overflow. See [1]_ for more
174
+ details.
175
+
176
+ .. versionadded:: 1.2.0
177
+
178
+ References
179
+ ----------
180
+ .. [1] P. Blanchard, D.J. Higham, N.J. Higham, "Accurately computing the
181
+ log-sum-exp and softmax functions", IMA Journal of Numerical Analysis,
182
+ Vol.41(4), :doi:`10.1093/imanum/draa038`.
183
+
184
+ Examples
185
+ --------
186
+ >>> import numpy as np
187
+ >>> from scipy.special import softmax
188
+ >>> np.set_printoptions(precision=5)
189
+
190
+ >>> x = np.array([[1, 0.5, 0.2, 3],
191
+ ... [1, -1, 7, 3],
192
+ ... [2, 12, 13, 3]])
193
+ ...
194
+
195
+ Compute the softmax transformation over the entire array.
196
+
197
+ >>> m = softmax(x)
198
+ >>> m
199
+ array([[ 4.48309e-06, 2.71913e-06, 2.01438e-06, 3.31258e-05],
200
+ [ 4.48309e-06, 6.06720e-07, 1.80861e-03, 3.31258e-05],
201
+ [ 1.21863e-05, 2.68421e-01, 7.29644e-01, 3.31258e-05]])
202
+
203
+ >>> m.sum()
204
+ 1.0
205
+
206
+ Compute the softmax transformation along the first axis (i.e., the
207
+ columns).
208
+
209
+ >>> m = softmax(x, axis=0)
210
+
211
+ >>> m
212
+ array([[ 2.11942e-01, 1.01300e-05, 2.75394e-06, 3.33333e-01],
213
+ [ 2.11942e-01, 2.26030e-06, 2.47262e-03, 3.33333e-01],
214
+ [ 5.76117e-01, 9.99988e-01, 9.97525e-01, 3.33333e-01]])
215
+
216
+ >>> m.sum(axis=0)
217
+ array([ 1., 1., 1., 1.])
218
+
219
+ Compute the softmax transformation along the second axis (i.e., the rows).
220
+
221
+ >>> m = softmax(x, axis=1)
222
+ >>> m
223
+ array([[ 1.05877e-01, 6.42177e-02, 4.75736e-02, 7.82332e-01],
224
+ [ 2.42746e-03, 3.28521e-04, 9.79307e-01, 1.79366e-02],
225
+ [ 1.22094e-05, 2.68929e-01, 7.31025e-01, 3.31885e-05]])
226
+
227
+ >>> m.sum(axis=1)
228
+ array([ 1., 1., 1.])
229
+
230
+ """
231
+ x = _asarray_validated(x, check_finite=False)
232
+ x_max = np.amax(x, axis=axis, keepdims=True)
233
+ exp_x_shifted = np.exp(x - x_max)
234
+ return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
235
+
236
+
237
+ def log_softmax(x, axis=None):
238
+ r"""Compute the logarithm of the softmax function.
239
+
240
+ In principle::
241
+
242
+ log_softmax(x) = log(softmax(x))
243
+
244
+ but using a more accurate implementation.
245
+
246
+ Parameters
247
+ ----------
248
+ x : array_like
249
+ Input array.
250
+ axis : int or tuple of ints, optional
251
+ Axis to compute values along. Default is None and softmax will be
252
+ computed over the entire array `x`.
253
+
254
+ Returns
255
+ -------
256
+ s : ndarray or scalar
257
+ An array with the same shape as `x`. Exponential of the result will
258
+ sum to 1 along the specified axis. If `x` is a scalar, a scalar is
259
+ returned.
260
+
261
+ Notes
262
+ -----
263
+ `log_softmax` is more accurate than ``np.log(softmax(x))`` with inputs that
264
+ make `softmax` saturate (see examples below).
265
+
266
+ .. versionadded:: 1.5.0
267
+
268
+ Examples
269
+ --------
270
+ >>> import numpy as np
271
+ >>> from scipy.special import log_softmax
272
+ >>> from scipy.special import softmax
273
+ >>> np.set_printoptions(precision=5)
274
+
275
+ >>> x = np.array([1000.0, 1.0])
276
+
277
+ >>> y = log_softmax(x)
278
+ >>> y
279
+ array([ 0., -999.])
280
+
281
+ >>> with np.errstate(divide='ignore'):
282
+ ... y = np.log(softmax(x))
283
+ ...
284
+ >>> y
285
+ array([ 0., -inf])
286
+
287
+ """
288
+
289
+ x = _asarray_validated(x, check_finite=False)
290
+
291
+ x_max = np.amax(x, axis=axis, keepdims=True)
292
+
293
+ if x_max.ndim > 0:
294
+ x_max[~np.isfinite(x_max)] = 0
295
+ elif not np.isfinite(x_max):
296
+ x_max = 0
297
+
298
+ tmp = x - x_max
299
+ exp_tmp = np.exp(tmp)
300
+
301
+ # suppress warnings about log of zero
302
+ with np.errstate(divide='ignore'):
303
+ s = np.sum(exp_tmp, axis=axis, keepdims=True)
304
+ out = np.log(s)
305
+
306
+ out = tmp - out
307
+ return out