This commit is contained in:
2024-11-29 18:15:30 +00:00
parent 40aade2d8e
commit bc9415586e
5298 changed files with 1938676 additions and 80 deletions

View File

@ -0,0 +1,67 @@
"""
==========================================
Miscellaneous routines (:mod:`scipy.misc`)
==========================================
.. currentmodule:: scipy.misc
.. deprecated:: 1.10.0
This module is deprecated and will be completely
removed in SciPy v2.0.0.
Various utilities that don't have another home.
.. autosummary::
:toctree: generated/
ascent - Get example image for processing
central_diff_weights - Weights for an n-point central mth derivative
derivative - Find the nth derivative of a function at a point
face - Get example image for processing
electrocardiogram - Load an example of a 1-D signal
"""
from ._common import *
from . import _common
import warnings
# Deprecated namespaces, to be removed in v2.0.0
from . import common, doccer
__all__ = _common.__all__
dataset_methods = ['ascent', 'face', 'electrocardiogram']
def __dir__():
return __all__
def __getattr__(name):
if name not in __all__:
raise AttributeError(
"scipy.misc is deprecated and has no attribute "
f"{name}.")
if name in dataset_methods:
msg = ("The module `scipy.misc` is deprecated and will be "
"completely removed in SciPy v2.0.0. "
f"All dataset methods including {name}, must be imported "
"directly from the new `scipy.datasets` module.")
else:
msg = (f"The method `{name}` from the `scipy.misc` namespace is"
" deprecated, and will be removed in SciPy v1.12.0.")
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return getattr(name)
del _common
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester

View File

