New in version 1.16.
Note
As a convenience for __array_function__ implementors, types provides all argument types with an '__array_function__' attribute. This allows implementors to quickly identify cases where they should defer to __array_function__ implementations on other arguments. Implementations should not rely on the iteration order of types.
Most implementations of __array_function__ will start with two checks:
If these conditions hold, __array_function__ should return the result from calling its implementation for func(*args, **kwargs). Otherwise, it should return the sentinel value NotImplemented, indicating that the function is not implemented by these types.
There are no general requirements on the return value from __array_function__, although most sensible implementations should probably return array(s) with the same type as one of the function’s arguments.
It may also be convenient to define a custom decorators (implements below) for registering __array_function__ implementations.
Note that it is not required for __array_function__ implementations to include all of the corresponding NumPy function’s optional arguments (e.g., broadcast_to above omits the irrelevant subok argument). Optional arguments are only passed in to __array_function__ if they were explicitly used in the NumPy function call.
Just like the case for builtin special methods like __add__, properly written __array_function__ methods should always return NotImplemented when an unknown type is encountered. Otherwise, it will be impossible to correctly override NumPy functions from another object if the operation also includes one of your objects.
For the most part, the rules for dispatch with __array_function__ match those for __array_ufunc__. In particular:
If no __array_function__ methods exists, NumPy will default to calling its own implementation, intended for use on NumPy arrays. This case arises, for example, when all array-like arguments are Python numbers or lists. (NumPy arrays do have a __array_function__ method, given below, but it always returns NotImplemented if any argument other than a NumPy array subclass implements __array_function__.)
One deviation from the current behavior of __array_ufunc__ is that NumPy will only call __array_function__ on the first argument of each unique type. This matches Python’s rule for calling reflected methods, and this ensures that checking overloads has acceptable performance even when there are a large number of overloaded arguments.


At the beginning of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The output array is passed in and whatever is returned is passed to the ufunc. Subclasses inherit a default implementation of this method which simply returns the output array unmodified. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the ufunc for computation.
Note
For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.


The value of this attribute is used to determine what type of object to return in situations where there is more than one possibility for the Python type of the returned object. Subclasses inherit a default value of 0.0 for this attribute.
Note
For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.


Note
Subclassing a numpy.ndarray is possible but if your goal is to create an array with modified behavior, as do dask arrays for distributed computation and cupy arrays for GPU-based computation, subclassing is discouraged. Instead, using numpy’s dispatch mechanism is recommended.
The ndarray can be inherited from (in Python or in C) if desired. Therefore, it can form a foundation for many useful classes. Often whether to sub-class the array object or to simply use the core array component as an internal part of a new class is a difficult decision, and can be simply a matter of choice. NumPy has several tools for simplifying how your new object interacts with other array objects, and so the choice may not be significant in the end. One way to simplify the question is by asking yourself if the object you are interested in can be replaced as a single array or does it really require two or more arrays at its core.
Note that asarray always returns the base-class ndarray. If you are confident that your use of the array object can handle any subclass of an ndarray, then asanyarray can be used to allow subclasses to propagate more cleanly through your subroutine. In principal a subclass could redefine any aspect of the array and therefore, under strict guidelines, asanyarray would rarely be useful. However, most subclasses of the array object will not redefine certain aspects of the array object such as the buffer interface, or the attributes of the array. One important example, however, of why your subroutine may not be able to handle an arbitrary subclass of an array is that matrices redefine the “*” operator to be matrix-multiplication, rather than element-by-element multiplication.
See also
Subclassing ndarray
NumPy provides several hooks that classes can customize:
New in version 1.13.
Any class, ndarray subclass or not, can define this method or set it to None in order to override the behavior of NumPy’s ufuncs. This works quite similarly to Python’s __mul__ and other binary operation routines.
The method should return either the result of the operation, or NotImplemented if the operation requested is not implemented.
If one of the input or output arguments has a __array_ufunc__ method, it is executed instead of the ufunc. If more than one of the arguments implements __array_ufunc__, they are tried in the order: subclasses before superclasses, inputs before outputs, otherwise left to right. The first routine returning something other than NotImplemented determines the result. If all of the __array_ufunc__ operations return NotImplemented, a TypeError is raised.
Note
We intend to re-implement numpy functions as (generalized) Ufunc, in which case it will become possible for them to be overridden by the __array_ufunc__ method. A prime candidate is matmul, which currently is not a Ufunc, but could be relatively easily be rewritten as a (set of) generalized Ufuncs. The same may happen with functions such as median, amin, and argsort.
Like with some other special methods in python, such as __hash__ and __iter__, it is possible to indicate that your class does not support ufuncs by setting __array_ufunc__ = None. Ufuncs always raise TypeError when called on an object that sets __array_ufunc__ = None.
The presence of __array_ufunc__ also influences how ndarray handles binary operations like arr + obj and arr
< obj when arr is an ndarray and obj is an instance of a custom class. There are two possibilities. If obj.__array_ufunc__ is present and not None, then ndarray.__add__ and friends will delegate to the ufunc machinery, meaning that arr + obj becomes np.add(arr, obj), and then add invokes obj.__array_ufunc__. This is useful if you want to define an object that acts like an array.
Alternatively, if obj.__array_ufunc__ is set to None, then as a special case, special methods like ndarray.__add__ will notice this and unconditionally raise TypeError. This is useful if you want to create objects that interact with arrays via binary operations, but are not themselves arrays. For example, a units handling system might have an object m representing the “meters” unit, and want to support the syntax arr * m to represent that the array has units of “meters”, but not want to otherwise interact with arrays via ufuncs or otherwise. This can be done by setting __array_ufunc__ = None and defining __mul__ and __rmul__ methods. (Note that this means that writing an __array_ufunc__ that always returns NotImplemented is not quite the same as setting __array_ufunc__ = None: in the former case, arr + obj will raise TypeError, while in the latter case it is possible to define a __radd__ method to prevent this.)
The above does not hold for in-place operators, for which ndarray never returns NotImplemented. Hence, arr += obj would always lead to a TypeError. This is because for arrays in-place operations cannot generically be replaced by a simple reverse operation. (For instance, by default, arr += obj would be translated to arr =
arr + obj, i.e., arr would be replaced, contrary to what is expected for in-place array operations.)
Note
If you define __array_ufunc__:
Note
If a class defines the __array_ufunc__ method, this disables the __array_wrap__, __array_prepare__, __array_priority__ mechanism described below for ufuncs (which may eventually be deprecated).
New in version 1.16.
Note
As a convenience for __array_function__ implementors, types provides all argument types with an '__array_function__' attribute. This allows implementors to quickly identify cases where they should defer to __array_function__ implementations on other arguments. Implementations should not rely on the iteration order of types.
Most implementations of __array_function__ will start with two checks:
If these conditions hold, __array_function__ should return the result from calling its implementation for func(*args, **kwargs). Otherwise, it should return the sentinel value NotImplemented, indicating that the function is not implemented by these types.
There are no general requirements on the return value from __array_function__, although most sensible implementations should probably return array(s) with the same type as one of the function’s arguments.
It may also be convenient to define a custom decorators (implements below) for registering __array_function__ implementations.
Note that it is not required for __array_function__ implementations to include all of the corresponding NumPy function’s optional arguments (e.g., broadcast_to above omits the irrelevant subok argument). Optional arguments are only passed in to __array_function__ if they were explicitly used in the NumPy function call.
Just like the case for builtin special methods like __add__, properly written __array_function__ methods should always return NotImplemented when an unknown type is encountered. Otherwise, it will be impossible to correctly override NumPy functions from another object if the operation also includes one of your objects.
For the most part, the rules for dispatch with __array_function__ match those for __array_ufunc__. In particular:
If no __array_function__ methods exists, NumPy will default to calling its own implementation, intended for use on NumPy arrays. This case arises, for example, when all array-like arguments are Python numbers or lists. (NumPy arrays do have a __array_function__ method, given below, but it always returns NotImplemented if any argument other than a NumPy array subclass implements __array_function__.)
One deviation from the current behavior of __array_ufunc__ is that NumPy will only call __array_function__ on the first argument of each unique type. This matches Python’s rule for calling reflected methods, and this ensures that checking overloads has acceptable performance even when there are a large number of overloaded arguments.
This method is called whenever the system internally allocates a new array from obj, where obj is a subclass (subtype) of the ndarray. It can be used to change attributes of self after construction (so as to ensure a 2-d matrix for example), or to update meta-information from the “parent.” Subclasses inherit a default implementation of this method that does nothing.
At the beginning of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The output array is passed in and whatever is returned is passed to the ufunc. Subclasses inherit a default implementation of this method which simply returns the output array unmodified. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the ufunc for computation.
Note
For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.
At the end of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The ufunc-computed array is passed in and whatever is returned is passed to the user. Subclasses inherit a default implementation of this method, which transforms the array into a new instance of the object’s class. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the user.
Note
For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.
The value of this attribute is used to determine what type of object to return in situations where there is more than one possibility for the Python type of the returned object. Subclasses inherit a default value of 0.0 for this attribute.
Note
For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.
If a class (ndarray subclass or not) having the __array__ method is used as the output object of an ufunc, results will not be written to the object returned by __array__. This practice will return TypeError.
Note
It is strongly advised not to use the matrix subclass. As described below, it makes writing functions that deal consistently with matrices and regular arrays very difficult. Currently, they are mainly used for interacting with scipy.sparse. We hope to provide an alternative for this use, however, and eventually remove the matrix subclass.
matrix objects inherit from the ndarray and therefore, they have the same attributes and methods of ndarrays. There are six important differences of matrix objects, however, that may lead to unexpected results when you use matrices but expect them to act like arrays:
Matrices have special attributes which make calculations easier. These are
matrix.T
Returns the transpose of the matrix.
matrix.H
Returns the (complex) conjugate transpose of self.
matrix.I
Returns the (multiplicative) inverse of invertible self.
matrix.A
Return self as an ndarray object.
Warning
Matrix objects over-ride multiplication, ‘*’, and power, ‘**’, to be matrix-multiplication and matrix power, respectively. If your subroutine can accept sub-classes and you do not convert to base- class arrays, then you must use the ufuncs multiply and power to be sure that you are performing the correct operation for all inputs.
The matrix class is a Python subclass of the ndarray and can be used as a reference for how to construct your own subclass of the ndarray. Matrices can be created from other matrices, strings, and anything else that can be converted to an ndarray . The name “mat “is an alias for “matrix “in NumPy.
matrix(data[, dtype, copy])
Note
It is no longer recommended to use this class, even for linear
asmatrix(data[, dtype])
Interpret the input as a matrix.
bmat(obj[, ldict, gdict])
Build a matrix object from a string, nested sequence, or array.
Example 1: Matrix creation from a string
Example 2: Matrix creation from nested sequence
Example 3: Matrix creation from an array
Memory-mapped files are useful for reading and/or modifying small segments of a large file with regular layout, without reading the entire file into memory. A simple subclass of the ndarray uses a memory-mapped file for the data buffer of the array. For small files, the over-head of reading the entire file into memory is typically not significant, however for large files using memory mapping can save considerable resources.
Memory-mapped-file arrays have one additional method (besides those they inherit from the ndarray): .flush() which must be called manually by the user to ensure that any changes to the array actually get written to disk.
memmap(filename[, dtype, mode, offset, ...])
Create a memory-map to an array stored in a binary file on disk.
memmap.flush()
Write any changes in the array to the file on disk.
Example:
See also
Creating character arrays (numpy.char)
Note
The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, bytes_ or str_, and use the free functions in the numpy.char module for fast vectorized string operations.
These are enhanced arrays of either str_ type or bytes_ type. These arrays inherit from the ndarray, but specially-define the operations +, *, and % on a (broadcasting) element-by-element basis. These operations are not available on the standard ndarray of character type. In addition, the chararray has all of the standard str (and bytes) methods, executing them on an element-by-element basis. Perhaps the easiest way to create a chararray is to use self.view(chararray) where self is an ndarray of str or unicode data-type. However, a chararray can also be created using the numpy.chararray constructor, or via the numpy.char.array function:
chararray(shape[, itemsize, unicode, ...])
Provides a convenient view on arrays of string and unicode values.
core.defchararray.array(obj[, itemsize, ...])
Create a chararray.
Another difference with the standard ndarray of str data-type is that the chararray inherits the feature introduced by Numarray that white-space at the end of any element in the array will be ignored on item retrieval and comparison operations.
See also
Creating record arrays (numpy.rec), Data type routines, Data type objects (dtype).
NumPy provides the recarray class which allows accessing the fields of a structured array as attributes, and a corresponding scalar data type object record.
recarray(shape[, dtype, buf, offset, ...])
Construct an ndarray that allows field access using attributes.
record
A data-type scalar that allows field access as attribute lookup.
See also
Masked arrays
For backward compatibility and as a standard “container “class, the UserArray from Numeric has been brought over to NumPy and named numpy.lib.user_array.container The container class is a Python class whose self.array attribute is an ndarray. Multiple inheritance is probably easier with numpy.lib.user_array.container than with the ndarray itself and so it is included by default. It is not documented here beyond mentioning its existence because you are encouraged to use the ndarray class directly if you can.
numpy.lib.user_array.container(data[, ...])
Standard container-class for easy multiple-inheritance.
Iterators are a powerful concept for array processing. Essentially, iterators implement a generalized for-loop. If myiter is an iterator object, then the Python code:
calls val = next(myiter) repeatedly until StopIteration is raised by the iterator. There are several ways to iterate over an array that may be useful: default iteration, flat iteration, and \(N\)-dimensional enumeration.
The default iterator of an ndarray object is the default Python iterator of a sequence type. Thus, when the array object itself is used as an iterator. The default behavior is equivalent to:
This default iterator selects a sub-array of dimension \(N-1\) from the array. This can be a useful construct for defining recursive algorithms. To loop over the entire array requires \(N\) for-loops.
ndarray.flat
A 1-D iterator over the array.
As mentioned previously, the flat attribute of ndarray objects returns an iterator that will cycle over the entire array in C-style contiguous order.
Here, I’ve used the built-in enumerate iterator to return the iterator index as well as the value.
ndenumerate(arr)
Multidimensional index iterator.
Sometimes it may be useful to get the N-dimensional index while iterating. The ndenumerate iterator can achieve this.
broadcast
Produce an object that mimics broadcasting.
The general concept of broadcasting is also available from Python using the broadcast iterator. This object takes \(N\) objects as inputs and returns an iterator that returns tuples providing each of the input sequence elements in the broadcasted result.


