Extending 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 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. import numpy as np
import numba as nb

from numpy.random import PCG64
from timeit import timeit

bit_gen = PCG64()
next_d = bit_gen.cffi.next_double
state_addr = bit_gen.cffi.state_address

def normals(n, state):
    out = np.empty(n)
    for i in range((n + 1) // 2):
        x1 = 2.0 * next_d(state) - 1.0
        x2 = 2.0 * next_d(state) - 1.0
        r2 = x1 * x1 + x2 * x2
        while r2 >= 1.0 or r2 == 0.0:
            x1 = 2.0 * next_d(state) - 1.0
            x2 = 2.0 * next_d(state) - 1.0
            r2 = x1 * x1 + x2 * x2
        f = np.sqrt(-2.0 * np.log(r2) / r2)
        out[2 * i] = f * x1
        if 2 * i + 1 < n:
            out[2 * i + 1] = f * x2
    return out

# Compile using Numba
normalsj = nb.jit(normals, nopython=True)
# Must use state address not state with numba
n = 10000

def numbacall():
    return normalsj(n, state_addr)

rg = np.random.Generator(PCG64())

def numpycall():
    return rg.normal(size=n)

# Check that the functions work
r1 = numbacall()
r2 = numpycall()
assert r1.shape == (n,)
assert r1.shape == r2.shape

t1 = timeit(numbacall, number=1000)
print(f'{t1:.2f} secs for {n} PCG64 (Numba/PCG64) gaussian randoms')
t2 = timeit(numpycall, number=1000)
print(f'{t2:.2f} secs for {n} PCG64 (NumPy/PCG64) gaussian randoms')

 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 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. #!/usr/bin/env python3
#cython: language_level=3
"""
This file shows how the to use a BitGenerator to create a distribution.
"""
import numpy as np
cimport numpy as np
cimport cython
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer
from libc.stdint cimport uint16_t, uint64_t
from numpy.random cimport bitgen_t
from numpy.random import PCG64
from numpy.random.c_distributions cimport (
      random_standard_uniform_fill, random_standard_uniform_fill_f)

@cython.boundscheck(False)
@cython.wraparound(False)
def uniforms(Py_ssize_t n):
    """
    Create an array of `n` uniformly distributed doubles.
    A 'real' distribution would want to process the values into
    some non-uniform distribution
    """
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef const char *capsule_name = "BitGenerator"
    cdef double[::1] random_values

    x = PCG64()
    capsule = x.capsule
    # Optional check that the capsule if from a BitGenerator
    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    # Cast the pointer
    rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
    random_values = np.empty(n, dtype='float64')
    with x.lock, nogil:
        for i in range(n):
            # Call the function
            random_values[i] = rng.next_double(rng.state)
    randoms = np.asarray(random_values)

    return randoms
 The BitGenerator can also be directly accessed using the members of the bitgen_t struct. @cython.boundscheck(False)
@cython.wraparound(False)
def uint10_uniforms(Py_ssize_t n):
    """Uniform 10 bit integers stored as 16-bit unsigned integers"""
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef const char *capsule_name = "BitGenerator"
    cdef uint16_t[::1] random_values
    cdef int bits_remaining
    cdef int width = 10
    cdef uint64_t buff, mask = 0x3FF

    x = PCG64()
    capsule = x.capsule
    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
    random_values = np.empty(n, dtype='uint16')
    # Best practice is to release GIL and acquire the lock
    bits_remaining = 0
    with x.lock, nogil:
        for i in range(n):
            if bits_remaining < width:
                buff = rng.next_uint64(rng.state)
            random_values[i] = buff & mask
            buff >>= width

    randoms = np.asarray(random_values)
    return randoms
 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. def uniforms_ex(bit_generator, Py_ssize_t n, dtype=np.float64):
    """
    Create an array of `n` uniformly distributed doubles via a "fill" function.

    A 'real' distribution would want to process the values into
    some non-uniform distribution

    Parameters
    ----------
    bit_generator: BitGenerator instance
    n: int
        Output vector length
    dtype: {str, dtype}, optional
        Desired dtype, either 'd' (or 'float64') or 'f' (or 'float32'). The
        default dtype value is 'd'
    """
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef const char *capsule_name = "BitGenerator"
    cdef np.ndarray randoms

    capsule = bit_generator.capsule
    # Optional check that the capsule if from a BitGenerator
    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    # Cast the pointer
    rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)

    _dtype = np.dtype(dtype)
    randoms = np.empty(n, dtype=_dtype)
    if _dtype == np.float32:
        with bit_generator.lock:
            random_standard_uniform_fill_f(rng, n, <float*>np.PyArray_DATA(randoms))
    elif _dtype == np.float64:
        with bit_generator.lock:
            random_standard_uniform_fill(rng, n, <double*>np.PyArray_DATA(randoms))
    else:
        raise TypeError('Unsupported dtype %r for random' % _dtype)
    return randoms
 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 CFFI can be used to directly access the functions in include/numpy/random/distributions.h. Some “massaging” of the header file is required: """
Use cffi to access any of the underlying C functions from distributions.h
"""
import os
import numpy as np
import cffi
from .parse import parse_distributions_h
ffi = cffi.FFI()

inc_dir = os.path.join(np.get_include(), 'numpy')

# Basic numpy types
ffi.cdef('''
    typedef intptr_t npy_intp;
    typedef unsigned char npy_bool;

''')

parse_distributions_h(ffi, inc_dir)

 Once the header is parsed by ffi.cdef, the functions can be accessed directly from the _generator shared object, using the BitGenerator.cffi interface.
# Compare the distributions.h random_standard_normal_fill to
# Generator.standard_random
bit_gen = np.random.PCG64()
rng = np.random.Generator(bit_gen)
state = bit_gen.state

interface = rng.bit_generator.cffi
n = 100
vals_cffi = ffi.new('double[%d]' % n)
lib.random_standard_normal_fill(interface.bit_generator, n, vals_cffi)

# reset the state
bit_gen.state = state

vals = rng.standard_normal(n)

for i in range(n):
    assert vals[i] == vals_cffi[i]
   New Bit Generators 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, typedef struct bitgen {
  void *state;
  uint64_t (*next_uint64)(void *st);
  uint32_t (*next_uint32)(void *st);
  double (*next_double)(void *st);
  uint64_t (*next_raw)(void *st);
} 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 bitgen_state->next_uint64(bitgen_state->state)
   Examples  Numba CFFI + Numba
Cython setup.py extending.pyx extending_distributions.pyx   CFFI


extending.pyx #!/usr/bin/env python3
#cython: language_level=3

from libc.stdint cimport uint32_t
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer

import numpy as np
cimport numpy as np
cimport cython

from numpy.random cimport bitgen_t
from numpy.random import PCG64

np.import_array()

@cython.boundscheck(False)
@cython.wraparound(False)
def uniform_mean(Py_ssize_t n):
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef const char *capsule_name = "BitGenerator"
    cdef double[::1] random_values
    cdef np.ndarray randoms

    x = PCG64()
    capsule = x.capsule
    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
    random_values = np.empty(n)
    # Best practice is to acquire the lock whenever generating random values.
    # This prevents other threads from modifying the state. Acquiring the lock
    # is only necessary if if the GIL is also released, as in this example.
    with x.lock, nogil:
        for i in range(n):
            random_values[i] = rng.next_double(rng.state)
    randoms = np.asarray(random_values)
    return randoms.mean()

# This function is declared nogil so it can be used without the GIL below
cdef uint32_t bounded_uint(uint32_t lb, uint32_t ub, bitgen_t *rng) nogil:
    cdef uint32_t mask, delta, val
    mask = delta = ub - lb
    mask |= mask >> 1
    mask |= mask >> 2
    mask |= mask >> 4
    mask |= mask >> 8
    mask |= mask >> 16

    val = rng.next_uint32(rng.state) & mask
    while val > delta:
        val = rng.next_uint32(rng.state) & mask

    return lb + val

@cython.boundscheck(False)
@cython.wraparound(False)
def bounded_uints(uint32_t lb, uint32_t ub, Py_ssize_t n):
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef uint32_t[::1] out
    cdef const char *capsule_name = "BitGenerator"

    x = PCG64()
    out = np.empty(n, dtype=np.uint32)
    capsule = x.capsule

    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    rng = <bitgen_t *>PyCapsule_GetPointer(capsule, capsule_name)

    with x.lock, nogil:
        for i in range(n):
            out[i] = bounded_uint(lb, ub, rng)
    return np.asarray(out)


