doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.vectorize.__call__ method vectorize.__call__(*args, **kwargs)[source] Return arrays with the results of pyfunc broadcast (vectorized) over args and kwargs not in excluded.
numpy.reference.generated.numpy.vectorize.__call__
The Array Interface Note This page describes the numpy-specific API for accessing the contents of a numpy array from other C extensions. PEP 3118 – The Revised Buffer Protocol introduces similar, standardized API to Python 2.6 and 3.0 for any extension module to use. Cython’s buffer array support uses the PEP 3118 API; see the Cython numpy tutorial. Cython provides a way to write code that supports the buffer protocol with Python versions older than 2.6 because it has a backward-compatible implementation utilizing the array interface described here. version 3 The array interface (sometimes called array protocol) was created in 2005 as a means for array-like Python objects to re-use each other’s data buffers intelligently whenever possible. The homogeneous N-dimensional array interface is a default mechanism for objects to share N-dimensional array memory and information. The interface consists of a Python-side and a C-side using two attributes. Objects wishing to be considered an N-dimensional array in application code should support at least one of these attributes. Objects wishing to support an N-dimensional array in application code should look for at least one of these attributes and use the information provided appropriately. This interface describes homogeneous arrays in the sense that each item of the array has the same “type”. This type can be very simple or it can be a quite arbitrary and complicated C-like structure. There are two ways to use the interface: A Python side and a C-side. Both are separate attributes. Python side This approach to the interface consists of the object having an __array_interface__ attribute. object.__array_interface__ A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided. The keys are: shape (required) Tuple whose elements are the array size in each dimension. Each entry is an integer (a Python int). Note that these integers could be larger than the platform int or long could hold (a Python int is a C long). It is up to the code using this attribute to handle this appropriately; either by raising an error when overflow is possible, or by using long long as the C type for the shapes. typestr (required) A string providing the basic type of the homogeneous array The basic string format consists of 3 parts: a character describing the byteorder of the data (<: little-endian, >: big-endian, |: not-relevant), a character code giving the basic type of the array, and an integer providing the number of bytes the type uses. The basic type character codes are: t Bit field (following integer gives the number of bits in the bit field). b Boolean (integer type where all values are only True or False) i Integer u Unsigned integer f Floating point c Complex floating point m Timedelta M Datetime O Object (i.e. the memory contains a pointer to PyObject) S String (fixed-length sequence of char) U Unicode (fixed-length sequence of Py_UNICODE) V Other (void * – each item is a fixed-size chunk of memory) descr (optional) A list of tuples providing a more detailed description of the memory layout for each item in the homogeneous array. Each tuple in the list has two or three elements. Normally, this attribute would be used when typestr is V[0-9]+, but this is not a requirement. The only requirement is that the number of bytes represented in the typestr key is the same as the total number of bytes represented here. The idea is to support descriptions of C-like structs that make up array elements. The elements of each tuple in the list are A string providing a name associated with this portion of the datatype. This could also be a tuple of ('full name', 'basic_name') where basic name would be a valid Python variable name representing the full name of the field. Either a basic-type description string as in typestr or another list (for nested structured types) An optional shape tuple providing how many times this part of the structure should be repeated. No repeats are assumed if this is not given. Very complicated structures can be described using this generic interface. Notice, however, that each element of the array is still of the same data-type. Some examples of using this interface are given below. Default: [('', typestr)] data (optional) A 2-tuple whose first argument is an integer (a long integer if necessary) that points to the data-area storing the array contents. This pointer must point to the first element of data (in other words any offset is always ignored in this case). The second entry in the tuple is a read-only flag (true means the data area is read-only). This attribute can also be an object exposing the buffer interface which will be used to share the data. If this key is not present (or returns None), then memory sharing will be done through the buffer interface of the object itself. In this case, the offset key can be used to indicate the start of the buffer. A reference to the object exposing the array interface must be stored by the new object if the memory area is to be secured. Default: None strides (optional) Either None to indicate a C-style contiguous array or a Tuple of strides which provides the number of bytes needed to jump to the next array element in the corresponding dimension. Each entry must be an integer (a Python int). As with shape, the values may be larger than can be represented by a C int or long; the calling code should handle this appropriately, either by raising an error, or by using long long in C. The default is None which implies a C-style contiguous memory buffer. In this model, the last dimension of the array varies the fastest. For example, the default strides tuple for an object whose array entries are 8 bytes long and whose shape is (10, 20, 30) would be (4800, 240, 8) Default: None (C-style contiguous) mask (optional) None or an object exposing the array interface. All elements of the mask array should be interpreted only as true or not true indicating which elements of this array are valid. The shape of this object should be “broadcastable” to the shape of the original array. Default: None (All array values are valid) offset (optional) An integer offset into the array data region. This can only be used when data is None or returns a buffer object. Default: 0. version (required) An integer showing the version of the interface (i.e. 3 for this version). Be careful not to use this to invalidate objects exposing future versions of the interface. C-struct access This approach to the array interface allows for faster access to an array using only one attribute lookup and a well-defined C-structure. object.__array_struct__ A PyCapsule whose pointer member contains a pointer to a filled PyArrayInterface structure. Memory for the structure is dynamically created and the PyCapsule is also created with an appropriate destructor so the retriever of this attribute simply has to apply Py_DECREF to the object returned by this attribute when it is finished. Also, either the data needs to be copied out, or a reference to the object exposing this attribute must be held to ensure the data is not freed. Objects exposing the __array_struct__ interface must also not reallocate their memory if other objects are referencing them. The PyArrayInterface structure is defined in numpy/ndarrayobject.h as: typedef struct { int two; /* contains the integer 2 -- simple sanity check */ int nd; /* number of dimensions */ char typekind; /* kind in array --- character code of typestr */ int itemsize; /* size of each element */ int flags; /* flags indicating how the data should be interpreted */ /* must set ARR_HAS_DESCR bit to validate descr */ Py_intptr_t *shape; /* A length-nd array of shape information */ Py_intptr_t *strides; /* A length-nd array of stride information */ void *data; /* A pointer to the first element of the array */ PyObject *descr; /* NULL or data-description (same as descr key of __array_interface__) -- must set ARR_HAS_DESCR flag or this will be ignored. */ } PyArrayInterface; The flags member may consist of 5 bits showing how the data should be interpreted and one bit showing how the Interface should be interpreted. The data-bits are NPY_ARRAY_C_CONTIGUOUS (0x1), NPY_ARRAY_F_CONTIGUOUS (0x2), NPY_ARRAY_ALIGNED (0x100), NPY_ARRAY_NOTSWAPPED (0x200), and NPY_ARRAY_WRITEABLE (0x400). A final flag NPY_ARR_HAS_DESCR (0x800) indicates whether or not this structure has the arrdescr field. The field should not be accessed unless this flag is present. NPY_ARR_HAS_DESCR New since June 16, 2006: In the past most implementations used the desc member of the PyCObject (now PyCapsule) itself (do not confuse this with the “descr” member of the PyArrayInterface structure above — they are two separate things) to hold the pointer to the object exposing the interface. This is now an explicit part of the interface. Be sure to take a reference to the object and call PyCapsule_SetContext before returning the PyCapsule, and configure a destructor to decref this reference. Type description examples For clarity it is useful to provide some examples of the type description and corresponding __array_interface__ ‘descr’ entries. Thanks to Scott Gilbert for these examples: In every case, the ‘descr’ key is optional, but of course provides more information which may be important for various applications: * Float data typestr == '>f4' descr == [('','>f4')] * Complex double typestr == '>c8' descr == [('real','>f4'), ('imag','>f4')] * RGB Pixel data typestr == '|V3' descr == [('r','|u1'), ('g','|u1'), ('b','|u1')] * Mixed endian (weird but could happen). typestr == '|V8' (or '>u8') descr == [('big','>i4'), ('little','<i4')] * Nested structure struct { int ival; struct { unsigned short sval; unsigned char bval; unsigned char cval; } sub; } typestr == '|V8' (or '<u8' if you want) descr == [('ival','<i4'), ('sub', [('sval','<u2'), ('bval','|u1'), ('cval','|u1') ]) ] * Nested array struct { int ival; double data[16*4]; } typestr == '|V516' descr == [('ival','>i4'), ('data','>f8',(16,4))] * Padded structure struct { int ival; double dval; } typestr == '|V16' descr == [('ival','>i4'),('','|V4'),('dval','>f8')] It should be clear that any structured type could be described using this interface. Differences with Array interface (Version 2) The version 2 interface was very similar. The differences were largely aesthetic. In particular: The PyArrayInterface structure had no descr member at the end (and therefore no flag ARR_HAS_DESCR) The context member of the PyCapsule (formally the desc member of the PyCObject) returned from __array_struct__ was not specified. Usually, it was the object exposing the array (so that a reference to it could be kept and destroyed when the C-object was destroyed). It is now an explicit requirement that this field be used in some way to hold a reference to the owning object. Note Until August 2020, this said: Now it must be a tuple whose first element is a string with “PyArrayInterface Version #” and whose second element is the object exposing the array. This design was retracted almost immediately after it was proposed, in <https://mail.python.org/pipermail/numpy-discussion/2006-June/020995.html>. Despite 14 years of documentation to the contrary, at no point was it valid to assume that __array_interface__ capsules held this tuple content. The tuple returned from __array_interface__['data'] used to be a hex-string (now it is an integer or a long integer). There was no __array_interface__ attribute instead all of the keys (except for version) in the __array_interface__ dictionary were their own attribute: Thus to obtain the Python-side information you had to access separately the attributes: __array_data__ __array_shape__ __array_strides__ __array_typestr__ __array_descr__ __array_offset__ __array_mask__
numpy.reference.arrays.interface
numpy.lib.format Binary serialization NPY format A simple format for saving numpy arrays to disk with the full information about them. The .npy format is the standard binary file format in NumPy for persisting a single arbitrary NumPy array on disk. The format stores all of the shape and dtype information necessary to reconstruct the array correctly even on another machine with a different architecture. The format is designed to be as simple as possible while achieving its limited goals. The .npz format is the standard format for persisting multiple NumPy arrays on disk. A .npz file is a zip file containing multiple .npy files, one for each array. Capabilities Can represent all NumPy arrays including nested record arrays and object arrays. Represents the data in its native binary form. Supports Fortran-contiguous arrays directly. Stores all of the necessary information to reconstruct the array including shape and dtype on a machine of a different architecture. Both little-endian and big-endian arrays are supported, and a file with little-endian numbers will yield a little-endian array on any machine reading the file. The types are described in terms of their actual sizes. For example, if a machine with a 64-bit C “long int” writes out an array with “long ints”, a reading machine with 32-bit C “long ints” will yield an array with 64-bit integers. Is straightforward to reverse engineer. Datasets often live longer than the programs that created them. A competent developer should be able to create a solution in their preferred programming language to read most .npy files that they have been given without much documentation. Allows memory-mapping of the data. See open_memmap. Can be read from a filelike stream object instead of an actual file. Stores object arrays, i.e. arrays containing elements that are arbitrary Python objects. Files with object arrays are not to be mmapable, but can be read and written to disk. Limitations Arbitrary subclasses of numpy.ndarray are not completely preserved. Subclasses will be accepted for writing, but only the array data will be written out. A regular numpy.ndarray object will be created upon reading the file. Warning Due to limitations in the interpretation of structured dtypes, dtypes with fields with empty names will have the names replaced by ‘f0’, ‘f1’, etc. Such arrays will not round-trip through the format entirely accurately. The data is intact; only the field names will differ. We are working on a fix for this. This fix will not require a change in the file format. The arrays with such structures can still be saved and restored, and the correct dtype may be restored by using the loadedarray.view(correct_dtype) method. File extensions We recommend using the .npy and .npz extensions for files saved in this format. This is by no means a requirement; applications may wish to use these file formats but use an extension specific to the application. In the absence of an obvious alternative, however, we suggest using .npy and .npz. Version numbering The version numbering of these formats is independent of NumPy version numbering. If the format is upgraded, the code in numpy.io will still be able to read and write Version 1.0 files. Format Version 1.0 The first 6 bytes are a magic string: exactly \x93NUMPY. The next 1 byte is an unsigned byte: the major version number of the file format, e.g. \x01. The next 1 byte is an unsigned byte: the minor version number of the file format, e.g. \x00. Note: the version of the file format is not tied to the version of the numpy package. The next 2 bytes form a little-endian unsigned short int: the length of the header data HEADER_LEN. The next HEADER_LEN bytes form the header data describing the array’s format. It is an ASCII string which contains a Python literal expression of a dictionary. It is terminated by a newline (\n) and padded with spaces (\x20) to make the total of len(magic string) + 2 + len(length) + HEADER_LEN be evenly divisible by 64 for alignment purposes. The dictionary contains three keys: “descr”dtype.descr An object that can be passed as an argument to the numpy.dtype constructor to create the array’s dtype. “fortran_order”bool Whether the array data is Fortran-contiguous or not. Since Fortran-contiguous arrays are a common form of non-C-contiguity, we allow them to be written directly to disk for efficiency. “shape”tuple of int The shape of the array. For repeatability and readability, the dictionary keys are sorted in alphabetic order. This is for convenience only. A writer SHOULD implement this if possible. A reader MUST NOT depend on this. Following the header comes the array data. If the dtype contains Python objects (i.e. dtype.hasobject is True), then the data is a Python pickle of the array. Otherwise the data is the contiguous (either C- or Fortran-, depending on fortran_order) bytes of the array. Consumers can figure out the number of bytes by multiplying the number of elements given by the shape (noting that shape=() means there is 1 element) by dtype.itemsize. Format Version 2.0 The version 1.0 format only allowed the array header to have a total size of 65535 bytes. This can be exceeded by structured arrays with a large number of columns. The version 2.0 format extends the header size to 4 GiB. numpy.save will automatically save in 2.0 format if the data requires it, else it will always use the more compatible 1.0 format. The description of the fourth element of the header therefore has become: “The next 4 bytes form a little-endian unsigned int: the length of the header data HEADER_LEN.” Format Version 3.0 This version replaces the ASCII string (which in practice was latin1) with a utf8-encoded string, so supports structured types with any unicode field names. Notes The .npy format, including motivation for creating it and a comparison of alternatives, is described in the “npy-format” NEP, however details have evolved with time and this document is more current. Functions descr_to_dtype(descr) Returns a dtype based off the given description. dtype_to_descr(dtype) Get a serializable descriptor from the dtype. header_data_from_array_1_0(array) Get the dictionary of header metadata from a numpy.ndarray. magic(major, minor) Return the magic string for the given file format version. open_memmap(filename[, mode, dtype, shape, ...]) Open a .npy file as a memory-mapped array. read_array(fp[, allow_pickle, pickle_kwargs]) Read an array from an NPY file. read_array_header_1_0(fp) Read an array header from a filelike object using the 1.0 file format version. read_array_header_2_0(fp) Read an array header from a filelike object using the 2.0 file format version. read_magic(fp) Read the magic string to get the version of the file format. write_array(fp, array[, version, ...]) Write an array to an NPY file, including a header. write_array_header_1_0(fp, d) Write the header for an array using the 1.0 format. write_array_header_2_0(fp, d) Write the header for an array using the 2.0 format.
numpy.reference.generated.numpy.lib.format