At the end of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The ufunc-computed array is passed in and whatever is returned is passed to the user. Subclasses inherit a default implementation of this method, which transforms the array into a new instance of the object’s class. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the user.
Note
For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.


Currently SciPy project consists of two packages:
NumPy — it provides packages like:
The aim of this document is to describe how to add new tools to SciPy.
SciPy consists of Python packages, called SciPy packages, that are available to Python users via the scipy namespace. Each SciPy package may contain other SciPy packages. And so on. Therefore, the SciPy directory tree is a tree of packages with arbitrary depth and width. Any SciPy package may depend on NumPy packages but the dependence on other SciPy packages should be kept minimal or zero.
A SciPy package contains, in addition to its sources, the following files and directories:
Their contents are described below.
In order to add a Python package to SciPy, its build script (setup.py) must meet certain requirements. The most important requirement is that the package define a configuration(parent_package='',top_path=None) function which returns a dictionary suitable for passing to numpy.distutils.core.setup(..). To simplify the construction of this dictionary, numpy.distutils.misc_util provides the Configuration class, described below.
Below is an example of a minimal setup.py file for a pure SciPy package:
The arguments of the configuration function specify the name of parent SciPy package (parent_package) and the directory location of the main setup.py script (top_path). These arguments, along with the name of the current package, should be passed to the Configuration constructor.
The Configuration constructor has a fourth optional argument, package_path, that can be used when package files are located in a different location than the directory of the setup.py file.
Remaining Configuration arguments are all keyword arguments that will be used to initialize attributes of Configuration instance. Usually, these keywords are the same as the ones that setup(..) function would expect, for example, packages, ext_modules, data_files, include_dirs, libraries, headers, scripts, package_dir, etc. However, the direct specification of these keywords is not recommended as the content of these keyword arguments will not be processed or checked for the consistency of SciPy building system.
Finally, Configuration has .todict() method that returns all the configuration data as a dictionary suitable for passing on to the setup(..) function.
In addition to attributes that can be specified via keyword arguments to Configuration constructor, Configuration instance (let us denote as config) has the following attributes that can be useful in writing setup scripts:
config.add_data_files(*files) — prepend files to data_files list. If files item is a tuple then its first element defines the suffix of where data files are copied relative to package installation directory and the second element specifies the path to data files. By default data files are copied under package installation directory. For example,
will install data files to the following locations
Path to data files can be a function taking no arguments and returning path(s) to data files – this is a useful when data files are generated while building the package. (XXX: explain the step when this function are called exactly)
config.add_data_dir(data_path) — add directory data_path recursively to data_files. The whole directory tree starting at data_path will be copied under package installation directory. If data_path is a tuple then its first element defines the suffix of where data files are copied relative to package installation directory and the second element specifies the path to data directory. By default, data directory are copied under package installation directory under the basename of data_path. For example,
will install data files to the following locations
config.add_extension(name,sources,**kw) — create and add an Extension instance to ext_modules list. The first argument name defines the name of the extension module that will be installed under config.name package. The second argument is a list of sources. add_extension method takes also keyword arguments that are passed on to the Extension constructor. The list of allowed keywords is the following: include_dirs, define_macros, undef_macros, library_dirs, libraries, runtime_library_dirs, extra_objects, extra_compile_args, extra_link_args, export_symbols, swig_opts, depends, language, f2py_options, module_dirs, extra_info, extra_f77_compile_args, extra_f90_compile_args.
Note that config.paths method is applied to all lists that may contain paths. extra_info is a dictionary or a list of dictionaries that content will be appended to keyword arguments. The list depends contains paths to files or directories that the sources of the extension module depend on. If any path in the depends list is newer than the extension module, then the module will be rebuilt.
The list of sources may contain functions (‘source generators’) with a pattern def <funcname>(ext, build_dir): return
<source(s) or None>. If funcname returns None, no sources are generated. And if the Extension instance has no sources after processing all source generators, no extension module will be built. This is the recommended way to conditionally define extension modules. Source generator functions are called by the build_src sub-command of numpy.distutils.
For example, here is a typical source generator function:
The first argument contains the Extension instance that can be useful to access its attributes like depends, sources, etc. lists and modify them during the building process. The second argument gives a path to a build directory that must be used when creating files to a disk.
NumPy distutils supports automatic conversion of source files named <somefile>.src. This facility can be used to maintain very similar code blocks requiring only simple changes between blocks. During the build phase of setup, if a template file named <somefile>.src is encountered, a new file named <somefile> is constructed from the template and placed in the build directory to be used instead. Two forms of template conversion are supported. The first form occurs for files named <file>.ext.src where ext is a recognized Fortran extension (f, f90, f95, f77, for, ftn, pyf). The second form is used for all other cases.
This template converter will replicate all function and subroutine blocks in the file with names that contain ‘<…>’ according to the rules in ‘<…>’. The number of comma-separated words in ‘<…>’ determines the number of times the block is repeated. What these words are indicates what that repeat rule, ‘<…>’, should be replaced with in each block. All of the repeat rules in a block must contain the same number of comma-separated words indicating the number of times that block should be repeated. If the word in the repeat rule needs a comma, leftarrow, or rightarrow, then prepend it with a backslash ‘ '. If a word in the repeat rule matches ‘ \<index>’ then it will be replaced with the <index>-th word in the same repeat specification. There are two forms for the repeat rule: named and short.
A named repeat rule is useful when the same set of repeats must be used several times in a block. It is specified using <rule1=item1, item2, item3,…, itemN>, where N is the number of times the block should be repeated. On each repeat of the block, the entire expression, ‘<…>’ will be replaced first with item1, and then with item2, and so forth until N repeats are accomplished. Once a named repeat specification has been introduced, the same repeat rule may be used in the current block by referring only to the name (i.e. <rule1>).
A short repeat rule looks like <item1, item2, item3, …, itemN>. The rule specifies that the entire expression, ‘<…>’ should be replaced first with item1, and then with item2, and so forth until N repeats are accomplished.
The following predefined named repeat rules are available:
Non-Fortran files use a separate syntax for defining template blocks that should be repeated using a variable expansion similar to the named repeat rules of the Fortran-specific repeats.
NumPy Distutils preprocesses C source files (extension: .c.src) written in a custom templating language to generate C code. The @ symbol is used to wrap macro-style variables to empower a string substitution mechanism that might describe (for instance) a set of data types.
The template language blocks are delimited by /**begin repeat and /**end repeat**/ lines, which may also be nested using consecutively numbered delimiting lines such as /**begin repeat1 and /**end repeat1**/:
The above rules may be clearer in the following template source example:
The preprocessing of generically-typed C source files (whether in NumPy proper or in any third party package using NumPy Distutils) is performed by conv_template.py. The type-specific C files generated (extension: .c) by these modules during the build process are ready to be compiled. This form of generic typing is also supported for C header files (preprocessed to produce .h files).
The header of a typical SciPy __init__.py is:
It is possible to specify config_fc options in setup.py scripts. For example, using
sources=[…], config_fc={‘noopt’:(__file__,1)})
will compile the library sources without optimization flags.
It’s recommended to specify only those config_fc options in such a way that are compiler independent.
Some old Fortran codes need special compiler options in order to work correctly. In order to specify compiler options per source file, numpy.distutils Fortran compiler looks for the following pattern:
in the first 20 lines of the source and use the f77flags for specified type of the fcompiler (the first character C is optional).
TODO: This feature can be easily extended for Fortran 90 codes as well. Let us know if you would need such a feature.