extending_distributions.pyx #!/usr/bin/env python3
#cython: language_level=3
"""
This file shows how the to use a BitGenerator to create a distribution.
"""
import numpy as np
cimport numpy as np
cimport cython
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer
from libc.stdint cimport uint16_t, uint64_t
from numpy.random cimport bitgen_t
from numpy.random import PCG64
from numpy.random.c_distributions cimport (
      random_standard_uniform_fill, random_standard_uniform_fill_f)

@cython.boundscheck(False)
@cython.wraparound(False)
def uniforms(Py_ssize_t n):
    """
    Create an array of `n` uniformly distributed doubles.
    A 'real' distribution would want to process the values into
    some non-uniform distribution
    """
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef const char *capsule_name = "BitGenerator"
    cdef double[::1] random_values

    x = PCG64()
    capsule = x.capsule
    # Optional check that the capsule if from a BitGenerator
    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    # Cast the pointer
    rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
    random_values = np.empty(n, dtype='float64')
    with x.lock, nogil:
        for i in range(n):
            # Call the function
            random_values[i] = rng.next_double(rng.state)
    randoms = np.asarray(random_values)

    return randoms

# cython example 2
@cython.boundscheck(False)
@cython.wraparound(False)
def uint10_uniforms(Py_ssize_t n):
    """Uniform 10 bit integers stored as 16-bit unsigned integers"""
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef const char *capsule_name = "BitGenerator"
    cdef uint16_t[::1] random_values
    cdef int bits_remaining
    cdef int width = 10
    cdef uint64_t buff, mask = 0x3FF

    x = PCG64()
    capsule = x.capsule
    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
    random_values = np.empty(n, dtype='uint16')
    # Best practice is to release GIL and acquire the lock
    bits_remaining = 0
    with x.lock, nogil:
        for i in range(n):
            if bits_remaining < width:
                buff = rng.next_uint64(rng.state)
            random_values[i] = buff & mask
            buff >>= width

    randoms = np.asarray(random_values)
    return randoms

# cython example 3
def uniforms_ex(bit_generator, Py_ssize_t n, dtype=np.float64):
    """
    Create an array of `n` uniformly distributed doubles via a "fill" function.

    A 'real' distribution would want to process the values into
    some non-uniform distribution

    Parameters
    ----------
    bit_generator: BitGenerator instance
    n: int
        Output vector length
    dtype: {str, dtype}, optional
        Desired dtype, either 'd' (or 'float64') or 'f' (or 'float32'). The
        default dtype value is 'd'
    """
    cdef Py_ssize_t i
    cdef bitgen_t *rng
    cdef const char *capsule_name = "BitGenerator"
    cdef np.ndarray randoms

    capsule = bit_generator.capsule
    # Optional check that the capsule if from a BitGenerator
    if not PyCapsule_IsValid(capsule, capsule_name):
        raise ValueError("Invalid pointer to anon_func_state")
    # Cast the pointer
    rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)

    _dtype = np.dtype(dtype)
    randoms = np.empty(n, dtype=_dtype)
    if _dtype == np.float32:
        with bit_generator.lock:
            random_standard_uniform_fill_f(rng, n, <float*>np.PyArray_DATA(randoms))
    elif _dtype == np.float64:
        with bit_generator.lock:
            random_standard_uniform_fill(rng, n, <double*>np.PyArray_DATA(randoms))
    else:
        raise TypeError('Unsupported dtype %r for random' % _dtype)
    return randoms


numpy.fft.fft   fft.fft(a, n=None, axis=- 1, norm=None)[source]

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].  Parameters

aarray_like

Input array, can be complex.
nint, optional

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.
axisint, optional

Axis over which to compute the FFT. If not given, the last axis is used.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified.    Raises
 IndexError

If axis is not a valid axis of a.      See also  numpy.fft

for definition of the DFT and conventions used.  ifft

The inverse of fft.  fft2

The two-dimensional FFT.  fftn

The n-dimensional FFT.  rfftn

The n-dimensional FFT of real input.  fftfreq

Frequency bins for given FFT parameters.    Notes 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. References  CT
Cooley, James W., and John W. Tukey, 1965, “An algorithm for the machine calculation of complex Fourier series,” Math. Comput. 19: 297-301.   Examples >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
array([-2.33486982e-16+1.14423775e-17j,  8.00000000e+00-1.25557246e-15j,
        2.33486982e-16+2.33486982e-16j,  0.00000000e+00+1.22464680e-16j,
       -1.14423775e-17+2.33486982e-16j,  0.00000000e+00+5.20784380e-16j,
        1.14423775e-17+1.14423775e-17j,  0.00000000e+00+1.22464680e-16j])
 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: >>> import matplotlib.pyplot as plt
>>> t = np.arange(256)
>>> sp = np.fft.fft(np.sin(t))
>>> freq = np.fft.fftfreq(t.shape[-1])
>>> plt.plot(freq, sp.real, freq, sp.imag)
[<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
>>> plt.show()


numpy.fft.fft2   fft.fft2(a, s=None, axes=(- 2, - 1), norm=None)[source]

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.  Parameters

aarray_like

Input array, can be complex
ssequence of ints, optional

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.
axessequence of ints, optional

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.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

The truncated or zero-padded input, transformed along the axes indicated by axes, or the last two axes if axes is not given.    Raises
 ValueError

If s and axes have different length, or axes not given and len(s) != 2.  IndexError

If an element of axes is larger than than the number of axes of a.      See also  numpy.fft

Overall view of discrete Fourier transforms, with definitions and conventions used.  ifft2

The inverse two-dimensional FFT.  fft

The one-dimensional FFT.  fftn

The n-dimensional FFT.  fftshift

Shifts zero-frequency terms to the center of the array. For two-dimensional input, swaps first and third quadrants, and second and fourth quadrants.    Notes 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. Examples >>> a = np.mgrid[:5, :5][0]
>>> np.fft.fft2(a)
array([[ 50.  +0.j        ,   0.  +0.j        ,   0.  +0.j        , # may vary
          0.  +0.j        ,   0.  +0.j        ],
       [-12.5+17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
          0.  +0.j        ,   0.  +0.j        ],
       [-12.5 +4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
          0.  +0.j        ,   0.  +0.j        ],
       [-12.5 -4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
          0.  +0.j        ,   0.  +0.j        ],
       [-12.5-17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
          0.  +0.j        ,   0.  +0.j        ]])


numpy.fft.fftfreq   fft.fftfreq(n, d=1.0)[source]

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: f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd
  Parameters

nint

Window length.
dscalar, optional

Sample spacing (inverse of the sampling rate). Defaults to 1.    Returns

fndarray

Array of length n containing the sample frequencies.     Examples >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
>>> fourier = np.fft.fft(signal)
>>> n = signal.size
>>> timestep = 0.1
>>> freq = np.fft.fftfreq(n, d=timestep)
>>> freq
array([ 0.  ,  1.25,  2.5 , ..., -3.75, -2.5 , -1.25])


numpy.fft.fftn   fft.fftn(a, s=None, axes=None, norm=None)[source]

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).  Parameters

aarray_like

Input array, can be complex.
ssequence of ints, optional

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.
axessequence of ints, optional

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.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

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.    Raises
 ValueError

If s and axes have different length.  IndexError

If an element of axes is larger than than the number of axes of a.      See also  numpy.fft

Overall view of discrete Fourier transforms, with definitions and conventions used.  ifftn

The inverse of fftn, the inverse n-dimensional FFT.  fft

The one-dimensional FFT, with definitions and conventions used.  rfftn

The n-dimensional FFT of real input.  fft2

The two-dimensional FFT.  fftshift

Shifts zero-frequency terms to centre of array    Notes 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. Examples >>> a = np.mgrid[:3, :3, :3][0]
>>> np.fft.fftn(a, axes=(1, 2))
array([[[ 0.+0.j,   0.+0.j,   0.+0.j], # may vary
        [ 0.+0.j,   0.+0.j,   0.+0.j],
        [ 0.+0.j,   0.+0.j,   0.+0.j]],
       [[ 9.+0.j,   0.+0.j,   0.+0.j],
        [ 0.+0.j,   0.+0.j,   0.+0.j],
        [ 0.+0.j,   0.+0.j,   0.+0.j]],
       [[18.+0.j,   0.+0.j,   0.+0.j],
        [ 0.+0.j,   0.+0.j,   0.+0.j],
        [ 0.+0.j,   0.+0.j,   0.+0.j]]])
>>> np.fft.fftn(a, (2, 2), axes=(0, 1))
array([[[ 2.+0.j,  2.+0.j,  2.+0.j], # may vary
        [ 0.+0.j,  0.+0.j,  0.+0.j]],
       [[-2.+0.j, -2.+0.j, -2.+0.j],
        [ 0.+0.j,  0.+0.j,  0.+0.j]]])
 >>> import matplotlib.pyplot as plt
