Undocumented
Variable | array_function_dispatch |
Undocumented |
Class | vectorize |
vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None) |
Function | _angle_dispatcher |
Undocumented |
Function | _append_dispatcher |
Undocumented |
Function | _average_dispatcher |
Undocumented |
Function | _calculate_shapes |
Helper for calculating broadcast shapes with core dimensions. |
Function | _chbevl |
Undocumented |
Function | _check_interpolation_as_method |
Undocumented |
Function | _closest_observation |
Undocumented |
Function | _compute_virtual_index |
No summary |
Function | _copy_dispatcher |
Undocumented |
Function | _corrcoef_dispatcher |
Undocumented |
Function | _cov_dispatcher |
Undocumented |
Function | _create_arrays |
Helper for creating output arrays in vectorize. |
Function | _delete_dispatcher |
Undocumented |
Function | _diff_dispatcher |
Undocumented |
Function | _digitize_dispatcher |
Undocumented |
Function | _discret_interpolation_to_boundaries |
Undocumented |
Function | _extract_dispatcher |
Undocumented |
Function | _flip_dispatcher |
Undocumented |
Function | _get_gamma |
Compute gamma (a.k.a 'm' or 'weight') for the linear interpolation of quantiles. |
Function | _get_gamma_mask |
Undocumented |
Function | _get_indexes |
No summary |
Function | _gradient_dispatcher |
Undocumented |
Function | _i0_1 |
Undocumented |
Function | _i0_2 |
Undocumented |
Function | _i0_dispatcher |
Undocumented |
Function | _insert_dispatcher |
Undocumented |
Function | _interp_dispatcher |
Undocumented |
Function | _inverted_cdf |
Undocumented |
Function | _lerp |
Compute the linear interpolation weighted by gamma on each point of two same shape array. |
Function | _median |
Undocumented |
Function | _median_dispatcher |
Undocumented |
Function | _meshgrid_dispatcher |
Undocumented |
Function | _msort_dispatcher |
Undocumented |
Function | _parse_gufunc_signature |
Parse string signatures for a generalized universal function. |
Function | _parse_input_dimensions |
Parse broadcast and core dimensions for vectorize with a signature. |
Function | _percentile_dispatcher |
Undocumented |
Function | _piecewise_dispatcher |
Undocumented |
Function | _place_dispatcher |
Undocumented |
Function | _quantile |
No summary |
Function | _quantile_dispatcher |
Undocumented |
Function | _quantile_is_valid |
Undocumented |
Function | _quantile_unchecked |
Assumes that q is in [0, 1], and is an ndarray |
Function | _quantile_ureduce_func |
Undocumented |
Function | _rot90_dispatcher |
Undocumented |
Function | _select_dispatcher |
Undocumented |
Function | _sinc_dispatcher |
Undocumented |
Function | _sort_complex |
Undocumented |
Function | _trapz_dispatcher |
Undocumented |
Function | _trim_zeros |
Undocumented |
Function | _unwrap_dispatcher |
Undocumented |
Function | _update_dim_sizes |
Incrementally check and update core dimension sizes for a single argument. |
Function | _ureduce |
Internal Function. Call func with a as first argument swapping the axes to use extended axis on functions that don't support it natively. |
Function | add_newdoc |
Add documentation to an existing object, typically one defined in C |
Function | angle |
Return the angle of the complex argument. |
Function | append |
Append values to the end of an array. |
Function | asarray_chkfinite |
Convert the input to an array, checking for NaNs or Infs. |
Function | average |
Compute the weighted average along the specified axis. |
Function | bartlett |
Return the Bartlett window. |
Function | blackman |
Return the Blackman window. |
Function | copy |
Return an array copy of the given object. |
Function | corrcoef |
Return Pearson product-moment correlation coefficients. |
Function | cov |
Estimate a covariance matrix, given data and weights. |
Function | delete |
Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj] . |
Function | diff |
Calculate the n-th discrete difference along the given axis. |
Function | digitize |
Return the indices of the bins to which each value in input array belongs. |
Function | disp |
Display a message on a device. |
Function | extract |
Return the elements of an array that satisfy some condition. |
Function | flip |
Reverse the order of elements in an array along the given axis. |
Function | gradient |
Return the gradient of an N-dimensional array. |
Function | hamming |
Return the Hamming window. |
Function | hanning |
Return the Hanning window. |
Function | i0 |
Modified Bessel function of the first kind, order 0. |
Function | insert |
Insert values along the given axis before the given indices. |
Function | interp |
One-dimensional linear interpolation for monotonically increasing sample points. |
Function | iterable |
Check whether or not an object can be iterated over. |
Function | kaiser |
Return the Kaiser window. |
Function | median |
Compute the median along the specified axis. |
Function | meshgrid |
Return coordinate matrices from coordinate vectors. |
Function | msort |
Return a copy of an array sorted along the first axis. |
Function | percentile |
Compute the q-th percentile of the data along the specified axis. |
Function | piecewise |
Evaluate a piecewise-defined function. |
Function | place |
Change elements of an array based on conditional and input values. |
Function | quantile |
Compute the q-th quantile of the data along the specified axis. |
Function | rot90 |
Rotate an array by 90 degrees in the plane specified by axes. |
Function | select |
Return an array drawn from elements in choicelist, depending on conditions. |
Function | sinc |
Return the normalized sinc function. |
Function | sort_complex |
Sort a complex array using the real part first, then the imaginary part. |
Function | trapz |
Integrate along the given axis using the composite trapezoidal rule. |
Function | trim_zeros |
Trim the leading and/or trailing zeros from a 1-D array or sequence. |
Function | unwrap |
Unwrap by taking the complement of large deltas with respect to the period. |
Constant | _ARGUMENT |
Undocumented |
Constant | _ARGUMENT_LIST |
Undocumented |
Constant | _CORE_DIMENSION_LIST |
Undocumented |
Constant | _DIMENSION_NAME |
Undocumented |
Constant | _SIGNATURE |
Undocumented |
Variable | _i0A |
Undocumented |
Variable | _i0B |
Undocumented |
Variable | _QuantileMethods |
Undocumented |
Compute the floating point indexes of an array for the linear interpolation of quantiles. n : array_like
The sample sizes.
alpha and beta values depend on the chosen method (see quantile documentation)
Reference: Hyndman&Fan paper "Sample Quantiles in Statistical Packages", DOI: 10.1080/00031305.1996.10473566
Parameters | |
n | Undocumented |
quantiles | Undocumented |
alpha:float | Undocumented |
beta:float | Undocumented |
Undocumented
Compute gamma (a.k.a 'm' or 'weight') for the linear interpolation of quantiles.
gamma is usually the fractional part of virtual_indexes but can be modified by the interpolation method.
Get the valid indexes of arr neighbouring virtual_indexes. Note This is a companion function to linear interpolation of Quantiles
Compute the linear interpolation weighted by gamma on each point of two same shape array.
Parse string signatures for a generalized universal function.
Tuple of input and output core dimensions parsed from the signature, each of the form List[Tuple[str, ...]].
Parse broadcast and core dimensions for vectorize with a signature.
Undocumented
Private function that doesn't support extended axis or keepdims.
These methods are extended to this function using _ureduce
See nanpercentile for parameter usage
It computes the quantiles of the array for the given axis.
A linear interpolation is performed based on the interpolation
.
By default, the method is "linear" where alpha == beta == 1 which performs the 7th method of Hyndman&Fan. With "median_unbiased" we get alpha == beta == 1/3 thus the 8th method of Hyndman&Fan.
Parameters | |
arr:np.array | Undocumented |
quantiles:np.array | Undocumented |
axis:int | Undocumented |
method | Undocumented |
out | Undocumented |
Undocumented
Undocumented
Parameters | |
a:np.array | Undocumented |
q:np.array | Undocumented |
axis:int | Undocumented |
out | Undocumented |
overwrite_input:bool | Undocumented |
method | Undocumented |
Returns | |
np.array | Undocumented |
Incrementally check and update core dimension sizes for a single argument.
Internal Function.
Call func
with a
as first argument swapping the axes to use extended
axis on functions that don't support it natively.
Returns result and a.shape with axis dims set to 1.
a
as first argument followed by kwargs
.func
.Add documentation to an existing object, typically one defined in C
The purpose is to allow easier editing of the docstrings without requiring a re-compile. This exists primarily for internal use within numpy itself.
If a string, the documentation to apply to obj
If a tuple, then the first element is interpreted as an attribute of
obj
and the second as the docstring to apply - (method, docstring)
If a list, then each element of the list should be a tuple of length two - [(method1, docstring1), (method2, docstring2), ...]
UserWarning
if this is used to attach
documentation to a pure-python object.This routine never raises an error if the docstring can't be written, but will raise an error if the object being documented does not exist.
This routine cannot modify read-only docstrings, as appear in new-style classes or built-in functions. Because this routine never raises an error the caller must check manually that the docstrings were changed.
Since this function grabs the char * from a c-level str object and puts
it into the tp_doc slot of the type of obj
, it violates a number of
C-API best-practices, by:
PyTypeObject
after calling PyType_Ready
Py_INCREF
on the str and losing the reference, so the str
will never be releasedIf possible it should be avoided.
Return the angle of the complex argument.
The counterclockwise angle from the positive real axis on the complex plane in the range (-pi, pi], with dtype as numpy.float64.
ma.array
.arctan2 absolute
Although the angle of the complex number 0 is undefined, numpy.angle(0) returns the value 0.
>>> np.angle([1.0, 1.0j, 1+1j]) # in radians array([ 0. , 1.57079633, 0.78539816]) # may vary >>> np.angle(1+1j, deg=True) # in degrees 45.0
Append values to the end of an array.
arr
. It must be of the
correct shape (the same shape as arr
, excluding axis
). If
axis
is not specified, values
can be any shape and will be
flattened before use.values
are appended. If axis
is not
given, both arr
and values
are flattened before use.arr
with values
appended to axis
. Note that
append
does not occur in-place: a new array is allocated and
filled. If axis
is None, out
is a flattened array.insert : Insert elements into an array. delete : Delete elements from an array.
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, ..., 7, 8, 9])
When axis
is specified, values
must have the correct shape.
>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): ... ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)
Convert the input to an array, checking for NaNs or Infs.
a
is Fortran contiguous, 'C' otherwise
'K' (keep) preserve input order
Defaults to 'C'.a
. No copy is performed if the input
is already an ndarray. If a
is a subclass of ndarray, a base
class ndarray is returned.a
contains NaN (Not a Number) or Inf (Infinity).asarray : Create and array. asanyarray : Similar function which passes through subclasses. ascontiguousarray : Convert input to a contiguous array. asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major
memory order.
fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid
positions.
Convert a list into an array. If all elements are finite asarray_chkfinite is identical to asarray.
>>> a = [1, 2] >>> np.asarray_chkfinite(a, dtype=float) array([1., 2.])
Raises ValueError if array_like contains Nans or Infs.
>>> a = [1, 2, np.inf] >>> try: ... np.asarray_chkfinite(a) ... except ValueError: ... print('ValueError') ... ValueError
Compute the weighted average along the specified axis.
a
is not an array, a
conversion is attempted.Axis or axes along which to average a
. The default,
axis=None, will average over all of the elements of the input array.
If axis is negative it counts from the last to the first axis.
If axis is a tuple of ints, averaging is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
An array of weights associated with the values in a
. Each value in
a
contributes to the average according to its associated weight.
The weights array can either be 1-D (in which case its length must be
the size of a
along the given axis) or of the same shape as a
.
If weights=None
, then all data in a
are assumed to have a
weight equal to one. The 1-D calculation is:
avg = sum(a * weights) / sum(weights)
The only constraint on weights
is that sum(weights)
must not be 0.
False
. If True
, the tuple (average
, sum_of_weights
)
is returned, otherwise only the average is returned.
If weights=None
, sum_of_weights
is equivalent to the number of
elements over which the average is taken.returned
is True
,
return a tuple with the average as the first element and the sum
of the weights as the second element. sum_of_weights
is of the
same type as retval
. The result dtype follows a genereal pattern.
If weights
is None, the result dtype will be that of a
, or float64
if a
is integral. Otherwise, if weights
is not None and a
is non-
integral, the result type will be the type of lowest precision capable of
representing values of both a
and weights
. If a
happens to be
integral, the previous rules still applies but the result dtype will
at least be float64.numpy.ma.average
for a
version robust to this type of error.weights
is not the same as the shape of a
along axis.mean
>>> data = np.arange(1, 5) >>> data array([1, 2, 3, 4]) >>> np.average(data) 2.5 >>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1)) 4.0
>>> data = np.arange(6).reshape((3,2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): ... TypeError: Axis must be specified when shapes of a and weights differ.
>>> a = np.ones(5, dtype=np.float128) >>> w = np.ones(5, dtype=np.complex64) >>> avg = np.average(a, weights=w) >>> print(avg.dtype) complex256
Return the Bartlett window.
The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain.
blackman, hamming, hanning, kaiser
The Bartlett window is defined as
Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means"removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich.
[1] | M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", Biometrika 37, 1-16, 1950. |
[2] | E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. |
[3] | A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal Processing", Prentice-Hall, 1999, pp. 468-471. |
[4] | Wikipedia, "Window function", https://en.wikipedia.org/wiki/Window_function |
[5] | W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 429. |
>>> import matplotlib.pyplot as plt >>> np.bartlett(12) array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, # may vary 0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636, 0.18181818, 0. ])
Plot the window and its frequency response (requires SciPy and matplotlib):
>>> from numpy.fft import fft, fftshift >>> window = np.bartlett(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Bartlett window") Text(0.5, 1.0, 'Bartlett window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show()
>>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ... >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Bartlett window") Text(0.5, 1.0, 'Frequency response of Bartlett window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> _ = plt.axis('tight') >>> plt.show()
Return the Blackman window.
The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.
bartlett, hamming, hanning, kaiser
The Blackman window is defined as
Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a "near optimal" tapering function, almost as good (by some measures) as the kaiser window.
Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York.
Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
>>> import matplotlib.pyplot as plt >>> np.blackman(12) array([-1.38777878e-17, 3.26064346e-02, 1.59903635e-01, # may vary 4.14397981e-01, 7.36045180e-01, 9.67046769e-01, 9.67046769e-01, 7.36045180e-01, 4.14397981e-01, 1.59903635e-01, 3.26064346e-02, -1.38777878e-17])
Plot the window and the frequency response:
>>> from numpy.fft import fft, fftshift >>> window = np.blackman(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Blackman window") Text(0.5, 1.0, 'Blackman window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show()
>>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ... >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Blackman window") Text(0.5, 1.0, 'Frequency response of Blackman window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> _ = plt.axis('tight') >>> plt.show()
Return an array copy of the given object.
a
is Fortran contiguous,
'C' otherwise. 'K' means match the layout of a
as closely
as possible. (Note that this function and ndarray.copy
are very
similar, but have different default values for their order=
arguments.)If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (defaults to False).
a
.ndarray.copy : Preferred method for creating an array copy
This is equivalent to:
>>> np.array(a, copy=True) #doctest: +SKIP
Create an array x, with a reference y and a copy z:
>>> x = np.array([1, 2, 3]) >>> y = x >>> z = np.copy(x)
Note that, when we modify x, y changes, but not z:
>>> x[0] = 10 >>> x[0] == y[0] True >>> x[0] == z[0] False
Note that, np.copy clears previously set WRITEABLE=False flag.
>>> a = np.array([1, 2, 3]) >>> a.flags["WRITEABLE"] = False >>> b = np.copy(a) >>> b.flags["WRITEABLE"] True >>> b[0] = 3 >>> b array([3, 2, 3])
Note that np.copy is a shallow copy and will not copy object elements within arrays. This is mainly important for arrays containing Python objects. The new array will contain the same object which may lead to surprises if that object can be modified (is mutable):
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object) >>> b = np.copy(a) >>> b[2][0] = 10 >>> a array([1, 'm', list([10, 3, 4])], dtype=object)
To ensure all elements within an object array are copied,
use copy.deepcopy
:
>>> import copy >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object) >>> c = copy.deepcopy(a) >>> c[2][0] = 10 >>> c array([1, 'm', list([10, 3, 4])], dtype=object) >>> a array([1, 'm', list([2, 3, 4])], dtype=object)
Return Pearson product-moment correlation coefficients.
Please refer to the documentation for cov
for more detail. The
relationship between the correlation coefficient matrix, R
, and the
covariance matrix, C
, is
The values of R
are between -1 and 1, inclusive.
x
represents a variable, and each column a single
observation of all those variables. Also see rowvar
below.y
has the same
shape as x
.rowvar
is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.Has no effect, do not use.
Has no effect, do not use.
Data-type of the result. By default, the return data-type will have
at least numpy.float64
precision.
cov : Covariance matrix
Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case.
This function accepts but discards arguments bias
and ddof
. This is
for backwards compatibility with previous versions of this function. These
arguments had no effect on the return values of the function and can be
safely ignored in this and previous versions of numpy.
In this example we generate two random arrays, xarr and yarr, and compute the row-wise and column-wise Pearson correlation coefficients, R. Since rowvar is true by default, we first find the row-wise Pearson correlation coefficients between the variables of xarr.
>>> import numpy as np >>> rng = np.random.default_rng(seed=42) >>> xarr = rng.random((3, 3)) >>> xarr array([[0.77395605, 0.43887844, 0.85859792], [0.69736803, 0.09417735, 0.97562235], [0.7611397 , 0.78606431, 0.12811363]]) >>> R1 = np.corrcoef(xarr) >>> R1 array([[ 1. , 0.99256089, -0.68080986], [ 0.99256089, 1. , -0.76492172], [-0.68080986, -0.76492172, 1. ]])
If we add another set of variables and observations yarr, we can compute the row-wise Pearson correlation coefficients between the variables in xarr and yarr.
>>> yarr = rng.random((3, 3)) >>> yarr array([[0.45038594, 0.37079802, 0.92676499], [0.64386512, 0.82276161, 0.4434142 ], [0.22723872, 0.55458479, 0.06381726]]) >>> R2 = np.corrcoef(xarr, yarr) >>> R2 array([[ 1. , 0.99256089, -0.68080986, 0.75008178, -0.934284 , -0.99004057], [ 0.99256089, 1. , -0.76492172, 0.82502011, -0.97074098, -0.99981569], [-0.68080986, -0.76492172, 1. , -0.99507202, 0.89721355, 0.77714685], [ 0.75008178, 0.82502011, -0.99507202, 1. , -0.93657855, -0.83571711], [-0.934284 , -0.97074098, 0.89721355, -0.93657855, 1. , 0.97517215], [-0.99004057, -0.99981569, 0.77714685, -0.83571711, 0.97517215, 1. ]])
Finally if we use the option rowvar=False, the columns are now being treated as the variables and we will find the column-wise Pearson correlation coefficients between variables in xarr and yarr.
>>> R3 = np.corrcoef(xarr, yarr, rowvar=False) >>> R3 array([[ 1. , 0.77598074, -0.47458546, -0.75078643, -0.9665554 , 0.22423734], [ 0.77598074, 1. , -0.92346708, -0.99923895, -0.58826587, -0.44069024], [-0.47458546, -0.92346708, 1. , 0.93773029, 0.23297648, 0.75137473], [-0.75078643, -0.99923895, 0.93773029, 1. , 0.55627469, 0.47536961], [-0.9665554 , -0.58826587, 0.23297648, 0.55627469, 1. , -0.46666491], [ 0.22423734, -0.44069024, 0.75137473, 0.47536961, -0.46666491, 1. ]])
Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, X = [x1, x2, ...xN]T, then the covariance matrix element Cij is the covariance of xi and xj. The element Cii is the variance of xi.
See the notes for an outline of the algorithm.
m
represents a variable, and each column a single
observation of all those variables. Also see rowvar
below.y
has the same form
as that of m
.rowvar
is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.bias
is True,
then normalization is by N. These values can be overridden by using
the keyword ddof in numpy versions >= 1.5.If not None the default value implied by bias
is overridden.
Note that ddof=1 will return the unbiased estimate, even if both
fweights
and aweights
are specified, and ddof=0 will return
the simple average. See the notes for the details. The default value
is None.
1-D array of integer frequency weights; the number of times each observation vector should be repeated.
1-D array of observation vector weights. These relative weights are typically large for observations considered "important" and smaller for observations considered less "important". If ddof=0 the array of weights can be used to assign probabilities to observation vectors.
Data-type of the result. By default, the return data-type will have
at least numpy.float64
precision.
corrcoef : Normalized covariance matrix
Assume that the observations are in the columns of the observation
array m
and let f = fweights and a = aweights for brevity. The
steps to compute the weighted covariance are as follows:
>>> m = np.arange(10, dtype=np.float64) >>> f = np.arange(10) * 2 >>> a = np.arange(10) ** 2. >>> ddof = 1 >>> w = f * a >>> v1 = np.sum(w) >>> v2 = np.sum(w * a) >>> m -= np.sum(m * w, axis=None, keepdims=True) / v1 >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
Note that when a == 1, the normalization factor v1 / (v1**2 - ddof * v2) goes over to 1 / (np.sum(f) - ddof) as it should.
Consider two variables, x0 and x1, which correlate perfectly, but in opposite directions:
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T >>> x array([[0, 1, 2], [2, 1, 0]])
Note how x0 increases while x1 decreases. The covariance matrix shows this clearly:
>>> np.cov(x) array([[ 1., -1.], [-1., 1.]])
Note that element C0, 1, which shows the correlation between x0 and x1, is negative.
Further, note how x
and y
are combined:
>>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.stack((x, y), axis=0) >>> np.cov(X) array([[11.71 , -4.286 ], # may vary [-4.286 , 2.144133]]) >>> np.cov(x, y) array([[11.71 , -4.286 ], # may vary [-4.286 , 2.144133]]) >>> np.cov(x) array(11.71)
Return a new array with sub-arrays along an axis deleted. For a one
dimensional array, this returns those entries not returned by
arr[obj]
.
Indicate indices of sub-arrays to remove along the specified axis.
obj
.
If axis
is None, obj
is applied to the flattened array.arr
with the elements specified by obj
removed. Note
that delete
does not occur in-place. If axis
is None, out
is
a flattened array.insert : Insert elements into an array. append : Append elements at the end of an array.
Often it is preferable to use a boolean mask. For example:
>>> arr = np.arange(12) + 1 >>> mask = np.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...]
Is equivalent to np.delete(arr, [0,2,4], axis=0)
, but allows further
use of mask
.
>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) >>> np.delete(arr, 1, 0) array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]])
>>> np.delete(arr, np.s_[::2], 1) array([[ 2, 4], [ 6, 8], [10, 12]]) >>> np.delete(arr, [1,3,5], None) array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])
Calculate the n-th discrete difference along the given axis.
The first difference is given by out[i] = a[i+1] - a[i] along
the given axis, higher differences are calculated by using diff
recursively.
Values to prepend or append to a
along axis prior to
performing the difference. Scalar values are expanded to
arrays with length 1 in the direction of axis and the shape
of the input array in along all other axes. Otherwise the
dimension and shape must match a
except along axis.
a
except along axis
where the dimension is smaller by n
. The
type of the output is the same as the type of the difference
between any two elements of a
. This is the same as the type of
a
in most cases. A notable exception is datetime64
, which
results in a timedelta64
output array.gradient, ediff1d, cumsum
Type is preserved for boolean arrays, so the result will contain
False
when consecutive elements are the same and True
when they
differ.
For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly:
>>> u8_arr = np.array([1, 0], dtype=np.uint8) >>> np.diff(u8_arr) array([255], dtype=uint8) >>> u8_arr[1,...] - u8_arr[0,...] 255
If this is not desirable, then the array should be cast to a larger integer type first:
>>> i16_arr = u8_arr.astype(np.int16) >>> np.diff(i16_arr) array([-1], dtype=int16)
>>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) array([ 1, 2, 3, -7]) >>> np.diff(x, n=2) array([ 1, 1, -10])
>>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]])
>>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64) >>> np.diff(x) array([1, 1], dtype='timedelta64[D]')
Return the indices of the bins to which each value in input array belongs.
right |
order of bins | returned index i satisfies |
---|---|---|
False | increasing | bins[i-1] <= x < bins[i] |
True | increasing | bins[i-1] < x <= bins[i] |
False | decreasing | bins[i-1] > x >= bins[i] |
True | decreasing | bins[i-1] >= x > bins[i] |
If values in x
are beyond the bounds of bins
, 0 or len(bins) is
returned as appropriate.
x
.bins
is not monotonic.bincount, histogram, unique, searchsorted
If values in x
are such that they fall outside the bin range,
attempting to index bins
with the indices that digitize
returns
will result in an IndexError.
np.digitize
is implemented in terms of np.searchsorted
. This means
that a binary search is used to bin the values, which scales much better
for larger number of bins than the previous linear search. It also removes
the requirement for the input array to be 1-dimensional.
For monotonically _increasing_ bins
, the following are equivalent:
np.digitize(x, bins, right=True) np.searchsorted(bins, x, side='left')
Note that as the order of the arguments are reversed, the side must be too.
The searchsorted
call is marginally faster, as it does not do any
monotonicity checks. Perhaps more importantly, it supports all dtypes.
>>> x = np.array([0.2, 6.4, 3.0, 1.6]) >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) >>> inds = np.digitize(x, bins) >>> inds array([1, 4, 3, 2]) >>> for n in range(x.size): ... print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]]) ... 0.0 <= 0.2 < 1.0 4.0 <= 6.4 < 10.0 2.5 <= 3.0 < 4.0 1.0 <= 1.6 < 2.5
>>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.]) >>> bins = np.array([0, 5, 10, 15, 20]) >>> np.digitize(x,bins,right=True) array([1, 2, 3, 4, 4]) >>> np.digitize(x,bins,right=False) array([1, 3, 3, 4, 5])
Display a message on a device.
device
needs to have write() and
flush() methods.device
does not have a write() or flush() method.Besides sys.stdout, a file-like object can also be used as it has both required methods:
>>> from io import StringIO >>> buf = StringIO() >>> np.disp(u'"Display" in a file', device=buf) >>> buf.getvalue() '"Display" in a file\n'
Return the elements of an array that satisfy some condition.
This is equivalent to np.compress(ravel(condition), ravel(arr)). If
condition
is boolean np.extract is equivalent to arr[condition].
Note that place
does the exact opposite of extract
.
arr
to extract.condition
.arr
where condition
is True.take, put, copyto, compress, place
>>> arr = np.arange(12).reshape((3, 4)) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition array([[ True, False, False, True], [False, False, True, False], [False, True, False, False]]) >>> np.extract(condition, arr) array([0, 3, 6, 9])
If condition
is boolean:
>>> arr[condition] array([0, 3, 6, 9])
Reverse the order of elements in an array along the given axis.
The shape of the array is preserved, but the elements are reordered.
Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.
If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple.
m
with the entries of axis reversed. Since a view is
returned, this operation is done in constant time.flipud : Flip an array vertically (axis=0). fliplr : Flip an array horizontally (axis=1).
flip(m, 0) is equivalent to flipud(m).
flip(m, 1) is equivalent to fliplr(m).
flip(m, n) corresponds to m[...,::-1,...] with ::-1 at position n.
flip(m) corresponds to m[::-1,::-1,...,::-1] with ::-1 at all positions.
flip(m, (0, 1)) corresponds to m[::-1,::-1,...] with ::-1 at position 0 and position 1.
>>> A = np.arange(8).reshape((2,2,2)) >>> A array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.flip(A, 0) array([[[4, 5], [6, 7]], [[0, 1], [2, 3]]]) >>> np.flip(A, 1) array([[[2, 3], [0, 1]], [[6, 7], [4, 5]]]) >>> np.flip(A) array([[[7, 6], [5, 4]], [[3, 2], [1, 0]]]) >>> np.flip(A, (0, 2)) array([[[5, 4], [7, 6]], [[1, 0], [3, 2]]]) >>> A = np.random.randn(3,4,5) >>> np.all(np.flip(A,2) == A[:,:,::-1,...]) True
Return the gradient of an N-dimensional array.
The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array.
Spacing between f values. Default unitary spacing for all dimensions. Spacing can be specified using:
dx
, dy
, dz
, ...If axis
is given, the number of varargs must equal the number of axes.
Default: 1.
Gradient is calculated using N-th order accurate differences at the boundaries. Default: 1.
Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array. axis may be negative, in which case it counts from the last to the first axis.
>>> f = np.array([1, 2, 4, 7, 11, 16], dtype=float) >>> np.gradient(f) array([1. , 1.5, 2.5, 3.5, 4.5, 5. ]) >>> np.gradient(f, 2) array([0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
Spacing can be also specified with an array that represents the coordinates of the values F along the dimensions. For instance a uniform spacing:
>>> x = np.arange(f.size) >>> np.gradient(f, x) array([1. , 1.5, 2.5, 3.5, 4.5, 5. ])
Or a non uniform one:
>>> x = np.array([0., 1., 1.5, 3.5, 4., 6.], dtype=float) >>> np.gradient(f, x) array([1. , 3. , 3.5, 6.7, 6.9, 2.5])
For two dimensional arrays, the return will be two arrays ordered by axis. In this example the first array stands for the gradient in rows and the second one in columns direction:
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float)) [array([[ 2., 2., -1.], [ 2., 2., -1.]]), array([[1. , 2.5, 4. ], [1. , 1. , 1. ]])]
In this example the spacing is also specified: uniform for axis=0 and non uniform for axis=1
>>> dx = 2. >>> y = [1., 1.5, 3.5] >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), dx, y) [array([[ 1. , 1. , -0.5], [ 1. , 1. , -0.5]]), array([[2. , 2. , 2. ], [2. , 1.7, 0.5]])]
It is possible to specify how boundaries are treated using edge_order
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
The axis
keyword can be used to specify a subset of axes of which the
gradient is calculated
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), axis=0) array([[ 2., 2., -1.], [ 2., 2., -1.]])
Assuming that f ∈ C3 (i.e., f has at least 3 continuous derivatives) and let h* be a non-homogeneous stepsize, we minimize the "consistency error" ηi between the true gradient and its estimate from a linear combination of the neighboring grid-points:
By substituting f(xi + hd) and f(xi − hs) with their Taylor series expansion, this translates into solving the following the linear system:
The resulting approximation of f(1)i is the following:
It is worth noting that if hs = hd (i.e., data are evenly spaced) we find the standard second order approximation:
With a similar procedure the forward/backward approximations used for boundaries can be derived.
[1] | Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics (Texts in Applied Mathematics). New York: Springer. |
[2] | Durran D. R. (1999) Numerical Methods for Wave Equations in Geophysical Fluid Dynamics. New York: Springer. |
[3] | Fornberg B. (1988) Generation of Finite Difference Formulas on Arbitrarily Spaced Grids, Mathematics of Computation 51, no. 184 : 699-706. PDF. |
Return the Hamming window.
The Hamming window is a taper formed by using a weighted cosine.
bartlett, blackman, hanning, kaiser
The Hamming window is defined as
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman and Tukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Most references to the Hamming window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.
[1] | Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. |
[2] | E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. |
[3] | Wikipedia, "Window function", https://en.wikipedia.org/wiki/Window_function |
[4] | W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. |
>>> np.hamming(12) array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, # may vary 0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909, 0.15302337, 0.08 ])
Plot the window and the frequency response:
>>> import matplotlib.pyplot as plt >>> from numpy.fft import fft, fftshift >>> window = np.hamming(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hamming window") Text(0.5, 1.0, 'Hamming window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show()
>>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Hamming window") Text(0.5, 1.0, 'Frequency response of Hamming window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> plt.axis('tight') ... >>> plt.show()
Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
M
is odd).bartlett, blackman, hamming, kaiser
The Hanning window is defined as
The Hanning was named for Julius von Hann, an Austrian meteorologist. It is also known as the Cosine Bell. Some authors prefer that it be called a Hann window, to help avoid confusion with the very similar Hamming window.
Most references to the Hanning window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.
[1] | Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. |
[2] | E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 106-108. |
[3] | Wikipedia, "Window function", https://en.wikipedia.org/wiki/Window_function |
[4] | W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. |
>>> np.hanning(12) array([0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037, 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249, 0.07937323, 0. ])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt >>> from numpy.fft import fft, fftshift >>> window = np.hanning(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hann window") Text(0.5, 1.0, 'Hann window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show()
>>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ... >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of the Hann window") Text(0.5, 1.0, 'Frequency response of the Hann window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> plt.axis('tight') ... >>> plt.show()
Modified Bessel function of the first kind, order 0.
Usually denoted I0.
x
.scipy.special.i0, scipy.special.iv, scipy.special.ive
The scipy implementation is recommended over this function: it is a proper ufunc written in C, and more than an order of magnitude faster.
We use the algorithm published by Clenshaw [1] and referenced by Abramowitz and Stegun [2], for which the function domain is partitioned into the two intervals [0,8] and (8,inf), and Chebyshev polynomial expansions are employed in each interval. Relative error on the domain [0,30] using IEEE arithmetic is documented [3] as having a peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).
[1] | C. W. Clenshaw, "Chebyshev series for mathematical functions", in National Physical Laboratory Mathematical Tables, vol. 5, London: Her Majesty's Stationery Office, 1962. |
[2] | M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 379. https://personal.math.ubc.ca/~cbm/aands/page_379.htm |
[3] | https://metacpan.org/pod/distribution/Math-Cephes/lib/Math/Cephes.pod#i0:-Modified-Bessel-function-of-order-zero |
>>> np.i0(0.) array(1.0) >>> np.i0([0, 1, 2, 3]) array([1. , 1.26606588, 2.2795853 , 4.88079259])
Insert values along the given axis before the given indices.
Object that defines the index or indices before which values
is
inserted.
Support for multiple insertions when obj
is a single scalar or a
sequence with one element (similar to calling insert multiple
times).
arr
. If the type of values
is different
from that of arr
, values
is converted to the type of arr
.
values
should be shaped so that arr[...,obj,...] = values
is legal.values
. If axis
is None then arr
is flattened first.arr
with values
inserted. Note that insert
does not occur in-place: a new array is returned. If
axis
is None, out
is a flattened array.append : Append elements at the end of an array. concatenate : Join a sequence of arrays along an existing axis. delete : Delete elements from an array.
Note that for higher dimensional inserts obj=0
behaves very different
from obj=[0]
just like arr[:,0,:] = values
is different from
arr[:,[0],:] = values
.
>>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, ..., 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]])
Difference between sequence and scalars:
>>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), ... np.insert(a, [1], [[1],[2],[3]], axis=1)) True
>>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, ..., 2, 3, 3])
>>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, ..., 2, 3, 3])
>>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, ..., 2, 3, 3])
>>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]])
One-dimensional linear interpolation for monotonically increasing sample points.
Returns the one-dimensional piecewise linear interpolant to a function
with given discrete data points (xp
, fp
), evaluated at x
.
period
is not specified. Otherwise, xp
is internally sorted after
normalizing the periodic boundaries with xp = xp % period.xp
.x < xp[0]
, default is fp[0]
.x > xp[-1]
, default is fp[-1]
.A period for the x-coordinates. This parameter allows the proper
interpolation of angular x-coordinates. Parameters left
and right
are ignored if period
is specified.
x
.xp
and fp
have different length
If xp
or fp
are not 1-D sequences
If period == 0
scipy.interpolate
The x-coordinate sequence is expected to be increasing, but this is not
explicitly enforced. However, if the sequence xp
is non-increasing,
interpolation results are meaningless.
Note that, since NaN is unsortable, xp
also cannot contain NaNs.
A simple check for xp
being strictly increasing is:
np.all(np.diff(xp) > 0)
>>> xp = [1, 2, 3] >>> fp = [3, 2, 0] >>> np.interp(2.5, xp, fp) 1.0 >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp) array([3. , 3. , 2.5 , 0.56, 0. ]) >>> UNDEF = -99.0 >>> np.interp(3.14, xp, fp, right=UNDEF) -99.0
Plot an interpolant to the sine function:
>>> x = np.linspace(0, 2*np.pi, 10) >>> y = np.sin(x) >>> xvals = np.linspace(0, 2*np.pi, 50) >>> yinterp = np.interp(xvals, x, y) >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(xvals, yinterp, '-x') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.show()
Interpolation with periodic x-coordinates:
>>> x = [-180, -170, -185, 185, -10, -5, 0, 365] >>> xp = [190, -190, 350, -350] >>> fp = [5, 10, 3, 4] >>> np.interp(x, xp, fp, period=360) array([7.5 , 5. , 8.75, 6.25, 3. , 3.25, 3.5 , 3.75])
Complex interpolation:
>>> x = [1.5, 4.0] >>> xp = [2,3,5] >>> fp = [1.0j, 0, 2+3j] >>> np.interp(x, xp, fp) array([0.+1.j , 1.+1.5j])
Check whether or not an object can be iterated over.
>>> np.iterable([1, 2, 3]) True >>> np.iterable(2) False
In most cases, the results of np.iterable(obj) are consistent with isinstance(obj, collections.abc.Iterable). One notable exception is the treatment of 0-dimensional arrays:
>>> from collections.abc import Iterable >>> a = np.array(1.0) # 0-dimensional numpy array >>> isinstance(a, Iterable) True >>> np.iterable(a) False
Return the Kaiser window.
The Kaiser window is a taper formed by using a Bessel function.
bartlett, blackman, hamming, hanning
The Kaiser window is defined as
with
where I0 is the modified zeroth-order Bessel function.
The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based on Bessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence, or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative to total energy.
The Kaiser can approximate many other windows by varying the beta parameter.
beta | Window shape |
---|---|
0 | Rectangular |
5 | Similar to a Hamming |
6 | Similar to a Hanning |
8.6 | Similar to a Blackman |
A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned.
Most references to the Kaiser window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.
[1] | J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966). |
[2] | E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 177-178. |
[3] | Wikipedia, "Window function", https://en.wikipedia.org/wiki/Window_function |
>>> import matplotlib.pyplot as plt >>> np.kaiser(12, 14) array([7.72686684e-06, 3.46009194e-03, 4.65200189e-02, # may vary 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, 4.65200189e-02, 3.46009194e-03, 7.72686684e-06])
Plot the window and the frequency response:
>>> from numpy.fft import fft, fftshift >>> window = np.kaiser(51, 14) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Kaiser window") Text(0.5, 1.0, 'Kaiser window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show()
>>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Kaiser window") Text(0.5, 1.0, 'Frequency response of Kaiser window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) # may vary >>> plt.show()
Compute the median along the specified axis.
Returns the median of the array elements.
a
for
calculations. The input array will be modified by the call to
median
. This will save memory when you do not need to preserve
the contents of the input array. Treat the input as undefined,
but it will probably be fully or partially sorted. Default is
False. If overwrite_input
is True and a
is not already an
ndarray
, an error will be raised.If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original arr
.
out
is specified, that array is
returned instead.mean, percentile
Given a vector V of length N, the median of V is the middle value of a sorted copy of V, V_sorted - i e., V_sorted[(N-1)/2], when N is odd, and the average of the two middle values of V_sorted when N is even.
>>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.median(a) 3.5 >>> np.median(a, axis=0) array([6.5, 4.5, 2.5]) >>> np.median(a, axis=1) array([7., 2.]) >>> m = np.median(a, axis=0) >>> out = np.zeros_like(m) >>> np.median(a, axis=0, out=m) array([6.5, 4.5, 2.5]) >>> m array([6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.median(b, axis=1, overwrite_input=True) array([7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.median(b, axis=None, overwrite_input=True) 3.5 >>> assert not np.all(a==b)
Return coordinate matrices from coordinate vectors.
Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn.
Cartesian ('xy', default) or matrix ('ij') indexing of output. See Notes for more details.
If True the shape of the returned coordinate array for dimension i is reduced from (N1, ..., Ni, ... Nn) to (1, ..., 1, Ni, 1, ..., 1). These sparse coordinate grids are intended to be use with :ref:`basics.broadcasting`. When all coordinates are used in an expression, broadcasting still leads to a fully-dimensonal result array.
Default is False.
If False, a view into the original arrays are returned in order to conserve memory. Default is True. Please note that sparse=False, copy=False will likely return non-contiguous arrays. Furthermore, more than one element of a broadcast array may refer to a single memory location. If you need to write to the arrays, make copies first.
x1
, x2
,..., 'xn' with lengths Ni=len(xi) ,
return (N1, N2, N3,...Nn) shaped arrays if indexing='ij'
or (N2, N1, N3,...Nn) shaped arrays if indexing='xy'
with the elements of xi
repeated to fill the matrix along
the first dimension for x1
, the second for x2
and so on.This function supports both indexing conventions through the indexing keyword argument. Giving the string 'ij' returns a meshgrid with matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. In the 2-D case with inputs of length M and N, the outputs are of shape (N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case with inputs of length M, N and P, outputs are of shape (N, M, P) for 'xy' indexing and (M, N, P) for 'ij' indexing. The difference is illustrated by the following code snippet:
xv, yv = np.meshgrid(x, y, indexing='ij') for i in range(nx): for j in range(ny): # treat xv[i,j], yv[i,j] xv, yv = np.meshgrid(x, y, indexing='xy') for i in range(nx): for j in range(ny): # treat xv[j,i], yv[j,i]
In the 1-D and 0-D case, the indexing and sparse keywords have no effect.
mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. ogrid : Construct an open multi-dimensional "meshgrid" using indexing
notation.
>>> nx, ny = (3, 2) >>> x = np.linspace(0, 1, nx) >>> y = np.linspace(0, 1, ny) >>> xv, yv = np.meshgrid(x, y) >>> xv array([[0. , 0.5, 1. ], [0. , 0.5, 1. ]]) >>> yv array([[0., 0., 0.], [1., 1., 1.]]) >>> xv, yv = np.meshgrid(x, y, sparse=True) # make sparse output arrays >>> xv array([[0. , 0.5, 1. ]]) >>> yv array([[0.], [1.]])
meshgrid
is very useful to evaluate functions on a grid. If the
function depends on all coordinates, you can use the parameter
sparse=True to save memory and computation time.
>>> x = np.linspace(-5, 5, 101) >>> y = np.linspace(-5, 5, 101) >>> # full coorindate arrays >>> xx, yy = np.meshgrid(x, y) >>> zz = np.sqrt(xx**2 + yy**2) >>> xx.shape, yy.shape, zz.shape ((101, 101), (101, 101), (101, 101)) >>> # sparse coordinate arrays >>> xs, ys = np.meshgrid(x, y, sparse=True) >>> zs = np.sqrt(xs**2 + ys**2) >>> xs.shape, ys.shape, zs.shape ((1, 101), (101, 1), (101, 101)) >>> np.array_equal(zz, zs) True
>>> import matplotlib.pyplot as plt >>> h = plt.contourf(x, y, zs) >>> plt.axis('scaled') >>> plt.colorbar() >>> plt.show()
Return a copy of an array sorted along the first axis.
a
.sort
np.msort(a) is equivalent to np.sort(a, axis=0).
Compute the q-th percentile of the data along the specified axis.
Returns the q-th percentile(s) of the array elements.
Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array.
a
to be modified by intermediate
calculations, to save memory. In this case, the contents of the input
a
after this function completes is undefined.This parameter specifies the method to use for estimating the percentile. There are many different methods, some unique to NumPy. See the notes for explanation. The options sorted by their R type as summarized in the H&F paper [1] are:
The first three methods are discontiuous. NumPy further defines the following discontinuous variations of the default 'linear' (7.) option:
If this is set to True, the axes which are reduced are left in
the result as dimensions with size one. With this option, the
result will broadcast correctly against the original array a
.
Deprecated name for the method keyword argument.
q
is a single percentile and axis=None
, then the result
is a scalar. If multiple percentiles are given, first axis of
the result corresponds to the percentiles. The other axes are
the axes that remain after the reduction of a
. If the input
contains integers or floats smaller than float64, the output
data-type is float64. Otherwise, the output data-type is the
same as that of the input. If out
is specified, that array is
returned instead.mean median : equivalent to percentile(..., 50) nanpercentile quantile : equivalent to percentile, except q in the range [0, 1].
Given a vector V of length N, the q-th percentile of V is
the value q/100 of the way from the minimum to the maximum in a
sorted copy of V. The values and distances of the two nearest
neighbors as well as the method
parameter will determine the
percentile if the normalized ranking does not match the location of
q exactly. This function is the same as the median if q=50, the
same as the minimum if q=0 and the same as the maximum if
q=100.
This optional method
parameter specifies the method to use when the
desired quantile lies between two data points i < j.
If g is the fractional part of the index surrounded by i and
alpha and beta are correction constants modifying i and j.
Below, 'q' is the quantile value, 'n' is the sample size and alpha and beta are constants. The following formula gives an interpolation "i + g" of where the quantile would be in the sorted sample. With 'i' being the floor and 'g' the fractional part of the result.
The different methods then work as follows
>>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.percentile(a, 50) 3.5 >>> np.percentile(a, 50, axis=0) array([6.5, 4.5, 2.5]) >>> np.percentile(a, 50, axis=1) array([7., 2.]) >>> np.percentile(a, 50, axis=1, keepdims=True) array([[7.], [2.]])
>>> m = np.percentile(a, 50, axis=0) >>> out = np.zeros_like(m) >>> np.percentile(a, 50, axis=0, out=out) array([6.5, 4.5, 2.5]) >>> m array([6.5, 4.5, 2.5])
>>> b = a.copy() >>> np.percentile(b, 50, axis=1, overwrite_input=True) array([7., 2.]) >>> assert not np.all(a == b)
The different methods can be visualized graphically:
Evaluate a piecewise-defined function.
Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.
Each boolean array corresponds to a function in funclist
. Wherever
condlist[i]
is True, funclist[i](x)
is used as the output value.
Each boolean array in condlist
selects a piece of x
,
and should therefore be of the same shape as x
.
The length of condlist
must correspond to that of funclist
.
If one extra function is given, i.e. if
len(funclist) == len(condlist) + 1, then that extra function
is the default value, used wherever all conditions are false.
x
wherever its corresponding
condition is True. It should take a 1d array as input and give an 1d
array or a scalar value as output. If, instead of a callable,
a scalar is provided then a constant function (lambda x: scalar) is
assumed.piecewise
are passed to the functions
upon execution, i.e., if called piecewise(..., ..., 1, 'a'), then
each function is called as f(x, 1, 'a').piecewise
are passed to the
functions upon execution, i.e., if called
piecewise(..., ..., alpha=1), then each function is called as
f(x, alpha=1).funclist
on the appropriate portions of x
,
as defined by the boolean arrays in condlist
. Portions not covered
by any condition have a default value of 0.choose, select, where
This is similar to choose or select, except that functions are
evaluated on elements of x
that satisfy the corresponding condition from
condlist
.
The result is:
|-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |--
Define the sigma function, which is -1 for x < 0 and +1 for x >= 0.
>>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
Define the absolute value, which is -x for x <0 and x for x >= 0.
>>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x]) array([2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
Apply the same function to a scalar value.
>>> y = -2 >>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x]) array(2)
Change elements of an array based on conditional and input values.
Similar to np.copyto(arr, vals, where=mask), the difference is that
place
uses the first N elements of vals
, where N is the number of
True values in mask
, while copyto
uses the elements where mask
is True.
Note that extract
does the exact opposite of place
.
a
.a
. Only the first N elements are used, where
N is the number of True values in mask
. If vals
is smaller
than N, it will be repeated, and if elements of a
are to be masked,
this sequence must be non-empty.copyto, put, take, extract
>>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]])
Compute the q-th quantile of the data along the specified axis.
a
to be modified by
intermediate calculations, to save memory. In this case, the
contents of the input a
after this function completes is
undefined.This parameter specifies the method to use for estimating the quantile. There are many different methods, some unique to NumPy. See the notes for explanation. The options sorted by their R type as summarized in the H&F paper [1] are:
The first three methods are discontiuous. NumPy further defines the following discontinuous variations of the default 'linear' (7.) option:
a
.Deprecated name for the method keyword argument.
q
is a single quantile and axis=None
, then the result
is a scalar. If multiple quantiles are given, first axis of
the result corresponds to the quantiles. The other axes are
the axes that remain after the reduction of a
. If the input
contains integers or floats smaller than float64, the output
data-type is float64. Otherwise, the output data-type is the
same as that of the input. If out
is specified, that array is
returned instead.mean percentile : equivalent to quantile, but with q in the range [0, 100]. median : equivalent to quantile(..., 0.5) nanquantile
Given a vector V of length N, the q-th quantile of V is the
value q of the way from the minimum to the maximum in a sorted copy of
V. The values and distances of the two nearest neighbors as well as the
method
parameter will determine the quantile if the normalized
ranking does not match the location of q exactly. This function is the
same as the median if q=0.5, the same as the minimum if q=0.0 and
the same as the maximum if q=1.0.
This optional method
parameter specifies the method to use when the
desired quantile lies between two data points i < j.
If g is the fractional part of the index surrounded by i and
alpha and beta are correction constants modifying i and j.
The different methods then work as follows
>>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.quantile(a, 0.5) 3.5 >>> np.quantile(a, 0.5, axis=0) array([6.5, 4.5, 2.5]) >>> np.quantile(a, 0.5, axis=1) array([7., 2.]) >>> np.quantile(a, 0.5, axis=1, keepdims=True) array([[7.], [2.]]) >>> m = np.quantile(a, 0.5, axis=0) >>> out = np.zeros_like(m) >>> np.quantile(a, 0.5, axis=0, out=out) array([6.5, 4.5, 2.5]) >>> m array([6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.quantile(b, 0.5, axis=1, overwrite_input=True) array([7., 2.]) >>> assert not np.all(a == b)
See also numpy.percentile
for a visualization of most methods.
Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis.
The array is rotated in the plane defined by the axes. Axes must be different.
m
.flip : Reverse the order of elements in an array along the given axis. fliplr : Flip an array horizontally. flipud : Flip an array vertically.
rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))
rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))
>>> m = np.array([[1,2],[3,4]], int) >>> m array([[1, 2], [3, 4]]) >>> np.rot90(m) array([[2, 4], [1, 3]]) >>> np.rot90(m, 2) array([[4, 3], [2, 1]]) >>> m = np.arange(8).reshape((2,2,2)) >>> np.rot90(m, 1, (1,2)) array([[[1, 3], [0, 2]], [[5, 7], [4, 6]]])
Return an array drawn from elements in choicelist, depending on conditions.
choicelist
the output elements are taken. When multiple conditions are satisfied,
the first one encountered in condlist
is used.condlist
.output
when all conditions evaluate to False.choicelist
where the m-th element of the corresponding array in
condlist
is True.where : Return elements from one of two arrays depending on condition. take, choose, compress, diag, diagonal
>>> x = np.arange(6) >>> condlist = [x<3, x>3] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist, 42) array([ 0, 1, 2, 42, 16, 25])
>>> condlist = [x<=4, x>3] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist, 55) array([ 0, 1, 2, 3, 4, 25])
Return the normalized sinc function.
The sinc function is sin(πx) ⁄ (πx).
Note
Note the normalization factor of pi used in the definition. This is the most commonly used definition in signal processing. Use sinc(x / np.pi) to obtain the unnormalized sinc function sin(x) ⁄ (x) that is more common in mathematics.
sinc(0) is the limit value 1.
The name sinc is short for "sine cardinal" or "sinus cardinalis".
The sinc function is used in various signal processing applications, including in anti-aliasing, in the construction of a Lanczos resampling filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function.
[1] | Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/SincFunction.html |
[2] | Wikipedia, "Sinc function", https://en.wikipedia.org/wiki/Sinc_function |
>>> import matplotlib.pyplot as plt >>> x = np.linspace(-4, 4, 41) >>> np.sinc(x) array([-3.89804309e-17, -4.92362781e-02, -8.40918587e-02, # may vary -8.90384387e-02, -5.84680802e-02, 3.89804309e-17, 6.68206631e-02, 1.16434881e-01, 1.26137788e-01, 8.50444803e-02, -3.89804309e-17, -1.03943254e-01, -1.89206682e-01, -2.16236208e-01, -1.55914881e-01, 3.89804309e-17, 2.33872321e-01, 5.04551152e-01, 7.56826729e-01, 9.35489284e-01, 1.00000000e+00, 9.35489284e-01, 7.56826729e-01, 5.04551152e-01, 2.33872321e-01, 3.89804309e-17, -1.55914881e-01, -2.16236208e-01, -1.89206682e-01, -1.03943254e-01, -3.89804309e-17, 8.50444803e-02, 1.26137788e-01, 1.16434881e-01, 6.68206631e-02, 3.89804309e-17, -5.84680802e-02, -8.90384387e-02, -8.40918587e-02, -4.92362781e-02, -3.89804309e-17])
>>> plt.plot(x, np.sinc(x)) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Sinc Function") Text(0.5, 1.0, 'Sinc Function') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("X") Text(0.5, 0, 'X') >>> plt.show()
Sort a complex array using the real part first, then the imaginary part.
>>> np.sort_complex([5, 3, 6, 2, 1]) array([1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])
>>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) array([1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j])
Integrate along the given axis using the composite trapezoidal rule.
If x
is provided, the integration happens in sequence along its
elements - they are not sorted.
Integrate y
(x
) along each 1d slice on the given axis, compute
∫y(x)dx.
When x
is specified, this integrates along the parametric curve,
computing ∫ty(t)dt = ∫ty(t)(dx)/(dt)||x = x(t)dt.
y
values. If x
is None,
the sample points are assumed to be evenly spaced dx
apart. The
default is None.x
is None. The default is 1.sum, cumsum
Image [2] illustrates trapezoidal rule -- y-axis locations of points
will be taken from y
array, by default x-axis distances between
points will be 1.0, alternatively they can be provided with x
array
or with dx
scalar. Return value will be equal to combined area under
the red lines.
[1] | Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule |
[2] | Illustration image: https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png |
>>> np.trapz([1,2,3]) 4.0 >>> np.trapz([1,2,3], x=[4,6,8]) 8.0 >>> np.trapz([1,2,3], dx=2) 8.0
Using a decreasing x
corresponds to integrating in reverse:
>>> np.trapz([1,2,3], x=[8,6,4]) -8.0
More generally x
is used to integrate along a parametric curve.
This finds the area of a circle, noting we repeat the sample which closes
the curve:
>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True) >>> np.trapz(np.cos(theta), x=np.sin(theta)) 3.141571941375841
>>> a = np.arange(6).reshape(2, 3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.trapz(a, axis=0) array([1.5, 2.5, 3.5]) >>> np.trapz(a, axis=1) array([2., 8.])
Trim the leading and/or trailing zeros from a 1-D array or sequence.
>>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1])
>>> np.trim_zeros(a, 'b') array([0, 0, 0, ..., 0, 2, 1])
The input data type is preserved, list/tuple in means list/tuple out.
>>> np.trim_zeros([0, 1, 2, 0]) [1, 2]
Unwrap by taking the complement of large deltas with respect to the period.
This unwraps a signal p
by changing elements which have an absolute
difference from their predecessor of more than max(discont, period/2)
to their period
-complementary values.
For the default case where period
is 2π and discont
is
π, this unwraps a radian phase p
such that adjacent differences
are never greater than π by adding 2kπ for some
integer k.
discont
should be
larger than period/2.Size of the range over which the input wraps. By default, it is 2 pi.
rad2deg, deg2rad
If the discontinuity in p
is smaller than period/2,
but larger than discont
, no unwrapping is done because taking
the complement would only make the discontinuity larger.
>>> phase = np.linspace(0, np.pi, num=5) >>> phase[3:] += np.pi >>> phase array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) # may vary >>> np.unwrap(phase) array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) # may vary >>> np.unwrap([0, 1, 2, -1, 0], period=4) array([0, 1, 2, 3, 4]) >>> np.unwrap([ 1, 2, 3, 4, 5, 6, 1, 2, 3], period=6) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.unwrap([2, 3, 4, 5, 2, 3, 4, 5], period=4) array([2, 3, 4, 5, 6, 7, 8, 9]) >>> phase_deg = np.mod(np.linspace(0 ,720, 19), 360) - 180 >>> np.unwrap(phase_deg, period=360) array([-180., -140., -100., -60., -20., 20., 60., 100., 140., 180., 220., 260., 300., 340., 380., 420., 460., 500., 540.])