Create a chararray.
Note
This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type string_ or unicode_ and use the free functions in numpy.char for fast vectorized string operations instead.
Versus a regular NumPy array of type str or unicode, this class adds the following functionality:
itemsize is the number of characters per scalar in the resulting array. If itemsize is None, and obj is an object array or a Python list, the itemsize will be automatically determined. If itemsize is provided and obj is of type str or unicode, then the obj string will be chunked into itemsize pieces.
If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (itemsize, unicode, order, etc.).
When true, the resulting chararray can contain Unicode characters, when false only 8-bit characters. If unicode is None and obj is one of the following:
then the unicode setting of the output array will be automatically determined.
Specify the order of the array. If order is ‘C’ (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is ‘F’, then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is ‘A’, then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous).


Convert the input to a chararray, copying the data only if necessary.
Versus a regular NumPy array of type str or unicode, this class adds the following functionality:
itemsize is the number of characters per scalar in the resulting array. If itemsize is None, and obj is an object array or a Python list, the itemsize will be automatically determined. If itemsize is provided and obj is of type str or unicode, then the obj string will be chunked into itemsize pieces.
When true, the resulting chararray can contain Unicode characters, when false only 8-bit characters. If unicode is None and obj is one of the following:
then the unicode setting of the output array will be automatically determined.
Specify the order of the array. If order is ‘C’ (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is ‘F’, then the returned array will be in Fortran-contiguous order (first-index varies the fastest).


Construct a record array from a wide-variety of objects.
A general-purpose record array constructor that dispatches to the appropriate recarray creation function based on the inputs (see Notes).
Input object. See Notes for details on how various input types are treated.
Valid dtype for array.
Shape of each array.
Position in the file or buffer to start reading from.
Buffer (buf) is interpreted according to these strides (strides define how many bytes each array element, row, column, etc. occupy in memory).
If dtype is None, these arguments are passed to numpy.format_parser to construct a dtype. See that function for detailed documentation.
Whether to copy the input object (True), or to use a reference instead. This option only applies when the input is an ndarray or recarray. Defaults to True.
Record array created from the specified object.
If obj is None, then call the recarray constructor. If obj is a string, then call the fromstring constructor. If obj is a list or a tuple, then if the first object is an ndarray, call fromarrays, otherwise call fromrecords. If obj is a recarray, then make a copy of the data in the recarray (if copy=True) and use the new formats, names, and titles. If obj is a file, then call fromfile. Finally, if obj is an ndarray, then return obj.view(recarray), making a copy of the data if copy=True.


Create a record array from a (flat) list of arrays
List of array-like objects (such as lists, tuples, and ndarrays).
valid dtype for all arrays
Shape of the resulting array. If not provided, inferred from arrayList[0].
If dtype is None, these arguments are passed to numpy.format_parser to construct a dtype. See that function for detailed documentation.
Record array consisting of given arrayList columns.


Create an array from binary file data
If file is a string or a path-like object then that file is opened, else it is assumed to be a file object. The file object must support random access (i.e. it must have tell and seek methods).
valid dtype for all arrays
shape of each array.
Position in the file to start reading from.
If dtype is None, these arguments are passed to numpy.format_parser to construct a dtype. See that function for detailed documentation
record array consisting of data enclosed in file.


Create a recarray from a list of records in text form.
data in the same field may be heterogeneous - they will be promoted to the highest data type.
valid dtype for all arrays
shape of each array.
If dtype is None, these arguments are passed to numpy.format_parser to construct a dtype. See that function for detailed documentation.
If both formats and dtype are None, then this will auto-detect formats. Use list of tuples rather than list of lists for faster processing.
record array consisting of given recList rows.


Create a record array from binary data
Note that despite the name of this function it does not accept str instances.
Buffer of binary data
Valid dtype for all arrays
Shape of each array.
Position in the buffer to start reading from.
If dtype is None, these arguments are passed to numpy.format_parser to construct a dtype. See that function for detailed documentation.
Record array view into the data in datastring. This will be readonly if datastring is readonly.
See also


The SciPy module scipy.fft is a more comprehensive superset of numpy.fft, which includes only a basic set of routines.
fft(a[, n, axis, norm])
Compute the one-dimensional discrete Fourier Transform.
ifft(a[, n, axis, norm])
Compute the one-dimensional inverse discrete Fourier Transform.
fft2(a[, s, axes, norm])
Compute the 2-dimensional discrete Fourier Transform.
ifft2(a[, s, axes, norm])
Compute the 2-dimensional inverse discrete Fourier Transform.
fftn(a[, s, axes, norm])
Compute the N-dimensional discrete Fourier Transform.
ifftn(a[, s, axes, norm])
Compute the N-dimensional inverse discrete Fourier Transform.
rfft(a[, n, axis, norm])
Compute the one-dimensional discrete Fourier Transform for real input.
irfft(a[, n, axis, norm])
Computes the inverse of rfft.
rfft2(a[, s, axes, norm])
Compute the 2-dimensional FFT of a real array.
irfft2(a[, s, axes, norm])
Computes the inverse of rfft2.
rfftn(a[, s, axes, norm])
Compute the N-dimensional discrete Fourier Transform for real input.
irfftn(a[, s, axes, norm])
Computes the inverse of rfftn.
hfft(a[, n, axis, norm])
Compute the FFT of a signal that has Hermitian symmetry, i.e., a real spectrum.
ihfft(a[, n, axis, norm])
Compute the inverse FFT of a signal that has Hermitian symmetry.
fftfreq(n[, d])
Return the Discrete Fourier Transform sample frequencies.
rfftfreq(n[, d])
Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft).
fftshift(x[, axes])
Shift the zero-frequency component to the center of the spectrum.
ifftshift(x[, axes])
The inverse of fftshift.
Fourier analysis is fundamentally a method for expressing a function as a sum of periodic components, and for recovering the function from those components. When both the function and its Fourier transform are replaced with discretized counterparts, it is called the discrete Fourier transform (DFT). The DFT has become a mainstay of numerical computing in part because of a very fast algorithm for computing it, called the Fast Fourier Transform (FFT), which was known to Gauss (1805) and was brought to light in its current form by Cooley and Tukey [CT]. Press et al. [NR] provide an accessible introduction to Fourier analysis and its applications.
Because the discrete Fourier transform separates its input into components that contribute at discrete frequencies, it has a great number of applications in digital signal processing, e.g., for filtering, and in this context the discretized input to the transform is customarily referred to as a signal, which exists in the time domain. The output is called a spectrum or transform and exists in the frequency domain.
There are many ways to define the DFT, varying in the sign of the exponent, normalization, etc. In this implementation, the DFT is defined as
The DFT is in general defined for complex inputs and outputs, and a single-frequency component at linear frequency \(f\) is represented by a complex exponential \(a_m = \exp\{2\pi i\,f m\Delta t\}\), where \(\Delta t\) is the sampling interval.
The values in the result follow so-called “standard” order: If A =
fft(a, n), then A[0] contains the zero-frequency term (the sum of the signal), which is always purely real for real inputs. Then A[1:n/2] contains the positive-frequency terms, and A[n/2+1:] contains the negative-frequency terms, in order of decreasingly negative frequency. For an even number of input points, A[n/2] represents both positive and negative Nyquist frequency, and is also purely real for real input. For an odd number of input points, A[(n-1)/2] contains the largest positive frequency, while A[(n+1)/2] contains the largest negative frequency. The routine np.fft.fftfreq(n) returns an array giving the frequencies of corresponding elements in the output. The routine np.fft.fftshift(A) shifts transforms and their frequencies to put the zero-frequency components in the middle, and np.fft.ifftshift(A) undoes that shift.
When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).
The inverse DFT is defined as
It differs from the forward transform by the sign of the exponential argument and the default normalization by \(1/n\).
numpy.fft promotes float32 and complex64 arrays to float64 and complex128 arrays respectively. For an FFT implementation that does not promote input arrays, see scipy.fftpack.
The argument norm indicates which direction of the pair of direct/inverse transforms is scaled and with what normalization factor. The default normalization ("backward") has the direct (forward) transforms unscaled and the inverse (backward) transforms scaled by \(1/n\). It is possible to obtain unitary transforms by setting the keyword argument norm to "ortho" so that both direct and inverse transforms are scaled by \(1/\sqrt{n}\). Finally, setting the keyword argument norm to "forward" has the direct transforms scaled by \(1/n\) and the inverse transforms unscaled (i.e. exactly opposite to the default "backward"). None is an alias of the default option "backward" for backward compatibility.
When the input is purely real, its transform is Hermitian, i.e., the component at frequency \(f_k\) is the complex conjugate of the component at frequency \(-f_k\), which means that for real inputs there is no information in the negative frequency components that is not already available from the positive frequency components. The family of rfft functions is designed to operate on real inputs, and exploits this symmetry by computing only the positive frequency components, up to and including the Nyquist frequency. Thus, n input points produce n/2+1 complex output points. The inverses of this family assumes the same symmetry of its input, and for an output of n points uses n/2+1 input points.
Correspondingly, when the spectrum is purely real, the signal is Hermitian. The hfft family of functions exploits this symmetry by using n/2+1 complex points in the input (time) domain for n real points in the frequency domain.
In higher dimensions, FFTs are used, e.g., for image analysis and filtering. The computational efficiency of the FFT means that it can also be a faster way to compute large convolutions, using the property that a convolution in the time domain is equivalent to a point-by-point multiplication in the frequency domain.
In two dimensions, the DFT is defined as
which extends in the obvious way to higher dimensions, and the inverses in higher dimensions also extend in the same way.
Cooley, James W., and John W. Tukey, 1965, “An algorithm for the machine calculation of complex Fourier series,” Math. Comput. 19: 297-301.
Press, W., Teukolsky, S., Vetterline, W.T., and Flannery, B.P., 2007, Numerical Recipes: The Art of Scientific Computing, ch. 12-13. Cambridge Univ. Press, Cambridge, UK.
For examples, see the various functions.