>>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
...                      2 * np.pi * np.arange(200) / 34)
>>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape)
>>> FS = np.fft.fftn(S)
>>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2))
<matplotlib.image.AxesImage object at 0x...>
>>> plt.show()


numpy.fft.fftshift   fft.fftshift(x, axes=None)[source]

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.  Parameters

xarray_like

Input array.
axesint or shape tuple, optional

Axes over which to shift. Default is None, which shifts all axes.    Returns

yndarray

The shifted array.      See also  ifftshift

The inverse of fftshift.    Examples >>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0.,  1.,  2., ..., -3., -2., -1.])
>>> np.fft.fftshift(freqs)
array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
 Shift the zero-frequency component only along the second axis: >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])
>>> np.fft.fftshift(freqs, axes=(1,))
array([[ 2.,  0.,  1.],
       [-4.,  3.,  4.],
       [-1., -3., -2.]])


numpy.fft.hfft   fft.hfft(a, n=None, axis=- 1, norm=None)[source]

Compute the FFT of a signal that has Hermitian symmetry, i.e., a real spectrum.  Parameters

aarray_like

The input array.
nint, optional

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.
axisint, optional

Axis over which to compute the FFT. If not given, the last axis is used.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outndarray

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,    Raises
 IndexError

If axis is not a valid axis of a.      See also  rfft

Compute the one-dimensional FFT for real input.  ihfft

The inverse of hfft.    Notes 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.  even: ihfft(hfft(a, 2*len(a) - 2)) == a, within roundoff error, odd: ihfft(hfft(a, 2*len(a) - 1)) == a, within roundoff error.  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. Examples >>> signal = np.array([1, 2, 3, 4, 3, 2])
>>> np.fft.fft(signal)
array([15.+0.j,  -4.+0.j,   0.+0.j,  -1.-0.j,   0.+0.j,  -4.+0.j]) # may vary
>>> np.fft.hfft(signal[:4]) # Input first half of signal
array([15.,  -4.,   0.,  -1.,   0.,  -4.])
>>> np.fft.hfft(signal, 6)  # Input entire signal and truncate
array([15.,  -4.,   0.,  -1.,   0.,  -4.])
 >>> signal = np.array([[1, 1.j], [-1.j, 2]])
>>> np.conj(signal.T) - signal   # check Hermitian symmetry
array([[ 0.-0.j,  -0.+0.j], # may vary
       [ 0.+0.j,  0.-0.j]])
>>> freq_spectrum = np.fft.hfft(signal)
>>> freq_spectrum
array([[ 1.,  1.],
       [ 2., -2.]])


numpy.fft.ifft   fft.ifft(a, n=None, axis=- 1, norm=None)[source]

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.,
a[0] should contain the zero frequency term,
a[1:n//2] should contain the positive-frequency terms,
a[n//2 + 1:] should contain the negative-frequency terms, in increasing order starting from the most negative frequency.  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.  Parameters

aarray_like

Input array, can be complex.
nint, optional

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.
axisint, optional

Axis over which to compute the inverse DFT. If not given, the last axis is used.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified.    Raises
 IndexError

If axis is not a valid axis of a.      See also  numpy.fft

An introduction, with definitions and general explanations.  fft

The one-dimensional (forward) FFT, of which ifft is the inverse  ifft2

The two-dimensional inverse FFT.  ifftn

The n-dimensional inverse FFT.    Notes 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. Examples >>> np.fft.ifft([0, 4, 0, 0])
array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j]) # may vary
 Create and plot a band-limited signal with random phases: >>> import matplotlib.pyplot as plt
>>> t = np.arange(400)
>>> n = np.zeros((400,), dtype=complex)
>>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))
>>> s = np.fft.ifft(n)
>>> plt.plot(t, s.real, label='real')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(t, s.imag, '--', label='imaginary')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.legend()
<matplotlib.legend.Legend object at ...>
>>> plt.show()


numpy.fft.ifft2   fft.ifft2(a, s=None, axes=(- 2, - 1), norm=None)[source]

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.  Parameters

aarray_like

Input array, can be complex.
ssequence of ints, optional

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.
axessequence of ints, optional

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.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

The truncated or zero-padded input, transformed along the axes indicated by axes, or the last two axes if axes is not given.    Raises
 ValueError

If s and axes have different length, or axes not given and len(s) != 2.  IndexError

If an element of axes is larger than than the number of axes of a.      See also  numpy.fft

Overall view of discrete Fourier transforms, with definitions and conventions used.  fft2

The forward 2-dimensional FFT, of which ifft2 is the inverse.  ifftn

The inverse of the n-dimensional FFT.  fft

The one-dimensional FFT.  ifft

The one-dimensional inverse FFT.    Notes 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. Examples >>> a = 4 * np.eye(4)
>>> np.fft.ifft2(a)
array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
       [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j],
       [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
       [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])


numpy.fft.ifftn   fft.ifftn(a, s=None, axes=None, norm=None)[source]

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.  Parameters

aarray_like

Input array, can be complex.
ssequence of ints, optional

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.
axessequence of ints, optional

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.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

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.    Raises
 ValueError

If s and axes have different length.  IndexError

If an element of axes is larger than than the number of axes of a.      See also  numpy.fft

Overall view of discrete Fourier transforms, with definitions and conventions used.  fftn

The forward n-dimensional FFT, of which ifftn is the inverse.  ifft

The one-dimensional inverse FFT.  ifft2

The two-dimensional inverse FFT.  ifftshift

Undoes fftshift, shifts zero-frequency terms to beginning of array.    Notes 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. Examples >>> a = np.eye(4)
>>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))
array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
       [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
       [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
       [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j]])
 Create and plot an image with band-limited frequency content: >>> import matplotlib.pyplot as plt
>>> n = np.zeros((200,200), dtype=complex)
>>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20)))
>>> im = np.fft.ifftn(n).real
>>> plt.imshow(im)
<matplotlib.image.AxesImage object at 0x...>
>>> plt.show()


numpy.fft.ifftshift   fft.ifftshift(x, axes=None)[source]

The inverse of fftshift. Although identical for even-length x, the functions differ by one sample for odd-length x.  Parameters

xarray_like

Input array.
axesint or shape tuple, optional

Axes over which to calculate. Defaults to None, which shifts all axes.    Returns

yndarray

The shifted array.      See also  fftshift

Shift zero-frequency component to the center of the spectrum.    Examples >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])
>>> np.fft.ifftshift(np.fft.fftshift(freqs))
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])


numpy.fft.ihfft   fft.ihfft(a, n=None, axis=- 1, norm=None)[source]

Compute the inverse FFT of a signal that has Hermitian symmetry.  Parameters

aarray_like

Input array.
nint, optional

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.
axisint, optional

Axis over which to compute the inverse FFT. If not given, the last axis is used.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

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, irfft

  Notes 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:  even: ihfft(hfft(a, 2*len(a) - 2)) == a, within roundoff error, odd: ihfft(hfft(a, 2*len(a) - 1)) == a, within roundoff error.  Examples >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
>>> np.fft.ifft(spectrum)
array([1.+0.j,  2.+0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.+0.j]) # may vary
>>> np.fft.ihfft(spectrum)
array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j]) # may vary


numpy.fft.irfft   fft.irfft(a, n=None, axis=- 1, norm=None)[source]

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.  Parameters

aarray_like

The input array.
nint, optional

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.
axisint, optional

Axis over which to compute the inverse FFT. If not given, the last axis is used.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outndarray

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.    Raises
 IndexError

If axis is not a valid axis of a.      See also  numpy.fft

For definition of the DFT and conventions used.  rfft

The one-dimensional FFT of real input, of which irfft is inverse.  fft

The one-dimensional FFT.  irfft2

The inverse of the two-dimensional FFT of real input.  irfftn

The inverse of the n-dimensional FFT of real input.    Notes 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. Examples >>> np.fft.ifft([1, -1j, -1, 1j])
array([0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]) # may vary
>>> np.fft.irfft([1, -1j, -1])
array([0.,  1.,  0.,  0.])
 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.


numpy.fft.irfft2   fft.irfft2(a, s=None, axes=(- 2, - 1), norm=None)[source]

Computes the inverse of rfft2.  Parameters

aarray_like

The input array
ssequence of ints, optional

Shape of the real output to the inverse FFT.
axessequence of ints, optional

The axes over which to compute the inverse fft. Default is the last two axes.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outndarray

The result of the inverse real 2-D FFT.      See also  rfft2

The forward two-dimensional FFT of real input, of which irfft2 is the inverse.  rfft

The one-dimensional FFT for real input.  irfft

The inverse of the one-dimensional FFT of real input.  irfftn