@ -0,0 +1,344 @@
"""
Functions which are common and require SciPy Base and Level 1 SciPy
(special, linalg)
"""
from scipy._lib.deprecation import _deprecated
from scipy._lib._finite_differences import _central_diff_weights, _derivative
from numpy import array, frombuffer, load
__all__ = ['central_diff_weights', 'derivative', 'ascent', 'face',
'electrocardiogram']
@_deprecated(msg="scipy.misc.central_diff_weights is deprecated in "
"SciPy v1.10.0; and will be completely removed in "
"SciPy v1.12.0. You may consider using "
"findiff: https://github.com/maroba/findiff or "
"numdifftools: https://github.com/pbrod/numdifftools")
def central_diff_weights(Np, ndiv=1):
"""
Return weights for an Np-point central derivative.
Assumes equally-spaced function points.
If weights are in the vector w, then
derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx)
.. deprecated:: 1.10.0
`central_diff_weights` has been deprecated from
`scipy.misc.central_diff_weights` in SciPy 1.10.0 and
it will be completely removed in SciPy 1.12.0.
You may consider using
findiff: https://github.com/maroba/findiff or
numdifftools: https://github.com/pbrod/numdifftools
Parameters
----------
Np : int
Number of points for the central derivative.
ndiv : int, optional
Number of divisions. Default is 1.
Returns
-------
w : ndarray
Weights for an Np-point central derivative. Its size is `Np`.
Notes
-----
Can be inaccurate for a large number of points.
Examples
--------
We can calculate a derivative value of a function.
>>> from scipy.misc import central_diff_weights
>>> def f(x):
... return 2 * x**2 + 3
>>> x = 3.0 # derivative point
>>> h = 0.1 # differential step
>>> Np = 3 # point number for central derivative
>>> weights = central_diff_weights(Np) # weights for first derivative
>>> vals = [f(x + (i - Np/2) * h) for i in range(Np)]
>>> sum(w * v for (w, v) in zip(weights, vals))/h
11.79999999999998
This value is close to the analytical solution:
f'(x) = 4x, so f'(3) = 12
References
----------
.. [1] https://en.wikipedia.org/wiki/Finite_difference
"""
return _central_diff_weights(Np, ndiv)
@_deprecated(msg="scipy.misc.derivative is deprecated in "
"SciPy v1.10.0; and will be completely removed in "
"SciPy v1.12.0. You may consider using "
"findiff: https://github.com/maroba/findiff or "
"numdifftools: https://github.com/pbrod/numdifftools")
def derivative(func, x0, dx=1.0, n=1, args=(), order=3):
"""
Find the nth derivative of a function at a point.
Given a function, use a central difference formula with spacing `dx` to
compute the nth derivative at `x0`.
.. deprecated:: 1.10.0
`derivative` has been deprecated from `scipy.misc.derivative`
in SciPy 1.10.0 and it will be completely removed in SciPy 1.12.0.
You may consider using
findiff: https://github.com/maroba/findiff or
numdifftools: https://github.com/pbrod/numdifftools
Parameters
----------
func : function
Input function.
x0 : float
The point at which the nth derivative is found.
dx : float, optional
Spacing.
n : int, optional
Order of the derivative. Default is 1.
args : tuple, optional
Arguments
order : int, optional
Number of points to use, must be odd.
Notes
-----
Decreasing the step size too small can result in round-off error.
Examples
--------
>>> from scipy.misc import derivative
>>> def f(x):
... return x**3 + x**2
>>> derivative(f, 1.0, dx=1e-6)
4.9999999999217337
"""
return _derivative(func, x0, dx, n, args, order)
@_deprecated(msg="scipy.misc.ascent has been deprecated in SciPy v1.10.0;"
" and will be completely removed in SciPy v1.12.0. "
"Dataset methods have moved into the scipy.datasets "
"module. Use scipy.datasets.ascent instead.")
def ascent():
"""
Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy use in demos
The image is derived from accent-to-the-top.jpg at
http://www.public-domain-image.com/people-public-domain-images-pictures/
.. deprecated:: 1.10.0
`ascent` has been deprecated from `scipy.misc.ascent`
in SciPy 1.10.0 and it will be completely removed in SciPy 1.12.0.
Dataset methods have moved into the `scipy.datasets` module.
Use `scipy.datasets.ascent` instead.
Parameters
----------
None
Returns
-------
ascent : ndarray
convenient image to use for testing and demonstration
Examples
--------
>>> import scipy.misc
>>> ascent = scipy.misc.ascent()
>>> ascent.shape
(512, 512)
>>> ascent.max()
255
>>> import matplotlib.pyplot as plt
>>> plt.gray()
>>> plt.imshow(ascent)
>>> plt.show()
"""
import pickle
import os
fname = os.path.join(os.path.dirname(__file__),'ascent.dat')
with open(fname, 'rb') as f:
ascent = array(pickle.load(f))
return ascent
@_deprecated(msg="scipy.misc.face has been deprecated in SciPy v1.10.0; "
"and will be completely removed in SciPy v1.12.0. "
"Dataset methods have moved into the scipy.datasets "
"module. Use scipy.datasets.face instead.")
def face(gray=False):
"""
Get a 1024 x 768, color image of a raccoon face.
raccoon-procyon-lotor.jpg at http://www.public-domain-image.com
.. deprecated:: 1.10.0
`face` has been deprecated from `scipy.misc.face`
in SciPy 1.10.0 and it will be completely removed in SciPy 1.12.0.
Dataset methods have moved into the `scipy.datasets` module.
Use `scipy.datasets.face` instead.
Parameters
----------
gray : bool, optional
If True return 8-bit grey-scale image, otherwise return a color image
Returns
-------
face : ndarray
image of a raccoon face
Examples
--------
>>> import scipy.misc
>>> face = scipy.misc.face()
>>> face.shape
(768, 1024, 3)
>>> face.max()
255
>>> face.dtype
dtype('uint8')
>>> import matplotlib.pyplot as plt
>>> plt.gray()
>>> plt.imshow(face)
>>> plt.show()
"""
import bz2
import os
with open(os.path.join(os.path.dirname(__file__), 'face.dat'), 'rb') as f:
rawdata = f.read()
data = bz2.decompress(rawdata)
face = frombuffer(data, dtype='uint8')
face.shape = (768, 1024, 3)
if gray is True:
face = (0.21 * face[:,:,0]
+ 0.71 * face[:,:,1]
+ 0.07 * face[:,:,2]).astype('uint8')
return face
@_deprecated(msg="scipy.misc.electrocardiogram has been "
"deprecated in SciPy v1.10.0; and will "
"be completely removed in SciPy v1.12.0. "
"Dataset methods have moved into the scipy.datasets "
"module. Use scipy.datasets.electrocardiogram instead.")
def electrocardiogram():
"""
Load an electrocardiogram as an example for a 1-D signal.
The returned signal is a 5 minute long electrocardiogram (ECG), a medical
recording of the heart's electrical activity, sampled at 360 Hz.
.. deprecated:: 1.10.0
`electrocardiogram` has been deprecated from
`scipy.misc.electrocardiogram` in SciPy 1.10.0 and it will be
completely removed in SciPy 1.12.0.
Dataset methods have moved into the `scipy.datasets` module.
Use `scipy.datasets.electrocardiogram` instead.
Returns
-------
ecg : ndarray
The electrocardiogram in millivolt (mV) sampled at 360 Hz.
Notes
-----
The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
(lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
heartbeats as well as pathological changes.
.. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
.. versionadded:: 1.1.0
References
----------
.. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
(PMID: 11446209); :doi:`10.13026/C2F305`
.. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
PhysioToolkit, and PhysioNet: Components of a New Research Resource
for Complex Physiologic Signals. Circulation 101(23):e215-e220;
:doi:`10.1161/01.CIR.101.23.e215`
Examples
--------
>>> from scipy.misc import electrocardiogram
>>> ecg = electrocardiogram()
>>> ecg
array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385])
>>> ecg.shape, ecg.mean(), ecg.std()
((108000,), -0.16510875, 0.5992473991177294)
As stated the signal features several areas with a different morphology.
E.g., the first few seconds show the electrical activity of a heart in
normal sinus rhythm as seen below.
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> fs = 360
>>> time = np.arange(ecg.size) / fs
>>> plt.plot(time, ecg)
>>> plt.xlabel("time in s")
>>> plt.ylabel("ECG in mV")
>>> plt.xlim(9, 10.2)
>>> plt.ylim(-1, 1.5)
>>> plt.show()
After second 16, however, the first premature ventricular contractions, also
called extrasystoles, appear. These have a different morphology compared to
typical heartbeats. The difference can easily be observed in the following
plot.
>>> plt.plot(time, ecg)
>>> plt.xlabel("time in s")
>>> plt.ylabel("ECG in mV")
>>> plt.xlim(46.5, 50)
>>> plt.ylim(-2, 1.5)
>>> plt.show()
At several points large artifacts disturb the recording, e.g.:
>>> plt.plot(time, ecg)
>>> plt.xlabel("time in s")
>>> plt.ylabel("ECG in mV")
>>> plt.xlim(207, 215)
>>> plt.ylim(-2, 3.5)
>>> plt.show()
Finally, examining the power spectrum reveals that most of the biosignal is
made up of lower frequencies. At 60 Hz the noise induced by the mains
electricity can be clearly observed.
>>> from scipy.signal import welch
>>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
>>> plt.semilogy(f, Pxx)
>>> plt.xlabel("Frequency in Hz")
>>> plt.ylabel("Power spectrum of the ECG in mV**2")
>>> plt.xlim(f[[0, -1]])
>>> plt.show()
"""
import os
file_path = os.path.join(os.path.dirname(__file__), "ecg.dat")
with load(file_path) as file:
ecg = file["ecg"].astype(int) # np.uint16 -> int
# Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
ecg = (ecg - 1024) / 200.0
return ecg

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,20 @@
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.datasets` namespace for importing the dataset functions
# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822
'central_diff_weights', 'derivative', 'ascent', 'face',
'electrocardiogram'
]
def __dir__():
return __all__
def __getattr__(name):
return _sub_module_deprecation(sub_package="misc", module="common",
private_modules=["_common"], all=__all__,
attribute=name)

View File

@ -0,0 +1,45 @@
# This file is not meant for public use and will be removed in SciPy v2.0.0.
from importlib import import_module
import warnings
__all__ = [ # noqa: F822
'docformat', 'inherit_docstring_from', 'indentcount_lines',
'filldoc', 'unindent_dict', 'unindent_string', 'extend_notes_in_docstring',
'replace_notes_in_docstring'
]
def __dir__():
return __all__
def __getattr__(name):
if name not in __all__:
raise AttributeError(
f"`scipy.misc.doccer` has no attribute `{name}`; furthermore, "
f"`scipy.misc.doccer` is deprecated and will be removed in SciPy 2.0.0."
)
attr = getattr(import_module("scipy._lib.doccer"), name, None)
if attr is not None:
message = (
f"Please import `{name}` from the `scipy._lib.doccer` namespace; "
f"the `scipy.misc.doccer` namespace is deprecated and "
f"will be removed in SciPy 2.0.0."
)
else:
message = (
f"`scipy.misc.doccer.{name}` is deprecated along with "
f"the `scipy.misc.doccer` namespace. "
f"`scipy.misc.doccer.{name}` will be removed in SciPy 1.13.0, and "
f"the `scipy.misc.doccer` namespace will be removed in SciPy 2.0.0."
)
warnings.warn(message, category=DeprecationWarning, stacklevel=2)
try:
return getattr(import_module("scipy._lib.doccer"), name)
except AttributeError as e:
raise e

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,26 @@
from numpy.testing import assert_equal, assert_almost_equal, suppress_warnings
from scipy.misc import face, ascent, electrocardiogram
def test_face():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
assert_equal(face().shape, (768, 1024, 3))
def test_ascent():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
assert_equal(ascent().shape, (512, 512))
def test_electrocardiogram():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
# Test shape, dtype and stats of signal
ecg = electrocardiogram()
assert ecg.dtype == float
assert_equal(ecg.shape, (108000,))
assert_almost_equal(ecg.mean(), -0.16510875)
assert_almost_equal(ecg.std(), 0.5992473991177294)

View File

@ -0,0 +1,44 @@
"""
Check the SciPy config is valid.
"""
import scipy
import pytest
from unittest.mock import patch
pytestmark = pytest.mark.skipif(
not hasattr(scipy.__config__, "_built_with_meson"),
reason="Requires Meson builds",
)
class TestSciPyConfigs:
REQUIRED_CONFIG_KEYS = [
"Compilers",
"Machine Information",
"Python Information",
]
@patch("scipy.__config__._check_pyyaml")
def test_pyyaml_not_found(self, mock_yaml_importer):
mock_yaml_importer.side_effect = ModuleNotFoundError()
with pytest.warns(UserWarning):
scipy.show_config()
def test_dict_mode(self):
config = scipy.show_config(mode="dicts")
assert isinstance(config, dict)
assert all([key in config for key in self.REQUIRED_CONFIG_KEYS]), (
"Required key missing,"
" see index of `False` with `REQUIRED_CONFIG_KEYS`"
)
def test_invalid_mode(self):
with pytest.raises(AttributeError):
scipy.show_config(mode="foo")
def test_warn_to_add_tests(self):
assert len(scipy.__config__.DisplayModes) == 2, (
"New mode detected,"
" please add UT if applicable and increment this count"
)

View File

@ -0,0 +1,143 @@
''' Some tests for the documenting decorator and support functions '''
import sys
import pytest
from numpy.testing import assert_equal, suppress_warnings
from scipy._lib import doccer
# python -OO strips docstrings
DOCSTRINGS_STRIPPED = sys.flags.optimize > 1
docstring = \
"""Docstring
%(strtest1)s
%(strtest2)s
%(strtest3)s
"""
param_doc1 = \
"""Another test
with some indent"""
param_doc2 = \
"""Another test, one line"""
param_doc3 = \
""" Another test
with some indent"""
doc_dict = {'strtest1':param_doc1,
'strtest2':param_doc2,
'strtest3':param_doc3}
filled_docstring = \
"""Docstring
Another test
with some indent
Another test, one line
Another test
with some indent
"""
def test_unindent():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
assert_equal(doccer.unindent_string(param_doc1), param_doc1)
assert_equal(doccer.unindent_string(param_doc2), param_doc2)
assert_equal(doccer.unindent_string(param_doc3), param_doc1)
def test_unindent_dict():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
d2 = doccer.unindent_dict(doc_dict)
assert_equal(d2['strtest1'], doc_dict['strtest1'])
assert_equal(d2['strtest2'], doc_dict['strtest2'])
assert_equal(d2['strtest3'], doc_dict['strtest1'])
def test_docformat():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
udd = doccer.unindent_dict(doc_dict)
formatted = doccer.docformat(docstring, udd)
assert_equal(formatted, filled_docstring)
single_doc = 'Single line doc %(strtest1)s'
formatted = doccer.docformat(single_doc, doc_dict)
# Note - initial indent of format string does not
# affect subsequent indent of inserted parameter
assert_equal(formatted, """Single line doc Another test
with some indent""")
@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
def test_decorator():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
# with unindentation of parameters
decorator = doccer.filldoc(doc_dict, True)
@decorator
def func():
""" Docstring
%(strtest3)s
"""
def expected():
""" Docstring
Another test
with some indent
"""
assert_equal(func.__doc__, expected.__doc__)
# without unindentation of parameters
# The docstring should be unindented for Python 3.13+
# because of https://github.com/python/cpython/issues/81283
decorator = doccer.filldoc(doc_dict, False if \
sys.version_info < (3, 13) else True)
@decorator
def func():
""" Docstring
%(strtest3)s
"""
def expected():
""" Docstring
Another test
with some indent
"""
assert_equal(func.__doc__, expected.__doc__)
@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
def test_inherit_docstring_from():
with suppress_warnings() as sup:
sup.filter(category=DeprecationWarning)
class Foo:
def func(self):
'''Do something useful.'''
return
def func2(self):
'''Something else.'''
class Bar(Foo):
@doccer.inherit_docstring_from(Foo)
def func(self):
'''%(super)sABC'''
return
@doccer.inherit_docstring_from(Foo)
def func2(self):
# No docstring.
return
assert_equal(Bar.func.__doc__, Foo.func.__doc__ + 'ABC')
assert_equal(Bar.func2.__doc__, Foo.func2.__doc__)
bar = Bar()
assert_equal(bar.func.__doc__, Foo.func.__doc__ + 'ABC')
assert_equal(bar.func2.__doc__, Foo.func2.__doc__)