method
Return absolute path of file in the DataSource directory.
If path is an URL, then abspath will return either the location the file exists locally or the location it would exist when opened using the open method.
Can be a local file or a remote URL.
Complete path, including the DataSource destination directory.
The functionality is based on os.path.abspath.


method
Test if path exists.
Test if path exists as (and in this order):
Can be a local file or a remote URL.
True if path exists.
When path is an URL, exists will return True if it’s either stored locally in the DataSource directory, or is a valid remote URL. DataSource does not discriminate between the two, the file is accessible if it exists in either location.


method
Open and return file-like object.
If path is an URL, it will be downloaded, stored in the DataSource directory and opened from there.
Local file path or URL to open.
Mode to open path. Mode ‘r’ for reading, ‘w’ for writing, ‘a’ to append. Available modes depend on the type of object specified by path. Default is ‘r’.
Open text file with given encoding. The default encoding will be what io.open uses.
Newline to use when reading text file.
File object.


NumPy provides several functions to create arrays from tabular data. We focus here on the genfromtxt function.
In a nutshell, genfromtxt runs two main loops. The first loop converts each line of the file in a sequence of strings. The second loop converts each string to the appropriate data type. This mechanism is slower than a single loop, but gives more flexibility. In particular, genfromtxt is able to take missing data into account, when other faster and simpler functions like loadtxt cannot.
Note
When giving examples, we will use the following conventions:
The only mandatory argument of genfromtxt is the source of the data. It can be a string, a list of strings, a generator or an open file-like object with a read method, for example, a file or io.StringIO object. If a single string is provided, it is assumed to be the name of a local or remote file. If a list of strings or a generator returning strings is provided, each string is treated as one line in a file. When the URL of a remote file is passed, the file is automatically downloaded to the current directory and opened.
Recognized file types are text files and archives. Currently, the function recognizes gzip and bz2 (bzip2) archives. The type of the archive is determined from the extension of the file: if the filename ends with '.gz', a gzip archive is expected; if it ends with 'bz2', a bzip2 archive is assumed.
Once the file is defined and open for reading, genfromtxt splits each non-empty line into a sequence of strings. Empty or commented lines are just skipped. The delimiter keyword is used to define how the splitting should take place.
Quite often, a single character marks the separation between columns. For example, comma-separated files (CSV) use a comma (,) or a semicolon (;) as delimiter:
Another common separator is "\t", the tabulation character. However, we are not limited to a single character, any string will do. By default, genfromtxt assumes delimiter=None, meaning that the line is split along white spaces (including tabs) and that consecutive white spaces are considered as a single white space.
Alternatively, we may be dealing with a fixed-width file, where columns are defined as a given number of characters. In that case, we need to set delimiter to a single integer (if all the columns have the same size) or to a sequence of integers (if columns can have different sizes):
By default, when a line is decomposed into a series of strings, the individual entries are not stripped of leading nor trailing white spaces. This behavior can be overwritten by setting the optional argument autostrip to a value of True:
The optional argument comments is used to define a character string that marks the beginning of a comment. By default, genfromtxt assumes comments='#'. The comment marker may occur anywhere on the line. Any character present after the comment marker(s) is simply ignored:
New in version 1.7.0: When comments is set to None, no lines are treated as comments.
Note
There is one notable exception to this behavior: if the optional argument names=True, the first commented line will be examined for names.
The presence of a header in the file can hinder data processing. In that case, we need to use the skip_header optional argument. The values of this argument must be an integer which corresponds to the number of lines to skip at the beginning of the file, before any other action is performed. Similarly, we can skip the last n lines of the file by using the skip_footer attribute and giving it a value of n:
By default, skip_header=0 and skip_footer=0, meaning that no lines are skipped.
In some cases, we are not interested in all the columns of the data but only a few of them. We can select which columns to import with the usecols argument. This argument accepts a single integer or a sequence of integers corresponding to the indices of the columns to import. Remember that by convention, the first column has an index of 0. Negative integers behave the same as regular Python negative indexes.
For example, if we want to import only the first and the last columns, we can use usecols=(0, -1):
If the columns have names, we can also select which columns to import by giving their name to the usecols argument, either as a sequence of strings or a comma-separated string:
The main way to control how the sequences of strings we have read from the file are converted to other types is to set the dtype argument. Acceptable values for this argument are:
In all the cases but the first one, the output will be a 1D array with a structured dtype. This dtype has as many fields as items in the sequence. The field names are defined with the names keyword.
When dtype=None, the type of each column is determined iteratively from its data. We start by checking whether a string can be converted to a boolean (that is, if the string matches true or false in lower cases); then whether it can be converted to an integer, then to a float, then to a complex and eventually to a string. This behavior may be changed by modifying the default mapper of the StringConverter class.
The option dtype=None is provided for convenience. However, it is significantly slower than setting the dtype explicitly.
A natural approach when dealing with tabular data is to allocate a name to each column. A first possibility is to use an explicit structured dtype, as mentioned previously:
Another simpler possibility is to use the names keyword with a sequence of strings or a comma-separated string:
In the example above, we used the fact that by default, dtype=float. By giving a sequence of names, we are forcing the output to a structured dtype.
We may sometimes need to define the column names from the data itself. In that case, we must use the names keyword with a value of True. The names will then be read from the first line (after the skip_header ones), even if the line is commented out:
The default value of names is None. If we give any other value to the keyword, the new names will overwrite the field names we may have defined with the dtype:
If names=None but a structured dtype is expected, names are defined with the standard NumPy default of "f%i", yielding names like f0, f1 and so forth:
In the same way, if we don’t give enough names to match the length of the dtype, the missing names will be defined with this default template:
We can overwrite this default with the defaultfmt argument, that takes any format string:
Note
We need to keep in mind that defaultfmt is used only if some names are expected but not defined.
NumPy arrays with a structured dtype can also be viewed as recarray, where a field can be accessed as if it were an attribute. For that reason, we may need to make sure that the field name doesn’t contain any space or invalid character, or that it does not correspond to the name of a standard attribute (like size or shape), which would confuse the interpreter. genfromtxt accepts three optional arguments that provide a finer control on the names:
Gives a string combining all the characters that must be deleted from the name. By default, invalid characters are ~!@#$%^&*()-=+~\|]}[{';:
/?.>,<.
Gives a list of the names to exclude, such as return, file, print… If one of the input name is part of this list, an underscore character ('_') will be appended to it.
Whether the names should be case-sensitive (case_sensitive=True), converted to upper case (case_sensitive=False or case_sensitive='upper') or to lower case (case_sensitive='lower').
Usually, defining a dtype is sufficient to define how the sequence of strings must be converted. However, some additional control may sometimes be required. For example, we may want to make sure that a date in a format YYYY/MM/DD is converted to a datetime object, or that a string like xx% is properly converted to a float between 0 and 1. In such cases, we should define conversion functions with the converters arguments.
The value of this argument is typically a dictionary with column indices or column names as keys and a conversion functions as values. These conversion functions can either be actual functions or lambda functions. In any case, they should accept only a string as input and output only a single element of the wanted type.
In the following example, the second column is converted from as string representing a percentage to a float between 0 and 1:
We need to keep in mind that by default, dtype=float. A float is therefore expected for the second column. However, the strings ' 2.3%' and ' 78.9%' cannot be converted to float and we end up having np.nan instead. Let’s now use a converter:
The same results can be obtained by using the name of the second column ("p") as key instead of its index (1):
Converters can also be used to provide a default for missing entries. In the following example, the converter convert transforms a stripped string into the corresponding float or into -999 if the string is empty. We need to explicitly strip the string from white spaces as it is not done by default:
Some entries may be missing in the dataset we are trying to import. In a previous example, we used a converter to transform an empty string into a float. However, user-defined converters may rapidly become cumbersome to manage.
The genfromtxt function provides two other complementary mechanisms: the missing_values argument is used to recognize missing data and a second argument, filling_values, is used to process these missing data.
By default, any empty string is marked as missing. We can also consider more complex strings, such as "N/A" or "???" to represent missing or invalid data. The missing_values argument accepts three kinds of values:
This string will be used as the marker for missing data for all the columns
In that case, each item is associated to a column, in order.
Values of the dictionary are strings or sequence of strings. The corresponding keys can be column indices (integers) or column names (strings). In addition, the special key None can be used to define a default applicable to all columns.
We know how to recognize missing data, but we still need to provide a value for these missing entries. By default, this value is determined from the expected dtype according to this table:
Expected type
Default
bool
False
int
-1
float
np.nan
complex
np.nan+0j
string
'???'
We can get a finer control on the conversion of missing values with the filling_values optional argument. Like missing_values, this argument accepts different kind of values:
This will be the default for all columns
Each entry will be the default for the corresponding column
Each key can be a column index or a column name, and the corresponding value should be a single object. We can use the special key None to define a default for all columns.
In the following example, we suppose that the missing values are flagged with "N/A" in the first column and by "???" in the third column. We wish to transform these missing values to 0 if they occur in the first and second column, and to -999 if they occur in the last column:
We may also want to keep track of the occurrence of missing data by constructing a boolean mask, with True entries where data was missing and False otherwise. To do that, we just have to set the optional argument usemask to True (the default is False). The output array will then be a MaskedArray.
In addition to genfromtxt, the numpy.lib.npyio module provides several convenience functions derived from genfromtxt. These functions work the same way as the original, but they have different default values.
Returns a standard numpy.recarray (if usemask=False) or a MaskedRecords array (if usemaske=True). The default dtype is dtype=None, meaning that the types of each column will be automatically determined.
Like recfromtxt, but with a default delimiter=",".