Compute the inverse of the N-dimensional FFT of real input.    Notes This is really irfftn with different defaults. For more details see irfftn. Examples >>> a = np.mgrid[:5, :5][0]
>>> A = np.fft.rfft2(a)
>>> np.fft.irfft2(A, s=a.shape)
array([[0., 0., 0., 0., 0.],
       [1., 1., 1., 1., 1.],
       [2., 2., 2., 2., 2.],
       [3., 3., 3., 3., 3.],
       [4., 4., 4., 4., 4.]])


numpy.fft.irfftn   fft.irfftn(a, s=None, axes=None, norm=None)[source]

Computes the inverse of rfftn. This function computes the inverse of the N-dimensional discrete Fourier Transform for real input over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, irfftn(rfftn(a), a.shape) == a to within numerical accuracy. (The a.shape is necessary like len(a) is for irfft, and for the same reason.) The input should be ordered in the same way as is returned by rfftn, i.e. as for irfft for the final transformation axis, and as for ifftn along all the other axes.  Parameters

aarray_like

Input array.
ssequence of ints, optional

Shape (length of each transformed axis) of the output (s[0] refers to axis 0, s[1] to axis 1, etc.). s is also the number of input points used along this axis, except for the last axis, where s[-1]//2+1 points of the input are used. Along any axis, if the shape indicated by s 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. Except for the last axis which is taken to be 2*(m-1) where m is the length of the input along that axis.
axessequence of ints, optional

Axes over which to compute the inverse 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 inverse transform over that axis is performed multiple times.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outndarray

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. The length of each transformed axis is as given by the corresponding element of s, or the length of the input in every axis except for the last one if s is not given. In the final transformed axis the length of the output when s is not given is 2*(m-1) where m is the length of the final transformed axis of the input. To get an odd number of output points in the final axis, s must be specified.    Raises
 ValueError

If s and axes have different length.  IndexError

If an element of axes is larger than than the number of axes of a.      See also  rfftn

The forward n-dimensional FFT of real input, of which ifftn is the inverse.  fft

The one-dimensional FFT, with definitions and conventions used.  irfft

The inverse of the one-dimensional FFT of real input.  irfft2

The inverse of the two-dimensional FFT of real input.    Notes See fft for definitions and conventions used. See rfft for definitions and conventions used for real input. The correct interpretation of the hermitian input depends on the shape of the original data, as given by s. This is because each input shape could correspond to either an odd or even length signal. By default, irfftn assumes an even output length which puts the last entry at the Nyquist frequency; aliasing with its symmetric counterpart. When performing the final complex to real transform, the last value is thus treated as purely real. To avoid losing information, the correct shape of the real input must be given. Examples >>> a = np.zeros((3, 2, 2))
>>> a[0, 0, 0] = 3 * 2 * 2
>>> np.fft.irfftn(a)
array([[[1.,  1.],
        [1.,  1.]],
       [[1.,  1.],
        [1.,  1.]],
       [[1.,  1.],
        [1.,  1.]]])


numpy.fft.rfft   fft.rfft(a, n=None, axis=- 1, norm=None)[source]

Compute the one-dimensional discrete Fourier Transform for real input. This function computes the one-dimensional n-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT).  Parameters

aarray_like

Input array
nint, optional

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.
axisint, optional

Axis over which to compute the FFT. If not given, the last axis is used.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified. If n is even, the length of the transformed axis is (n/2)+1. If n is odd, the length is (n+1)/2.    Raises
 IndexError

If axis is not a valid axis of a.      See also  numpy.fft

For definition of the DFT and conventions used.  irfft

The inverse of rfft.  fft

The one-dimensional FFT of general (complex) input.  fftn

The n-dimensional FFT.  rfftn

The n-dimensional FFT of real input.    Notes When the DFT is computed for purely real input, the output is Hermitian-symmetric, i.e. the negative frequency terms are just the complex conjugates of the corresponding positive-frequency terms, and the negative-frequency terms are therefore redundant. This function does not compute the negative frequency terms, and the length of the transformed axis of the output is therefore n//2 + 1. When A = rfft(a) and fs is the sampling frequency, A[0] contains the zero-frequency term 0*fs, which is real due to Hermitian symmetry. If n is even, A[-1] contains the term representing both positive and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely real. If n is odd, there is no term at fs/2; A[-1] contains the largest positive frequency (fs/2*(n-1)/n), and is complex in the general case. If the input a contains an imaginary part, it is silently discarded. Examples >>> np.fft.fft([0, 1, 0, 0])
array([ 1.+0.j,  0.-1.j, -1.+0.j,  0.+1.j]) # may vary
>>> np.fft.rfft([0, 1, 0, 0])
array([ 1.+0.j,  0.-1.j, -1.+0.j]) # may vary
 Notice how the final element of the fft output is the complex conjugate of the second element, for real input. For rfft, this symmetry is exploited to compute only the non-negative frequency terms.


numpy.fft.rfft2   fft.rfft2(a, s=None, axes=(- 2, - 1), norm=None)[source]

Compute the 2-dimensional FFT of a real array.  Parameters

aarray

Input array, taken to be real.
ssequence of ints, optional

Shape of the FFT.
axessequence of ints, optional

Axes over which to compute the FFT.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outndarray

The result of the real 2-D FFT.      See also  rfftn

Compute the N-dimensional discrete Fourier Transform for real input.    Notes This is really just rfftn with different default behavior. For more details see rfftn. Examples >>> a = np.mgrid[:5, :5][0]
>>> np.fft.rfft2(a)
array([[ 50.  +0.j        ,   0.  +0.j        ,   0.  +0.j        ],
       [-12.5+17.20477401j,   0.  +0.j        ,   0.  +0.j        ],
       [-12.5 +4.0614962j ,   0.  +0.j        ,   0.  +0.j        ],
       [-12.5 -4.0614962j ,   0.  +0.j        ,   0.  +0.j        ],
       [-12.5-17.20477401j,   0.  +0.j        ,   0.  +0.j        ]])


numpy.fft.rfftfreq   fft.rfftfreq(n, d=1.0)[source]

Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft). 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: f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd
 Unlike fftfreq (but like scipy.fftpack.rfftfreq) the Nyquist frequency component is considered to be positive.  Parameters

nint

Window length.
dscalar, optional

Sample spacing (inverse of the sampling rate). Defaults to 1.    Returns

fndarray

Array of length n//2 + 1 containing the sample frequencies.     Examples >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
>>> fourier = np.fft.rfft(signal)
>>> n = signal.size
>>> sample_rate = 100
>>> freq = np.fft.fftfreq(n, d=1./sample_rate)
>>> freq
array([  0.,  10.,  20., ..., -30., -20., -10.])
>>> freq = np.fft.rfftfreq(n, d=1./sample_rate)
>>> freq
array([  0.,  10.,  20.,  30.,  40.,  50.])


numpy.fft.rfftn   fft.rfftn(a, s=None, axes=None, norm=None)[source]

Compute the N-dimensional discrete Fourier Transform for real input. This function computes the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional real array by means of the Fast Fourier Transform (FFT). By default, all axes are transformed, with the real transform performed over the last axis, while the remaining transforms are complex.  Parameters

aarray_like

Input array, taken to be real.
ssequence of ints, optional

Shape (length along each transformed axis) to use from the input. (s[0] refers to axis 0, s[1] to axis 1, etc.). The final element of s corresponds to n for rfft(x, n), while for the remaining axes, it 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.
axessequence of ints, optional

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.
norm{“backward”, “ortho”, “forward”}, optional

 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.     Returns

outcomplex ndarray

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. The length of the last axis transformed will be s[-1]//2+1, while the remaining transformed axes will have lengths according to s, or unchanged from the input.    Raises
 ValueError

If s and axes have different length.  IndexError

If an element of axes is larger than than the number of axes of a.      See also  irfftn

The inverse of rfftn, i.e. the inverse of the n-dimensional FFT of real input.  fft

The one-dimensional FFT, with definitions and conventions used.  rfft

The one-dimensional FFT of real input.  fftn

The n-dimensional FFT.  rfft2

The two-dimensional FFT of real input.    Notes The transform for real input is performed over the last transformation axis, as by rfft, then the transform over the remaining axes is performed as by fftn. The order of the output is as for rfft for the final transformation axis, and as for fftn for the remaining transformation axes. See fft for details, definitions and conventions used. Examples >>> a = np.ones((2, 2, 2))
>>> np.fft.rfftn(a)
array([[[8.+0.j,  0.+0.j], # may vary
        [0.+0.j,  0.+0.j]],
       [[0.+0.j,  0.+0.j],
        [0.+0.j,  0.+0.j]]])
 >>> np.fft.rfftn(a, axes=(2, 0))
array([[[4.+0.j,  0.+0.j], # may vary
        [4.+0.j,  0.+0.j]],
       [[0.+0.j,  0.+0.j],
        [0.+0.j,  0.+0.j]]])


numpy.flatiter.base attribute   flatiter.base

A reference to the array that is iterated over. Examples >>> x = np.arange(5)
>>> fl = x.flat
>>> fl.base is x
True


numpy.flatiter.coords attribute   flatiter.coords

An N-dimensional tuple of current coordinates. Examples >>> x = np.arange(6).reshape(2, 3)
>>> fl = x.flat
>>> fl.coords
(0, 0)
>>> next(fl)
0
>>> fl.coords
(0, 1)


numpy.flatiter.copy method   flatiter.copy()

Get a copy of the iterator as a 1-D array. Examples >>> x = np.arange(6).reshape(2, 3)
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> fl = x.flat
>>> fl.copy()
array([0, 1, 2, 3, 4, 5])


numpy.flatiter.index attribute   flatiter.index

Current flat index into the array. Examples >>> x = np.arange(6).reshape(2, 3)
>>> fl = x.flat
>>> fl.index
0
>>> next(fl)
0
>>> fl.index
1


numpy.generic.__array__ method   generic.__array__()

sc.__array__(dtype) return 0-dim array from scalar with specified dtype


numpy.generic.__array_interface__ attribute   generic.__array_interface__

Array protocol: Python side


numpy.generic.__array_priority__ attribute   generic.__array_priority__

Array priority.


numpy.generic.__array_struct__ attribute   generic.__array_struct__

Array protocol: struct


numpy.generic.__array_wrap__ method   generic.__array_wrap__()

sc.__array_wrap__(obj) return scalar from array


numpy.generic.__reduce__ method   generic.__reduce__()

Helper for pickle.


numpy.generic.__setstate__ method   generic.__setstate__()


numpy.generic.base attribute   generic.base

Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.


numpy.generic.byteswap method   generic.byteswap()

Scalar method identical to the corresponding array attribute. Please see ndarray.byteswap.


numpy.generic.data attribute   generic.data

Pointer to start of data.


numpy.generic.dtype attribute   generic.dtype

Get array data-descriptor.


numpy.generic.flags attribute   generic.flags

The integer value of flags.


numpy.generic.flat attribute   generic.flat

A 1-D view of the scalar.


numpy.generic.imag attribute   generic.imag

The imaginary part of the scalar.


numpy.generic.itemsize attribute   generic.itemsize

The length of one element in bytes.


numpy.generic.ndim attribute   generic.ndim

The number of array dimensions.


numpy.generic.real attribute   generic.real

The real part of the scalar.


numpy.generic.setflags method   generic.setflags()

Scalar method identical to the corresponding array attribute. Please see ndarray.setflags.


numpy.generic.shape attribute   generic.shape

Tuple of array dimensions.


numpy.generic.size attribute   generic.size

The number of elements in the gentype.


numpy.generic.squeeze method   generic.squeeze()

Scalar method identical to the corresponding array attribute. Please see ndarray.squeeze.


numpy.generic.strides attribute   generic.strides

Tuple of bytes steps in each dimension.


numpy.generic.T attribute   generic.T

Scalar attribute identical to the corresponding array attribute. Please see ndarray.T.


get_build_temp_dir()[source]

Return a path to a temporary directory where temporary files should be placed.


get_config_cmd()[source]

Returns the numpy.distutils config command instance.


get_distribution()[source]

Return the distutils distribution object for self.


get_info(*names)[source]

Get resources information. Return information (from system_info.get_info) for all of the names in the argument list in a single dictionary.


get_subpackage(subpackage_name, subpackage_path=None, parent_name=None, caller_level=1)[source]

Return list of subpackage configurations.  Parameters

subpackage_namestr or None

Name of the subpackage to get the configuration. ‘*’ in subpackage_name is handled as a wildcard.
subpackage_pathstr

If None, then the path is assumed to be the local path plus the subpackage_name. If a setup.py file is not found in the subpackage_path, then a default configuration is used.
parent_namestr

Parent name.


get_version(version_file=None, version_variable=None)[source]

Try to get version string of a package. Return a version string of the current package or None if the version information could not be detected. Notes This method scans files named __version__.py, <packagename>_version.py, version.py, and __svn_version__.py for string variables version, __version__, and <packagename>_version, until a version number is found.


have_f77c()[source]

Check for availability of Fortran 77 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully).


have_f90c()[source]

Check for availability of Fortran 90 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled successfully)


numpy.i: a SWIG Interface File for NumPy  Introduction The Simple Wrapper and Interface Generator (or SWIG) is a powerful tool for generating wrapper code for interfacing to a wide variety of scripting languages. SWIG can parse header files, and using only the code prototypes, create an interface to the target language. But SWIG is not omnipotent. For example, it cannot know from the prototype: double rms(double* seq, int n);
 what exactly seq is. Is it a single value to be altered in-place? Is it an array, and if so what is its length? Is it input-only? Output-only? Input-output? SWIG cannot determine these details, and does not attempt to do so. If we designed rms, we probably made it a routine that takes an input-only array of length n of double values called seq and returns the root mean square. The default behavior of SWIG, however, will be to create a wrapper function that compiles, but is nearly impossible to use from the scripting language in the way the C routine was intended. For Python, the preferred way of handling contiguous (or technically, strided) blocks of homogeneous data is with NumPy, which provides full object-oriented access to multidimensial arrays of data. Therefore, the most logical Python interface for the rms function would be (including doc string): def rms(seq):
    """
    rms: return the root mean square of a sequence
    rms(numpy.ndarray) -> double
    rms(list) -> double
    rms(tuple) -> double
    """
 where seq would be a NumPy array of double values, and its length n would be extracted from seq internally before being passed to the C routine. Even better, since NumPy supports construction of arrays from arbitrary Python sequences, seq itself could be a nearly arbitrary sequence (so long as each element can be converted to a double) and the wrapper code would internally convert it to a NumPy array before extracting its data and length. SWIG allows these types of conversions to be defined via a mechanism called typemaps. This document provides information on how to use numpy.i, a SWIG interface file that defines a series of typemaps intended to make the type of array-related conversions described above relatively simple to implement. For example, suppose that the rms function prototype defined above was in a header file named rms.h. To obtain the Python interface discussed above, your SWIG interface file would need the following: %{
#define SWIG_FILE_WITH_INIT
#include "rms.h"
%}

%include "numpy.i"

%init %{
import_array();
%}