Compile one or more source files.
Please refer to the Python distutils API reference for more details.
A list of filenames
Path to the output directory.
A list of macro definitions.
The directories to add to the default include file search path for this compilation only.
Whether or not to output debug symbols in or alongside the object file(s).
Extra pre- and post-arguments.
A list of file names that all targets depend on.
A list of object file names, one per source file sources.
If compilation fails.


Do any platform-specific customization of a compiler instance.
This method calls distutils.sysconfig.customize_compiler for platform-specific customization, as well as optionally remove a flag to suppress spurious warnings in case C++ code is being compiled.
This parameter is not used for anything.
Whether or not C++ has to be compiled. If so (True), the "-Wstrict-prototypes" option is removed to prevent spurious warnings. Default is False.
All the default options used by distutils can be extracted with:


Customize compiler using distutils command.
An instance inheriting from distutils.cmd.Command.
List of CCompiler commands (without 'set_') that should not be altered. Strings that are checked for are: ('include_dirs', 'define', 'undef', 'libraries', 'library_dirs',
'rpath', 'link_objects').


Return the C++ compiler.
The C++ compiler, as a CCompiler instance.


Does nothing here, but is called by the get_version method and can be overridden by subclasses. In particular it is redefined in the FCompiler class where more documentation can be found.


Return compiler version, or None if compiler is not available.
If True, force a new determination of the version, even if the compiler already has a version attribute. Default is False.
The list of status values returned by the version look-up process for which a version string is returned. If the status value is not in ok_status, None is returned. Default is [0].
Version string, in the format of distutils.version.LooseVersion.


Return the name of the object files for the given source files.
The list of paths to source files. Paths can be either relative or absolute, this is handled transparently.
Whether to strip the directory from the returned paths. If True, the file name prepended by output_dir is returned. Default is False.
If given, this path is prepended to the returned paths to the object files.
The list of paths to the object files corresponding to the source files in source_filenames.