%apply (double* IN_ARRAY1, int DIM1) {(double* seq, int n)};
%include "rms.h"
 Typemaps are keyed off a list of one or more function arguments, either by type or by type and name. We will refer to such lists as signatures. One of the many typemaps defined by numpy.i is used above and has the signature (double* IN_ARRAY1, int DIM1). The argument names are intended to suggest that the double* argument is an input array of one dimension and that the int represents the size of that dimension. This is precisely the pattern in the rms prototype. Most likely, no actual prototypes to be wrapped will have the argument names IN_ARRAY1 and DIM1. We use the SWIG %apply directive to apply the typemap for one-dimensional input arrays of type double to the actual prototype used by rms. Using numpy.i effectively, therefore, requires knowing what typemaps are available and what they do. A SWIG interface file that includes the SWIG directives given above will produce wrapper code that looks something like:  1 PyObject *_wrap_rms(PyObject *args) {
 2   PyObject *resultobj = 0;
 3   double *arg1 = (double *) 0 ;
 4   int arg2 ;
 5   double result;
 6   PyArrayObject *array1 = NULL ;
 7   int is_new_object1 = 0 ;
 8   PyObject * obj0 = 0 ;
 9
10   if (!PyArg_ParseTuple(args,(char *)"O:rms",&obj0)) SWIG_fail;
11   {
12     array1 = obj_to_array_contiguous_allow_conversion(
13                  obj0, NPY_DOUBLE, &is_new_object1);
14     npy_intp size[1] = {
15       -1
16     };
17     if (!array1 || !require_dimensions(array1, 1) ||
18         !require_size(array1, size, 1)) SWIG_fail;
19     arg1 = (double*) array1->data;
20     arg2 = (int) array1->dimensions[0];
21   }
22   result = (double)rms(arg1,arg2);
23   resultobj = SWIG_From_double((double)(result));
24   {
25     if (is_new_object1 && array1) Py_DECREF(array1);
26   }
27   return resultobj;
28 fail:
29   {
30     if (is_new_object1 && array1) Py_DECREF(array1);
31   }
32   return NULL;
33 }
 The typemaps from numpy.i are responsible for the following lines of code: 12–20, 25 and 30. Line 10 parses the input to the rms function. From the format string "O:rms", we can see that the argument list is expected to be a single Python object (specified by the O before the colon) and whose pointer is stored in obj0. A number of functions, supplied by numpy.i, are called to make and check the (possible) conversion from a generic Python object to a NumPy array. These functions are explained in the section Helper Functions, but hopefully their names are self-explanatory. At line 12 we use obj0 to construct a NumPy array. At line 17, we check the validity of the result: that it is non-null and that it has a single dimension of arbitrary length. Once these states are verified, we extract the data buffer and length in lines 19 and 20 so that we can call the underlying C function at line 22. Line 25 performs memory management for the case where we have created a new array that is no longer needed. This code has a significant amount of error handling. Note the SWIG_fail is a macro for goto fail, referring to the label at line 28. If the user provides the wrong number of arguments, this will be caught at line 10. If construction of the NumPy array fails or produces an array with the wrong number of dimensions, these errors are caught at line 17. And finally, if an error is detected, memory is still managed correctly at line 30. Note that if the C function signature was in a different order: double rms(int n, double* seq);
 that SWIG would not match the typemap signature given above with the argument list for rms. Fortunately, numpy.i has a set of typemaps with the data pointer given last: %apply (int DIM1, double* IN_ARRAY1) {(int n, double* seq)};
 This simply has the effect of switching the definitions of arg1 and arg2 in lines 3 and 4 of the generated code above, and their assignments in lines 19 and 20.   Using numpy.i The numpy.i file is currently located in the tools/swig sub-directory under the numpy installation directory. Typically, you will want to copy it to the directory where you are developing your wrappers. A simple module that only uses a single SWIG interface file should include the following: %{
#define SWIG_FILE_WITH_INIT
%}
%include "numpy.i"
%init %{
import_array();
%}
 Within a compiled Python module, import_array() should only get called once. This could be in a C/C++ file that you have written and is linked to the module. If this is the case, then none of your interface files should #define SWIG_FILE_WITH_INIT or call import_array(). Or, this initialization call could be in a wrapper file generated by SWIG from an interface file that has the %init block as above. If this is the case, and you have more than one SWIG interface file, then only one interface file should #define SWIG_FILE_WITH_INIT and call import_array().   Available Typemaps The typemap directives provided by numpy.i for arrays of different data types, say double and int, and dimensions of different types, say int or long, are identical to one another except for the C and NumPy type specifications. The typemaps are therefore implemented (typically behind the scenes) via a macro: %numpy_typemaps(DATA_TYPE, DATA_TYPECODE, DIM_TYPE)
 that can be invoked for appropriate (DATA_TYPE, DATA_TYPECODE,
DIM_TYPE) triplets. For example: %numpy_typemaps(double, NPY_DOUBLE, int)
%numpy_typemaps(int,    NPY_INT   , int)
 The numpy.i interface file uses the %numpy_typemaps macro to implement typemaps for the following C data types and int dimension types:  signed char unsigned char short unsigned short int unsigned int long unsigned long long long unsigned long long float double  In the following descriptions, we reference a generic DATA_TYPE, which could be any of the C data types listed above, and DIM_TYPE which should be one of the many types of integers. The typemap signatures are largely differentiated on the name given to the buffer pointer. Names with FARRAY are for Fortran-ordered arrays, and names with ARRAY are for C-ordered (or 1D arrays).  Input Arrays Input arrays are defined as arrays of data that are passed into a routine but are not altered in-place or returned to the user. The Python input array is therefore allowed to be almost any Python sequence (such as a list) that can be converted to the requested type of array. The input array signatures are 1D:  ( DATA_TYPE IN_ARRAY1[ANY] ) ( DATA_TYPE* IN_ARRAY1, int DIM1 ) ( int DIM1, DATA_TYPE* IN_ARRAY1 )  2D:  ( DATA_TYPE IN_ARRAY2[ANY][ANY] ) ( DATA_TYPE* IN_ARRAY2, int DIM1, int DIM2 ) ( int DIM1, int DIM2, DATA_TYPE* IN_ARRAY2 ) ( DATA_TYPE* IN_FARRAY2, int DIM1, int DIM2 ) ( int DIM1, int DIM2, DATA_TYPE* IN_FARRAY2 )  3D:  ( DATA_TYPE IN_ARRAY3[ANY][ANY][ANY] ) ( DATA_TYPE* IN_ARRAY3, int DIM1, int DIM2, int DIM3 ) ( int DIM1, int DIM2, int DIM3, DATA_TYPE* IN_ARRAY3 ) ( DATA_TYPE* IN_FARRAY3, int DIM1, int DIM2, int DIM3 ) ( int DIM1, int DIM2, int DIM3, DATA_TYPE* IN_FARRAY3 )  4D:  (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, , DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4)  The first signature listed, ( DATA_TYPE IN_ARRAY[ANY] ) is for one-dimensional arrays with hard-coded dimensions. Likewise, ( DATA_TYPE IN_ARRAY2[ANY][ANY] ) is for two-dimensional arrays with hard-coded dimensions, and similarly for three-dimensional.   In-Place Arrays In-place arrays are defined as arrays that are modified in-place. The input values may or may not be used, but the values at the time the function returns are significant. The provided Python argument must therefore be a NumPy array of the required type. The in-place signatures are 1D:  ( DATA_TYPE INPLACE_ARRAY1[ANY] ) ( DATA_TYPE* INPLACE_ARRAY1, int DIM1 ) ( int DIM1, DATA_TYPE* INPLACE_ARRAY1 )  2D:  ( DATA_TYPE INPLACE_ARRAY2[ANY][ANY] ) ( DATA_TYPE* INPLACE_ARRAY2, int DIM1, int DIM2 ) ( int DIM1, int DIM2, DATA_TYPE* INPLACE_ARRAY2 ) ( DATA_TYPE* INPLACE_FARRAY2, int DIM1, int DIM2 ) ( int DIM1, int DIM2, DATA_TYPE* INPLACE_FARRAY2 )  3D:  ( DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY] ) ( DATA_TYPE* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3 ) ( int DIM1, int DIM2, int DIM3, DATA_TYPE* INPLACE_ARRAY3 ) ( DATA_TYPE* INPLACE_FARRAY3, int DIM1, int DIM2, int DIM3 ) ( int DIM1, int DIM2, int DIM3, DATA_TYPE* INPLACE_FARRAY3 )  4D:  (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, , DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4) (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4)  These typemaps now check to make sure that the INPLACE_ARRAY arguments use native byte ordering. If not, an exception is raised. There is also a “flat” in-place array for situations in which you would like to modify or process each element, regardless of the number of dimensions. One example is a “quantization” function that quantizes each element of an array in-place, be it 1D, 2D or whatever. This form checks for continuity but allows either C or Fortran ordering. ND:  (DATA_TYPE* INPLACE_ARRAY_FLAT, DIM_TYPE DIM_FLAT)    Argout Arrays Argout arrays are arrays that appear in the input arguments in C, but are in fact output arrays. This pattern occurs often when there is more than one output variable and the single return argument is therefore not sufficient. In Python, the conventional way to return multiple arguments is to pack them into a sequence (tuple, list, etc.) and return the sequence. This is what the argout typemaps do. If a wrapped function that uses these argout typemaps has more than one return argument, they are packed into a tuple or list, depending on the version of Python. The Python user does not pass these arrays in, they simply get returned. For the case where a dimension is specified, the python user must provide that dimension as an argument. The argout signatures are 1D:  ( DATA_TYPE ARGOUT_ARRAY1[ANY] ) ( DATA_TYPE* ARGOUT_ARRAY1, int DIM1 ) ( int DIM1, DATA_TYPE* ARGOUT_ARRAY1 )  2D:  ( DATA_TYPE ARGOUT_ARRAY2[ANY][ANY] )  3D:  ( DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY] )  4D:  ( DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY] )  These are typically used in situations where in C/C++, you would allocate a(n) array(s) on the heap, and call the function to fill the array(s) values. In Python, the arrays are allocated for you and returned as new array objects. Note that we support DATA_TYPE* argout typemaps in 1D, but not 2D or 3D. This is because of a quirk with the SWIG typemap syntax and cannot be avoided. Note that for these types of 1D typemaps, the Python function will take a single argument representing DIM1.   Argout View Arrays Argoutview arrays are for when your C code provides you with a view of its internal data and does not require any memory to be allocated by the user. This can be dangerous. There is almost no way to guarantee that the internal data from the C code will remain in existence for the entire lifetime of the NumPy array that encapsulates it. If the user destroys the object that provides the view of the data before destroying the NumPy array, then using that array may result in bad memory references or segmentation faults. Nevertheless, there are situations, working with large data sets, where you simply have no other choice. The C code to be wrapped for argoutview arrays are characterized by pointers: pointers to the dimensions and double pointers to the data, so that these values can be passed back to the user. The argoutview typemap signatures are therefore 1D:  ( DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1 ) ( DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1 )  2D:  ( DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2 ) ( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2 ) ( DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2 ) ( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2 )  3D:  ( DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) ( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) ( DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) ( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3)  4D:  (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_ARRAY4) (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_FARRAY4)  Note that arrays with hard-coded dimensions are not supported. These cannot follow the double pointer signatures of these typemaps.   Memory Managed Argout View Arrays A recent addition to numpy.i are typemaps that permit argout arrays with views into memory that is managed. See the discussion here. 1D:  (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1) (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1)  2D:  (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2) (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2)  3D:  (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_ARRAY3) (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_FARRAY3)  4D:  (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4)    Output Arrays The numpy.i interface file does not support typemaps for output arrays, for several reasons. First, C/C++ return arguments are limited to a single value. This prevents obtaining dimension information in a general way. Second, arrays with hard-coded lengths are not permitted as return arguments. In other words: double[3] newVector(double x, double y, double z);
 is not legal C/C++ syntax. Therefore, we cannot provide typemaps of the form: %typemap(out) (TYPE[ANY]);
 If you run into a situation where a function or method is returning a pointer to an array, your best bet is to write your own version of the function to be wrapped, either with %extend for the case of class methods or %ignore and %rename for the case of functions.   Other Common Types: bool Note that C++ type bool is not supported in the list in the Available Typemaps section. NumPy bools are a single byte, while the C++ bool is four bytes (at least on my system). Therefore: %numpy_typemaps(bool, NPY_BOOL, int)
 will result in typemaps that will produce code that reference improper data lengths. You can implement the following macro expansion: %numpy_typemaps(bool, NPY_UINT, int)
 to fix the data length problem, and Input Arrays will work fine, but In-Place Arrays might fail type-checking.   Other Common Types: complex Typemap conversions for complex floating-point types is also not supported automatically. This is because Python and NumPy are written in C, which does not have native complex types. Both Python and NumPy implement their own (essentially equivalent) struct definitions for complex variables: /* Python */
typedef struct {double real; double imag;} Py_complex;

/* NumPy */
typedef struct {float  real, imag;} npy_cfloat;
typedef struct {double real, imag;} npy_cdouble;
 We could have implemented: %numpy_typemaps(Py_complex , NPY_CDOUBLE, int)
%numpy_typemaps(npy_cfloat , NPY_CFLOAT , int)
%numpy_typemaps(npy_cdouble, NPY_CDOUBLE, int)
 which would have provided automatic type conversions for arrays of type Py_complex, npy_cfloat and npy_cdouble. However, it seemed unlikely that there would be any independent (non-Python, non-NumPy) application code that people would be using SWIG to generate a Python interface to, that also used these definitions for complex types. More likely, these application codes will define their own complex types, or in the case of C++, use std::complex. Assuming these data structures are compatible with Python and NumPy complex types, %numpy_typemap expansions as above (with the user’s complex type substituted for the first argument) should work.    NumPy Array Scalars and SWIG SWIG has sophisticated type checking for numerical types. For example, if your C/C++ routine expects an integer as input, the code generated by SWIG will check for both Python integers and Python long integers, and raise an overflow error if the provided Python integer is too big to cast down to a C integer. With the introduction of NumPy scalar arrays into your Python code, you might conceivably extract an integer from a NumPy array and attempt to pass this to a SWIG-wrapped C/C++ function that expects an int, but the SWIG type checking will not recognize the NumPy array scalar as an integer. (Often, this does in fact work – it depends on whether NumPy recognizes the integer type you are using as inheriting from the Python integer type on the platform you are using. Sometimes, this means that code that works on a 32-bit machine will fail on a 64-bit machine.) If you get a Python error that looks like the following: TypeError: in method 'MyClass_MyMethod', argument 2 of type 'int'
 and the argument you are passing is an integer extracted from a NumPy array, then you have stumbled upon this problem. The solution is to modify the SWIG type conversion system to accept NumPy array scalars in addition to the standard integer types. Fortunately, this capability has been provided for you. Simply copy the file: pyfragments.swg
 to the working build directory for you project, and this problem will be fixed. It is suggested that you do this anyway, as it only increases the capabilities of your Python interface.  Why is There a Second File? The SWIG type checking and conversion system is a complicated combination of C macros, SWIG macros, SWIG typemaps and SWIG fragments. Fragments are a way to conditionally insert code into your wrapper file if it is needed, and not insert it if not needed. If multiple typemaps require the same fragment, the fragment only gets inserted into your wrapper code once. There is a fragment for converting a Python integer to a C long. There is a different fragment that converts a Python integer to a C int, that calls the routine defined in the long fragment. We can make the changes we want here by changing the definition for the long fragment. SWIG determines the active definition for a fragment using a “first come, first served” system. That is, we need to define the fragment for long conversions prior to SWIG doing it internally. SWIG allows us to do this by putting our fragment definitions in the file pyfragments.swg. If we were to put the new fragment definitions in numpy.i, they would be ignored.    Helper Functions The numpy.i file contains several macros and routines that it uses internally to build its typemaps. However, these functions may be useful elsewhere in your interface file. These macros and routines are implemented as fragments, which are described briefly in the previous section. If you try to use one or more of the following macros or functions, but your compiler complains that it does not recognize the symbol, then you need to force these fragments to appear in your code using: %fragment("NumPy_Fragments");
 in your SWIG interface file.  Macros  is_array(a)

Evaluates as true if a is non-NULL and can be cast to a PyArrayObject*.  array_type(a)

Evaluates to the integer data type code of a, assuming a can be cast to a PyArrayObject*.  array_numdims(a)

Evaluates to the integer number of dimensions of a, assuming a can be cast to a PyArrayObject*.  array_dimensions(a)

Evaluates to an array of type npy_intp and length array_numdims(a), giving the lengths of all of the dimensions of a, assuming a can be cast to a PyArrayObject*.  array_size(a,i)

Evaluates to the i-th dimension size of a, assuming a can be cast to a PyArrayObject*.  array_strides(a)

Evaluates to an array of type npy_intp and length array_numdims(a), giving the stridess of all of the dimensions of a, assuming a can be cast to a PyArrayObject*. A stride is the distance in bytes between an element and its immediate neighbor along the same axis.  array_stride(a,i)

Evaluates to the i-th stride of a, assuming a can be cast to a PyArrayObject*.  array_data(a)

Evaluates to a pointer of type void* that points to the data buffer of a, assuming a can be cast to a PyArrayObject*.  array_descr(a)

Returns a borrowed reference to the dtype property (PyArray_Descr*) of a, assuming a can be cast to a PyArrayObject*.  array_flags(a)

Returns an integer representing the flags of a, assuming a can be cast to a PyArrayObject*.  array_enableflags(a,f)

Sets the flag represented by f of a, assuming a can be cast to a PyArrayObject*.  array_is_contiguous(a)

Evaluates as true if a is a contiguous array. Equivalent to (PyArray_ISCONTIGUOUS(a)).  array_is_native(a)

Evaluates as true if the data buffer of a uses native byte order. Equivalent to (PyArray_ISNOTSWAPPED(a)).  array_is_fortran(a)