Print the compiler customizations to stdout.
Printing is only done if the distutils log threshold is < 2.


Execute a command in a sub-process.
The command to execute.
The text to add to the log file kept by numpy.distutils. If not given, display is equal to cmd.
If the command failed, i.e. the exit status was not 0.


Simple matching of version numbers, for use in CCompiler and FCompiler.
A regular expression matching version numbers. Default is r'[-.\d]+'.
A regular expression matching patterns to skip. Default is '', in which case nothing is skipped.
A regular expression matching the start of where to start looking for version numbers. Default is '', in which case searching is started at the beginning of the version string given to matcher.
A function that is appropriate to use as the .version_match attribute of a CCompiler class. matcher takes a single parameter, a version string.


method
Remove the conflicts that caused due gathering implied features flags.
flags should be sorted from the lowest to the highest interest.


method
Return a dictionary of supported CPU features by the platform, and accumulate the rest of undefined options in conf_features, the returned dict has same rules and notes in class attribute conf_features, also its override any options that been set in ‘conf_features’.


method
Returns a list of final CPU baseline compiler flags


method
return a list of final CPU baseline feature names


method
return a list of final CPU dispatch feature names


method
Return a tuple containing info about (platform, compiler, extra_args), required by the abstract class ‘_CCompiler’ for discovering the platform environment. This is also used as a cache factor in order to detect any changes happening from outside.


method
Return True if ‘CCompiler.compile()’ able to compile a source file with certain flags.


method
Return list of features in ‘names’ after remove any implied features and keep the origins.
sequence of CPU feature names in uppercase.


method
Generate C preprocessor definitions and include headers of a CPU feature.
CPU feature name in uppercase.
if > 0, align the generated strings to the right depend on number of tabs.


method
Return a list of CPU features that required to be detected sorted from the lowest to highest interest.


method
same as feature_implies_c() but stop collecting implied features when feature’s option that provided through parameter ‘keyisfalse’ is False, also sorting the returned features.


method
Return a set of CPU features that implied by ‘names’
CPU feature name(s) in uppercase.
if False(default) then the returned set will not contain any features from ‘names’. This case happens only when two features imply each other.


method
same as feature_implies() but combining ‘names’


method
Returns True if a certain feature is exist and covered within _Config.conf_features.
feature name in uppercase.


method
Returns a set of CPU feature names that supported by platform and the C compiler.
Specify certain CPU features to test it against the C compiler. if None(default), it will test all current supported features. Note: feature names must be in upper-case.
If None(default), default compiler flags for every CPU feature will be used during the test.
A list of C macro definitions.


method
Sort a list of CPU features ordered by the lowest interest.
sequence of supported feature names in uppercase.
If true, the sorted features is reversed. (highest interest)


method
same as ‘feature_ahead()’ but if both features implied each other and keep the highest interest.
sequence of CPU feature names in uppercase.


method
Generate the dispatch header which contains the #definitions and headers for platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features.
Its highly recommended to take a look at the generated header also the generated source files via try_dispatch() in order to get the full picture.


method
Returns True if the class loaded from the cache file


method
Fetch and parse configuration statements that required for defining the targeted CPU features, statements should be declared in the top of source in between C comment and start with a special mark @targets.
Configuration statements are sort of keywords representing CPU features names, group of statements and policies, combined together to determine the required optimization.
the path of C source file.


method
Compile one or more dispatch-able sources and generates object files, also generates abstract C config headers and macros that used later for the final runtime dispatching process.
The mechanism behind it is to takes each source file that specified in ‘sources’ and branching it into several files depend on special configuration statements that must be declared in the top of each source which contains targeted CPU features, then it compiles every branched source with the proper compiler flags.
Must be a list of dispatch-able sources file paths, and configuration statements must be declared inside each file.
Path of parent directory for the generated headers and wrapped sources. If None(default) the files will generated in-place.
Distutils CCompiler instance to be used for compilation. If None (default), the provided instance during the initialization will be used instead.
Arguments to pass on to the CCompiler.compile()
Raises by CCompiler.compile() on compiling failure.
Some errors during checking the sanity of configuration statements.
See also
Parsing the configuration statements of dispatch-able sources.


Create a new instance of ‘CCompilerOpt’ and generate the dispatch header which contains the #definitions and headers of platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features.
path of the dispatch header


Return (status,output) of executed command.
Deprecated since version 1.17: Use subprocess.Popen instead
A concatenated string of executable and arguments.
Before running command cd execute_in and after cd -.
If True, execute sh -c command. Default None (True)
If True use tee. Default None (True)
Both stdout and stderr messages.
On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0.


Convert bytes in the encoding used by a subprocess into a filesystem-appropriate str.
Inherited from exec_command, and possibly incorrect.


Return full path of a executable or None.
Symbolic links are not followed.


Forward bytes from a subprocess call to the console, without attempting to decode them.
The assumption is that the subprocess call already returned bytes in a suitable encoding.


0 - do nothing 1 - display warning message 2 - raise error


Returns a list of files named ‘fname’ from 1) System-wide directory (directory-location of this module) 2) Users HOME directory (os.environ[‘HOME’]) 3) Local directory


Set Default behavior for copy the limbo.


method
Return a parametrized wrapper around the dtype type.
New in version 1.22.
A parametrized dtype type.
See also
Type hinting generics in standard collections.
This method is only available for python 3.9 and later.


attribute
The required alignment (bytes) of this data-type according to the compiler.
More information is available in the C-API section of the manual.


attribute
Returns dtype for the base element of the subarrays, regardless of their dimension or shape.
See also


attribute
A character indicating the byte-order of this data-type object.
One of:
‘=’
native
‘<’
little-endian
‘>’
big-endian
‘|’
not applicable
All built-in data-type objects have byteorder either ‘=’ or ‘|’.


attribute
A unique character code for each of the 21 different built-in types.


attribute
__array_interface__ description of the data-type.
The format is that required by the ‘descr’ key in the __array_interface__ attribute.
Warning: This attribute exists specifically for __array_interface__, and passing it directly to np.dtype will not accurately reconstruct some dtypes (e.g., scalar and subarray dtypes).


attribute
Dictionary of named fields defined for this data type, or None.
The dictionary is indexed by keys that are the names of the fields. Each entry in the dictionary is a tuple fully describing the field:
Offset is limited to C int, which is signed and usually 32 bits. If present, the optional title can be any object (if it is a string or unicode then it will also be a key in the fields dictionary, otherwise it’s meta-data). Notice also that the first two elements of the tuple can be passed directly as arguments to the ndarray.getfield and ndarray.setfield methods.
See also


attribute
Bit-flags describing how this data type is to be interpreted.
Bit-masks are in numpy.core.multiarray as the constants ITEM_HASOBJECT, LIST_PICKLE, ITEM_IS_POINTER, NEEDS_INIT, NEEDS_PYAPI, USE_GETITEM, USE_SETITEM. A full explanation of these flags is in C-API documentation; they are largely useful for user-defined data-types.
The following example demonstrates that operations on this particular dtype requires Python C-API.


attribute
Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes.
Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer). Special handling may be required, and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won’t.


attribute
Boolean indicating whether the dtype is a struct which maintains field alignment. This flag is sticky, so when combining multiple structs together, it is preserved and produces new dtypes which are also aligned.


attribute
Integer indicating how this dtype relates to the built-in dtypes.
Read-only.
0
if this is a structured array type, with fields
1
if this is a dtype compiled into numpy (such as ints, floats etc)
2
if the dtype is for a user-defined numpy type A user-defined type uses the numpy C-API machinery to extend numpy to handle a new array type. See User-defined data-types in the NumPy manual.


attribute
Boolean indicating whether the byte order of this dtype is native to the platform.


attribute
The element size of this data-type object.
For 18 of the 21 types this number is fixed by the data-type. For the flexible data-types, this number can be anything.


attribute
A character code (one of ‘biufcmMOSUV’) identifying the general kind of data.
b
boolean
i
signed integer
u
unsigned integer
f
floating-point
c
complex floating-point
m
timedelta
M
datetime
O
object
S
(byte-)string
U
Unicode
V
void


attribute
Either None or a readonly dictionary of metadata (mappingproxy).
The metadata field can be set using any dictionary at data-type creation. NumPy currently has no uniform approach to propagating metadata; although some array operations preserve it, there is no guarantee that others will.
Warning
Although used in certain projects, this feature was long undocumented and is not well supported. Some aspects of metadata propagation are expected to change in the future.
Adding arrays with identical datatypes currently preserves the metadata:
But if the arrays have different dtype metadata, the metadata may be dropped:


attribute
A bit-width name for this data-type.
Un-sized flexible data-type objects do not have this attribute.


attribute
Ordered list of field names, or None if there are no fields.
The names are ordered according to increasing byte offset. This can be used, for example, to walk through all of the named fields in offset order.