Evaluates as true if a is FORTRAN ordered.     Routines pytype_string() Return type: const char* Arguments:
PyObject* py_obj, a general Python object.  Return a string describing the type of py_obj. typecode_string() Return type: const char* Arguments:
int typecode, a NumPy integer typecode.  Return a string describing the type corresponding to the NumPy typecode. type_match() Return type: int Arguments:
int actual_type, the NumPy typecode of a NumPy array.
int desired_type, the desired NumPy typecode.  Make sure that actual_type is compatible with desired_type. For example, this allows character and byte types, or int and long types, to match. This is now equivalent to PyArray_EquivTypenums(). obj_to_array_no_conversion() Return type: PyArrayObject* Arguments:
PyObject* input, a general Python object.
int typecode, the desired NumPy typecode.  Cast input to a PyArrayObject* if legal, and ensure that it is of type typecode. If input cannot be cast, or the typecode is wrong, set a Python error and return NULL. obj_to_array_allow_conversion() Return type: PyArrayObject* Arguments:
PyObject* input, a general Python object.
int typecode, the desired NumPy typecode of the resulting array.
int* is_new_object, returns a value of 0 if no conversion performed, else 1.  Convert input to a NumPy array with the given typecode. On success, return a valid PyArrayObject* with the correct type. On failure, the Python error string will be set and the routine returns NULL. make_contiguous() Return type: PyArrayObject* Arguments:
PyArrayObject* ary, a NumPy array.
int* is_new_object, returns a value of 0 if no conversion performed, else 1.
int min_dims, minimum allowable dimensions.
int max_dims, maximum allowable dimensions.  Check to see if ary is contiguous. If so, return the input pointer and flag it as not a new object. If it is not contiguous, create a new PyArrayObject* using the original data, flag it as a new object and return the pointer. make_fortran() Return type: PyArrayObject* Arguments
PyArrayObject* ary, a NumPy array.
int* is_new_object, returns a value of 0 if no conversion performed, else 1.  Check to see if ary is Fortran contiguous. If so, return the input pointer and flag it as not a new object. If it is not Fortran contiguous, create a new PyArrayObject* using the original data, flag it as a new object and return the pointer. obj_to_array_contiguous_allow_conversion() Return type: PyArrayObject* Arguments:
PyObject* input, a general Python object.
int typecode, the desired NumPy typecode of the resulting array.
int* is_new_object, returns a value of 0 if no conversion performed, else 1.  Convert input to a contiguous PyArrayObject* of the specified type. If the input object is not a contiguous PyArrayObject*, a new one will be created and the new object flag will be set. obj_to_array_fortran_allow_conversion() Return type: PyArrayObject* Arguments:
PyObject* input, a general Python object.
int typecode, the desired NumPy typecode of the resulting array.
int* is_new_object, returns a value of 0 if no conversion performed, else 1.  Convert input to a Fortran contiguous PyArrayObject* of the specified type. If the input object is not a Fortran contiguous PyArrayObject*, a new one will be created and the new object flag will be set. require_contiguous() Return type: int Arguments:
PyArrayObject* ary, a NumPy array.  Test whether ary is contiguous. If so, return 1. Otherwise, set a Python error and return 0. require_native() Return type: int Arguments:
PyArray_Object* ary, a NumPy array.  Require that ary is not byte-swapped. If the array is not byte-swapped, return 1. Otherwise, set a Python error and return 0. require_dimensions() Return type: int Arguments:
PyArrayObject* ary, a NumPy array.
int exact_dimensions, the desired number of dimensions.  Require ary to have a specified number of dimensions. If the array has the specified number of dimensions, return 1. Otherwise, set a Python error and return 0. require_dimensions_n() Return type: int Arguments:
PyArrayObject* ary, a NumPy array.
int* exact_dimensions, an array of integers representing acceptable numbers of dimensions.
int n, the length of exact_dimensions.  Require ary to have one of a list of specified number of dimensions. If the array has one of the specified number of dimensions, return 1. Otherwise, set the Python error string and return 0. require_size() Return type: int Arguments:
PyArrayObject* ary, a NumPy array.
npy_int* size, an array representing the desired lengths of each dimension.
int n, the length of size.  Require ary to have a specified shape. If the array has the specified shape, return 1. Otherwise, set the Python error string and return 0. require_fortran() Return type: int Arguments:
PyArrayObject* ary, a NumPy array.  Require the given PyArrayObject to to be Fortran ordered. If the PyArrayObject is already Fortran ordered, do nothing. Else, set the Fortran ordering flag and recompute the strides.    Beyond the Provided Typemaps There are many C or C++ array/NumPy array situations not covered by a simple %include "numpy.i" and subsequent %apply directives.  A Common Example Consider a reasonable prototype for a dot product function: double dot(int len, double* vec1, double* vec2);
 The Python interface that we want is: def dot(vec1, vec2):
    """
    dot(PyObject,PyObject) -> double
    """
 The problem here is that there is one dimension argument and two array arguments, and our typemaps are set up for dimensions that apply to a single array (in fact, SWIG does not provide a mechanism for associating len with vec2 that takes two Python input arguments). The recommended solution is the following: %apply (int DIM1, double* IN_ARRAY1) {(int len1, double* vec1),
                                      (int len2, double* vec2)}
%rename (dot) my_dot;
%exception my_dot {
    $action
    if (PyErr_Occurred()) SWIG_fail;
}
%inline %{
double my_dot(int len1, double* vec1, int len2, double* vec2) {
    if (len1 != len2) {
        PyErr_Format(PyExc_ValueError,
                     "Arrays of lengths (%d,%d) given",
                     len1, len2);
        return 0.0;
    }
    return dot(len1, vec1, vec2);
}
%}
 If the header file that contains the prototype for double dot() also contains other prototypes that you want to wrap, so that you need to %include this header file, then you will also need a %ignore
dot; directive, placed after the %rename and before the %include directives. Or, if the function in question is a class method, you will want to use %extend rather than %inline in addition to %ignore. A note on error handling: Note that my_dot returns a double but that it can also raise a Python error. The resulting wrapper function will return a Python float representation of 0.0 when the vector lengths do not match. Since this is not NULL, the Python interpreter will not know to check for an error. For this reason, we add the %exception directive above for my_dot to get the behavior we want (note that $action is a macro that gets expanded to a valid call to my_dot). In general, you will probably want to write a SWIG macro to perform this task.   Other Situations There are other wrapping situations in which numpy.i may be helpful when you encounter them.
In some situations, it is possible that you could use the %numpy_typemaps macro to implement typemaps for your own types. See the Other Common Types: bool or Other Common Types: complex sections for examples. Another situation is if your dimensions are of a type other than int (say long for example): %numpy_typemaps(double, NPY_DOUBLE, long)
  You can use the code in numpy.i to write your own typemaps. For example, if you had a five-dimensional array as a function argument, you could cut-and-paste the appropriate four-dimensional typemaps into your interface file. The modifications for the fourth dimension would be trivial. Sometimes, the best approach is to use the %extend directive to define new methods for your classes (or overload existing ones) that take a PyObject* (that either is or can be converted to a PyArrayObject*) instead of a pointer to a buffer. In this case, the helper routines in numpy.i can be very useful. Writing typemaps can be a bit nonintuitive. If you have specific questions about writing SWIG typemaps for NumPy, the developers of numpy.i do monitor the Numpy-discussion and Swig-user mail lists.    A Final Note When you use the %apply directive, as is usually necessary to use numpy.i, it will remain in effect until you tell SWIG that it shouldn’t be. If the arguments to the functions or methods that you are wrapping have common names, such as length or vector, these typemaps may get applied in situations you do not expect or want. Therefore, it is always a good idea to add a %clear directive after you are done with a specific typemap: %apply (double* IN_ARRAY1, int DIM1) {(double* vector, int length)}
%include "my_header.h"
%clear (double* vector, int length);
 In general, you should target these typemap signatures specifically where you want them, and then clear them after you are done.    Summary Out of the box, numpy.i provides typemaps that support conversion between NumPy arrays and C arrays:  That can be one of 12 different scalar types: signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, long long, unsigned long long, float and double.
That support 74 different argument signatures for each data type, including:  One-dimensional, two-dimensional, three-dimensional and four-dimensional arrays. Input-only, in-place, argout, argoutview, and memory managed argoutview behavior. Hard-coded dimensions, data-buffer-then-dimensions specification, and dimensions-then-data-buffer specification. Both C-ordering (“last dimension fastest”) or Fortran-ordering (“first dimension fastest”) support for 2D, 3D and 4D arrays.    The numpy.i interface file also provides additional tools for wrapper developers, including:  A SWIG macro (%numpy_typemaps) with three arguments for implementing the 74 argument signatures for the user’s choice of (1) C data type, (2) NumPy data type (assuming they match), and (3) dimension type. Fourteen C macros and fifteen C functions that can be used to write specialized typemaps, extensions, or inlined functions that handle cases not covered by the provided typemaps. Note that the macros and functions are coded specifically to work with the NumPy C/API regardless of NumPy version number, both before and after the deprecation of some aspects of the API after version 1.6.


numpy.lib.format.descr_to_dtype   lib.format.descr_to_dtype(descr)[source]

Returns a dtype based off the given description. This is essentially the reverse of dtype_to_descr(). It will remove the valueless padding fields created by, i.e. simple fields like dtype(‘float32’), and then convert the description to its corresponding dtype.  Parameters

descrobject

The object retrieved by dtype.descr. Can be passed to numpy.dtype() in order to replicate the input dtype.    Returns

dtypedtype

The dtype constructed by the description.


numpy.lib.format.dtype_to_descr   lib.format.dtype_to_descr(dtype)[source]

Get a serializable descriptor from the dtype. The .descr attribute of a dtype object cannot be round-tripped through the dtype() constructor. Simple types, like dtype(‘float32’), have a descr which looks like a record array with one field with ‘’ as a name. The dtype() constructor interprets this as a request to give a default name. Instead, we construct descriptor that can be passed to dtype().  Parameters

dtypedtype

The dtype of the array that will be written to disk.    Returns

descrobject

An object that can be passed to numpy.dtype() in order to replicate the input dtype.