attribute
Number of dimensions of the sub-array if this data type describes a sub-array, and 0 otherwise.
New in version 1.13.0.


method
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
Byte order to force; a value from the byte order specifications below. The default value (‘S’) results in swapping the current byte order. new_order codes can be any of:
New dtype object with the given change to the byte order.
Changes are also made in all fields and sub-arrays of the data type.


attribute
A unique number for each of the 21 different built-in types.
These are roughly ordered from least-to-most precision.


attribute
Shape tuple of the sub-array if this data type describes a sub-array, and () otherwise.


attribute
The array-protocol typestring of this data-type object.


attribute
Tuple (item_dtype, shape) if this dtype describes a sub-array, and None otherwise.
The shape is the fixed shape of the sub-array described by this data type, and item_dtype the data type of the array.
If a field whose dtype object has this attribute is retrieved, then the extra dimensions implied by shape are tacked on to the end of the retrieved array.
See also


exec_command
Implements exec_command function that is (almost) equivalent to commands.getstatusoutput function but on NT, DOS systems the returned status is actually correct (though, the returned status values may be different by a factor). In addition, exec_command takes keyword arguments for (re-)defining environment variables.
Provides functions:
in the modified environment.
variable PATH. Equivalent to posix which command.
Author: Pearu Peterson <pearu@cens.ioc.ee> Created: 11 January 2003
Requires: Python 2.x
Successfully tested on:
os.name
sys.platform
comments
posix
linux2
Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3 PyCrust 0.9.3, Idle 1.0.2
posix
linux2
Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2
posix
sunos5
SunOS 5.9, Python 2.2, 2.3.2
posix
darwin
Darwin 7.2.0, Python 2.3
nt
win32
Windows Me Python 2.3(EE), Idle 1.0, PyCrust 0.7.2 Python 2.1.1 Idle 0.8
nt
win32
Windows 98, Python 2.1.1. Idle 0.8
nt
win32
Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests fail i.e. redefining environment variables may not work. FIXED: don’t use cygwin echo! Comment: also cmd /c echo will not work but redefining environment variables do work.
posix
cygwin
Cygwin 98-4.10, Python 2.3.3(cygming special)
nt
win32
Windows XP, Python 2.3.3
Known bugs:
exec_command(command[, execute_in, ...])
Return (status,output) of executed command.
filepath_from_subprocess_output(output)
Convert bytes in the encoding used by a subprocess into a filesystem-appropriate str.
find_executable(exe[, path, _cache])
Return full path of a executable or None.
forward_bytes_to_stdout(val)
Forward bytes from a subprocess call to the console, without attempting to decode them.
get_pythonexe()
temp_file_name()


The BitGenerators have been designed to be extendable using standard tools for high-performance Python – numba and Cython. The Generator object can also be used with user-provided BitGenerators as long as these export a small set of required functions.
Numba can be used with either CTypes or CFFI. The current iteration of the BitGenerators all export a small set of functions through both interfaces.
This example shows how numba can be used to produce gaussian samples using a pure Python implementation which is then compiled. The random numbers are provided by ctypes.next_double.
Both CTypes and CFFI allow the more complicated distributions to be used directly in Numba after compiling the file distributions.c into a DLL or so. An example showing the use of a more complicated distribution is in the examples section below.
Cython can be used to unpack the PyCapsule provided by a BitGenerator. This example uses PCG64 and the example from above. The usual caveats for writing high-performance code using Cython – removing bounds checks and wrap around, providing array alignment information – still apply.
The BitGenerator can also be directly accessed using the members of the bitgen_t struct.
Cython can be used to directly access the functions in numpy/random/c_distributions.pxd. This requires linking with the npyrandom library located in numpy/random/lib.
See Extending numpy.random via Cython for the complete listings of these examples and a minimal setup.py to build the c-extension modules.
CFFI can be used to directly access the functions in include/numpy/random/distributions.h. Some “massaging” of the header file is required:
Once the header is parsed by ffi.cdef, the functions can be accessed directly from the _generator shared object, using the BitGenerator.cffi interface.
Generator can be used with user-provided BitGenerators. The simplest way to write a new BitGenerator is to examine the pyx file of one of the existing BitGenerators. The key structure that must be provided is the capsule which contains a PyCapsule to a struct pointer of type bitgen_t,
which provides 5 pointers. The first is an opaque pointer to the data structure used by the BitGenerators. The next three are function pointers which return the next 64- and 32-bit unsigned integers, the next random double and the next raw value. This final function is used for testing and so can be set to the next 64-bit unsigned integer function if not needed. Functions inside Generator use this structure as in


Compute the one-dimensional discrete Fourier Transform.
This function computes the one-dimensional n-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT].
Input array, can be complex.
Length of the transformed axis of the output. If n is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If n is not given, the length of the input along the axis specified by axis is used.
Axis over which to compute the FFT. If not given, the last axis is used.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified.
If axis is not a valid axis of a.
See also
for definition of the DFT and conventions used.
The inverse of fft.
The two-dimensional FFT.
The n-dimensional FFT.
The n-dimensional FFT of real input.
Frequency bins for given FFT parameters.
FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently, by using symmetries in the calculated terms. The symmetry is highest when n is a power of 2, and the transform is therefore most efficient for these sizes.
The DFT is defined, with the conventions used in this implementation, in the documentation for the numpy.fft module.
Cooley, James W., and John W. Tukey, 1965, “An algorithm for the machine calculation of complex Fourier series,” Math. Comput. 19: 297-301.
In this example, real input has an FFT which is Hermitian, i.e., symmetric in the real part and anti-symmetric in the imaginary part, as described in the numpy.fft documentation:


Compute the 2-dimensional discrete Fourier Transform.
This function computes the n-dimensional discrete Fourier Transform over any axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). By default, the transform is computed over the last two axes of the input array, i.e., a 2-dimensional FFT.
Input array, can be complex
Shape (length of each transformed axis) of the output (s[0] refers to axis 0, s[1] to axis 1, etc.). This corresponds to n for fft(x, n). Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if s is not given, the shape of the input along the axes specified by axes is used.
Axes over which to compute the FFT. If not given, the last two axes are used. A repeated index in axes means the transform over that axis is performed multiple times. A one-element sequence means that a one-dimensional FFT is performed.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axes indicated by axes, or the last two axes if axes is not given.
If s and axes have different length, or axes not given and len(s) != 2.
If an element of axes is larger than than the number of axes of a.
See also
Overall view of discrete Fourier transforms, with definitions and conventions used.
The inverse two-dimensional FFT.
The one-dimensional FFT.
The n-dimensional FFT.
Shifts zero-frequency terms to the center of the array. For two-dimensional input, swaps first and third quadrants, and second and fourth quadrants.
fft2 is just fftn with a different default for axes.
The output, analogously to fft, contains the term for zero frequency in the low-order corner of the transformed axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in the second half of the axes, in order of decreasingly negative frequency.
See fftn for details and a plotting example, and numpy.fft for definitions and conventions used.


Return the Discrete Fourier Transform sample frequencies.
The returned float array f contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second.
Given a window length n and a sample spacing d:
Window length.
Sample spacing (inverse of the sampling rate). Defaults to 1.
Array of length n containing the sample frequencies.


Compute the N-dimensional discrete Fourier Transform.
This function computes the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT).
Input array, can be complex.
Shape (length of each transformed axis) of the output (s[0] refers to axis 0, s[1] to axis 1, etc.). This corresponds to n for fft(x, n). Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if s is not given, the shape of the input along the axes specified by axes is used.
Axes over which to compute the FFT. If not given, the last len(s) axes are used, or all axes if s is also not specified. Repeated indices in axes means that the transform over that axis is performed multiple times.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axes indicated by axes, or by a combination of s and a, as explained in the parameters section above.
If s and axes have different length.
If an element of axes is larger than than the number of axes of a.
See also
Overall view of discrete Fourier transforms, with definitions and conventions used.
The inverse of fftn, the inverse n-dimensional FFT.
The one-dimensional FFT, with definitions and conventions used.
The n-dimensional FFT of real input.
The two-dimensional FFT.
Shifts zero-frequency terms to centre of array
The output, analogously to fft, contains the term for zero frequency in the low-order corner of all axes, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency.
See numpy.fft for details, definitions and conventions used.


Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all). Note that y[0] is the Nyquist component only if len(x) is even.
Input array.
Axes over which to shift. Default is None, which shifts all axes.
The shifted array.
See also
The inverse of fftshift.
Shift the zero-frequency component only along the second axis:


Compute the FFT of a signal that has Hermitian symmetry, i.e., a real spectrum.
The input array.
Length of the transformed axis of the output. For n output points, n//2 + 1 input points are necessary. If the input is longer than this, it is cropped. If it is shorter than this, it is padded with zeros. If n is not given, it is taken to be 2*(m-1) where m is the length of the input along the axis specified by axis.
Axis over which to compute the FFT. If not given, the last axis is used.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified. The length of the transformed axis is n, or, if n is not given, 2*m - 2 where m is the length of the transformed axis of the input. To get an odd number of output points, n must be specified, for instance as 2*m - 1 in the typical case,
If axis is not a valid axis of a.
See also
Compute the one-dimensional FFT for real input.
The inverse of hfft.
hfft/ihfft are a pair analogous to rfft/irfft, but for the opposite case: here the signal has Hermitian symmetry in the time domain and is real in the frequency domain. So here it’s hfft for which you must supply the length of the result if it is to be odd.
The correct interpretation of the hermitian input depends on the length of the original data, as given by n. This is because each input shape could correspond to either an odd or even length signal. By default, hfft assumes an even output length which puts the last entry at the Nyquist frequency; aliasing with its symmetric counterpart. By Hermitian symmetry, the value is thus treated as purely real. To avoid losing information, the shape of the full signal must be given.


Compute the one-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the one-dimensional n-point discrete Fourier transform computed by fft. In other words, ifft(fft(a)) == a to within numerical accuracy. For a general description of the algorithm and definitions, see numpy.fft.
The input should be ordered in the same way as is returned by fft, i.e.,
For an even number of input points, A[n//2] represents the sum of the values at the positive and negative Nyquist frequencies, as the two are aliased together. See numpy.fft for details.
Input array, can be complex.
Length of the transformed axis of the output. If n is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If n is not given, the length of the input along the axis specified by axis is used. See notes about padding issues.
Axis over which to compute the inverse DFT. If not given, the last axis is used.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified.
If axis is not a valid axis of a.
See also
An introduction, with definitions and general explanations.
The one-dimensional (forward) FFT, of which ifft is the inverse
The two-dimensional inverse FFT.
The n-dimensional inverse FFT.
If the input parameter n is larger than the size of the input, the input is padded by appending zeros at the end. Even though this is the common approach, it might lead to surprising results. If a different padding is desired, it must be performed before calling ifft.
Create and plot a band-limited signal with random phases:


Compute the 2-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the 2-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ifft2(fft2(a)) == a to within numerical accuracy. By default, the inverse transform is computed over the last two axes of the input array.
The input, analogously to ifft, should be ordered in the same way as is returned by fft2, i.e. it should have the term for zero frequency in the low-order corner of the two axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in the second half of both axes, in order of decreasingly negative frequency.
Input array, can be complex.
Shape (length of each axis) of the output (s[0] refers to axis 0, s[1] to axis 1, etc.). This corresponds to n for ifft(x, n). Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if s is not given, the shape of the input along the axes specified by axes is used. See notes for issue on ifft zero padding.
Axes over which to compute the FFT. If not given, the last two axes are used. A repeated index in axes means the transform over that axis is performed multiple times. A one-element sequence means that a one-dimensional FFT is performed.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axes indicated by axes, or the last two axes if axes is not given.
If s and axes have different length, or axes not given and len(s) != 2.
If an element of axes is larger than than the number of axes of a.
See also
Overall view of discrete Fourier transforms, with definitions and conventions used.
The forward 2-dimensional FFT, of which ifft2 is the inverse.
The inverse of the n-dimensional FFT.
The one-dimensional FFT.
The one-dimensional inverse FFT.
ifft2 is just ifftn with a different default for axes.
See ifftn for details and a plotting example, and numpy.fft for definition and conventions used.
Zero-padding, analogously with ifft, is performed by appending zeros to the input along the specified dimension. Although this is the common approach, it might lead to surprising results. If another form of zero padding is desired, it must be performed before ifft2 is called.


Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ifftn(fftn(a)) == a to within numerical accuracy. For a description of the definitions and conventions used, see numpy.fft.
The input, analogously to ifft, should be ordered in the same way as is returned by fftn, i.e. it should have the term for zero frequency in all axes in the low-order corner, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency.
Input array, can be complex.
Shape (length of each transformed axis) of the output (s[0] refers to axis 0, s[1] to axis 1, etc.). This corresponds to n for ifft(x, n). Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if s is not given, the shape of the input along the axes specified by axes is used. See notes for issue on ifft zero padding.
Axes over which to compute the IFFT. If not given, the last len(s) axes are used, or all axes if s is also not specified. Repeated indices in axes means that the inverse transform over that axis is performed multiple times.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axes indicated by axes, or by a combination of s or a, as explained in the parameters section above.
If s and axes have different length.
If an element of axes is larger than than the number of axes of a.
See also
Overall view of discrete Fourier transforms, with definitions and conventions used.
The forward n-dimensional FFT, of which ifftn is the inverse.
The one-dimensional inverse FFT.
The two-dimensional inverse FFT.
Undoes fftshift, shifts zero-frequency terms to beginning of array.
See numpy.fft for definitions and conventions used.
Zero-padding, analogously with ifft, is performed by appending zeros to the input along the specified dimension. Although this is the common approach, it might lead to surprising results. If another form of zero padding is desired, it must be performed before ifftn is called.
Create and plot an image with band-limited frequency content:


The inverse of fftshift. Although identical for even-length x, the functions differ by one sample for odd-length x.
Input array.
Axes over which to calculate. Defaults to None, which shifts all axes.
The shifted array.
See also
Shift zero-frequency component to the center of the spectrum.


Compute the inverse FFT of a signal that has Hermitian symmetry.
Input array.
Length of the inverse FFT, the number of points along transformation axis in the input to use. If n is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If n is not given, the length of the input along the axis specified by axis is used.
Axis over which to compute the inverse FFT. If not given, the last axis is used.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified. The length of the transformed axis is n//2 + 1.
See also
hfft/ihfft are a pair analogous to rfft/irfft, but for the opposite case: here the signal has Hermitian symmetry in the time domain and is real in the frequency domain. So here it’s hfft for which you must supply the length of the result if it is to be odd:


Computes the inverse of rfft.
This function computes the inverse of the one-dimensional n-point discrete Fourier Transform of real input computed by rfft. In other words, irfft(rfft(a), len(a)) == a to within numerical accuracy. (See Notes below for why len(a) is necessary here.)
The input is expected to be in the form returned by rfft, i.e. the real zero-frequency term followed by the complex positive frequency terms in order of increasing frequency. Since the discrete Fourier Transform of real input is Hermitian-symmetric, the negative frequency terms are taken to be the complex conjugates of the corresponding positive frequency terms.
The input array.
Length of the transformed axis of the output. For n output points, n//2+1 input points are necessary. If the input is longer than this, it is cropped. If it is shorter than this, it is padded with zeros. If n is not given, it is taken to be 2*(m-1) where m is the length of the input along the axis specified by axis.
Axis over which to compute the inverse FFT. If not given, the last axis is used.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified. The length of the transformed axis is n, or, if n is not given, 2*(m-1) where m is the length of the transformed axis of the input. To get an odd number of output points, n must be specified.
If axis is not a valid axis of a.
See also
For definition of the DFT and conventions used.
The one-dimensional FFT of real input, of which irfft is inverse.
The one-dimensional FFT.
The inverse of the two-dimensional FFT of real input.
The inverse of the n-dimensional FFT of real input.
Returns the real valued n-point inverse discrete Fourier transform of a, where a contains the non-negative frequency terms of a Hermitian-symmetric sequence. n is the length of the result, not the input.
If you specify an n such that a must be zero-padded or truncated, the extra/removed values will be added/removed at high frequencies. One can thus resample a series to m points via Fourier interpolation by: a_resamp = irfft(rfft(a), m).
The correct interpretation of the hermitian input depends on the length of the original data, as given by n. This is because each input shape could correspond to either an odd or even length signal. By default, irfft assumes an even output length which puts the last entry at the Nyquist frequency; aliasing with its symmetric counterpart. By Hermitian symmetry, the value is thus treated as purely real. To avoid losing information, the correct length of the real input must be given.
Notice how the last term in the input to the ordinary ifft is the complex conjugate of the second term, and the output has zero imaginary part everywhere. When calling irfft, the negative frequencies are not specified, and the output array is purely real.


Computes the inverse of rfft2.
The input array
Shape of the real output to the inverse FFT.
The axes over which to compute the inverse fft. Default is the last two axes.
New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
The result of the inverse real 2-D FFT.
See also
The forward two-dimensional FFT of real input, of which irfft2 is the inverse.
The one-dimensional FFT for real input.
The inverse of the one-dimensional FFT of real input.
Compute the inverse of the N-dimensional FFT of real input.
This is really irfftn with different defaults. For more details see irfftn.