Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Indexing

Array API specification for indexing arrays.

A conforming implementation of the array API standard must adhere to the following conventions.

Single-axis Indexing

To index a single array axis, an array must support standard Python indexing rules. Letn be the axis (dimension) size.

  • An integer index must be an object satisfyingoperator.index (e.g.,int).

  • Nonnegative indices must start at0 (i.e., zero-based indexing).

  • Valid nonnegative indices must reside on the half-open interval[0,n).

    Note

    This specification does not require bounds checking. The behavior for out-of-bounds integer indices is left unspecified.

  • Negative indices must count backward from the last array index, starting from-1 (i.e., negative-one-based indexing, where-1 refers to the last array index).

    Note

    A negative indexj is equivalent ton-j; the former is syntactic sugar for the latter, providing a shorthand for indexing elements that would otherwise need to be specified in terms of the axis (dimension) size.

  • Valid negative indices must reside on the closed interval[-n,-1].

    Note

    This specification does not require bounds checking. The behavior for out-of-bounds integer indices is left unspecified.

  • A negative indexj is related to a zero-based nonnegative indexi viai=n+j.

  • Colons: must be used forslices:start:stop:step, wherestart is inclusive andstop is exclusive.

    Note

    The specification does not support returning scalar (i.e., non-array) values from operations, including indexing. In contrast to standard Python indexing rules, for any index, or combination of indices, which select a single value, the result must be a zero-dimensional array containing the selected value.

Slice Syntax

The basic slice syntax isi:j:k wherei is the starting index,j is the stopping index, andk is the step (k!=0). A slice may contain either one or two colons, with either an integer value or nothing on either side of each colon. The following are valid slices.

A[:]A[i:]A[:j]A[i:k]A[::]A[i::]A[:j:]A[::k]A[i:j:]A[i::k]A[:j:k]A[i::k]A[i:j:k]

Note

Slice syntax can be equivalently achieved using the Python built-inslice() API. From the perspective ofA, the behavior ofA[i:j:k] andA[slice(i,j,k)] is indistinguishable (i.e., both retrieve the same set of items from__getitem__).

Using a slice to index a single array axis must selectm elements with index values

i,i+k,i+2k,i+3k,...,i+(m-1)k

where

m=q+r

andq andr (r!=0) are the quotient and remainder obtained by dividingj-i byk

j-i=qk+r

such that

j>i+(m-1)k

Note

Fori on the interval[0,n) (wheren is the axis size),j on the interval(0,n],i less thanj, and positive stepk, a starting indexi isalways included, while the stopping indexj isalways excluded. This preservesx[:i]+x[i:] always being equal tox.

Note

Using a slice to index into a single array axis should select the same elements as using a slice to index a Python list of the same size.

Slice syntax must have the following defaults. Letn be the axis (dimension) size.

  • Ifk is not provided (e.g.,0:10),k must equal1.

  • Ifk is greater than0 andi is not provided (e.g.,:10:2),i must equal0.

  • Ifk is greater than0 andj is not provided (e.g.,0::2),j must equaln.

  • Ifk is less than0 andi is not provided (e.g.,:10:-2),i must equaln-1.

  • Ifk is less than0 andj is not provided (e.g.,0::-2),j must equal-n-1.

Using a slice to index a single array axis must adhere to the following rules. Letn be the axis (dimension) size.

  • Ifi equalsj, a slice must return an empty array, whose axis (dimension) size along the indexed axis is0.

  • Indexing via: and:: must be equivalent and have defaults derived from the rules above. Both: and:: indicate to select all elements along a single axis (dimension).

    Note

    This specification does not require “clipping” out-of-bounds slice indices. This is in contrast to Python slice semantics where0:100 and0:10 are equivalent on a list of length10.

The following ranges for the start and stop values of a slice must be supported. Letn be the axis (dimension) size being sliced. For a slicei:j:k, the behavior specified above should be implemented for the following:

  • i orj omitted (None).

  • -n<=i<=n.

  • Fork>0 ork omitted (None),-n<=j<=n.

  • Fork<0,-n-1<=j<=max(0,n-1).

The behavior outside of these bounds is unspecified.

Note

Rationale: this is consistent with bounds checking for integer indexing; the behavior of out-of-bounds indices is left unspecified. Implementations may choose to clip (consistent with Pythonlistslicing semantics), raise an exception, return junk values, or some other behavior depending on device requirements and performance considerations.

Multi-axis Indexing

Multi-dimensional arrays must extend the concept of single-axis indexing to multiple axes by applying single-axis indexing rules along each axis (dimension) and supporting the following additional rules. LetN be the number of dimensions (“rank”) of a multi-dimensional arrayA.

  • Each axis may be independently indexed via single-axis indexing by providing a comma-separated sequence (“selection tuple”) of single-axis indexing expressions (e.g.,A[:,2:10,:,5]).

    Note

    In Python,A[(exp1,exp2,...,expN)] is equivalent toA[exp1,exp2,...,expN]; the latter is syntactic sugar for the former.

    Accordingly, ifA has rank1, thenA[(2:10,)] must be equivalent toA[2:10]. IfA has rank2, thenA[(2:10,:)] must be equivalent toA[2:10,:]. And so on and so forth.

  • Providing a single nonnegative integeri as a single-axis index must index the same elements as the slicei:i+1.

  • Providing a single negative integeri as a single-axis index must index the same elements as the slicen+i:n+i+1, wheren is the axis (dimension) size.

  • Providing a single integer as a single-axis index must reduce the number of array dimensions by1 (i.e., the array rank must decrease by one; ifA has rank2,rank(A)-1==rank(A[0,:])). In particular, a selection tuple with themth element an integer (and all other entries:) indexes a sub-array with rankN-1.

    Note

    When providing a single integer as a single-axis index to an array of rank1, the result should be an array of rank0, not a NumPy scalar. Note that this behavior differs from NumPy.

  • Providing a slice must retain array dimensions (i.e., the array rank must remain the same;rank(A)==rank(A[:])).

  • Providingellipsis must apply: to each dimension necessary to index all dimensions (e.g., ifA has rank4,A[1:,...,2:5]==A[1:,:,:,2:5]). Only a single ellipsis must be allowed. AnIndexError exception must be raised if more than one ellipsis is provided.

  • Providing an empty tuple or an ellipsis to an array of rank0 must result in an array of the same rank (i.e., ifA has rank0,A==A[()] andA==A[...]).

    Note

    This behavior differs from NumPy where providing an empty tuple to an array of rank0 returns a NumPy scalar.

  • EachNone in the selection tuple must expand the dimensions of the resulting selection by one dimension of size1. The position of the added dimension must be the same as the position ofNone in the selection tuple.

    Note

    Expanding dimensions can be equivalently achieved via repeated invocation ofexpand_dims().

    Note

    The constantnewaxis is an alias ofNone and can thus be used in a similar manner asNone.

  • Except in the case of providing a single ellipsis (e.g.,A[2:10,...] orA[1:,...,2:5]), the number of provided single-axis indexing expressions (excludingNone) should equalN. For example, ifA has rank2, a single-axis indexing expression should be explicitly provided for both axes (e.g.,A[2:10,:]). AnIndexError exception should be raised if the number of provided single-axis indexing expressions (excludingNone) is less thanN.

    Note

    Some libraries, such as SymPy, support flat indexing (i.e., providing a single-axis indexing expression to a higher-dimensional array). That practice is not supported here.

    To perform flat indexing, usereshape(x,(-1,))[integer].

  • AnIndexError exception must be raised if the number of provided single-axis indexing expressions (excludingNone) is greater thanN.

    Note

    This specification leaves unspecified the behavior of providing a slice which attempts to select elements along a particular axis, but whose starting index is out-of-bounds.

    Rationale: this is consistent with bounds-checking for single-axis indexing. An implementation may choose to set the axis (dimension) size of the result array to0, raise an exception, return junk values, or some other behavior depending on device requirements and performance considerations.

Integer Array Indexing

Note

Integer array indexing, as described in this specification, is a reduced subset of “vectorized indexing” semantics, as implemented in libraries such as NumPy. In vectorized indexing, integers and integer arrays are broadcasted to integer arrays having a common shape before being “zipped” together to form a list of index coordinates. This form of indexing diverges from the multi-axis indexing semantics described above (seeMulti-axis Indexing) where each element of an indexing tuple comprised of integers and slices independently indexes a particular axis. This latter form of indexing is commonly referred to as “orthogonal indexing” and is the default form of indexing outside of Python in languages such as Julia and MATLAB.

An array must support indexing by an indexing tuple which contains only integers and integer arrays according to the following rules. LetA be anN-dimensional array with shapeS1. LetT be a tuple(t1,t2,...,tN) having lengthN. Lettk be an individual element ofT.

Note

This specification does not currently address indexing tuples which combine slices and integer arrays. Behavior for such indexing tuples is left unspecified and thus implementation-defined. This may be revisited in a future revision of this standard.

Note

This specification does not currently address indexing tuples which include array-like elements, such as Python lists, tuples, and other sequences. Behavior when indexing an array using array-like elements is left unspecified and thus implementation-defined.

  • Iftk is an integer array,tk should have the default array index data type (seeDefault Data Types).

Note

Conforming implementations of this standard may support integer arrays having other integer data types; however, consumers of this standard should be aware that integer arrays having uncommon array index data types such asint8 anduint8 may not be widely supported as index arrays across conforming array libraries. To dynamically resolve the default array index data type, including for that of the current device context, use the inspection APIdefault_dtypes().

  • Providing a zero-dimensional integer arraytk containing an integer index must be equivalent to providing an integer index having the valueint(tk). Conversely, each integer indextk must be equivalent to a zero-dimensional integer array containing the same value and be treated as such, including shape inference and broadcasting. Accordingly, ifT consists of only integers and zero-dimensional integer arrays, the result must be equivalent to indexing multiple axes using integer indices. For example, ifA is a two-dimensional array,T is the tuple(i,J),i is a valid integer index, andJ is a zero-dimensional array containing a valid integer indexj, the result ofA[T] must be equivalent toA[(i,j)] (seeMulti-axis Indexing).

  • Iftk is an integer array, each element intk must independently satisfy the rules stated above for indexing a single-axis with an integer index (seeSingle-axis Indexing).

    Note

    This specification does not require bounds checking. The behavior for out-of-bounds integer indices is left unspecified.

  • Iftk is an integer array containing duplicate valid integer indices, the result must include the corresponding elements ofA with the same duplication.

  • IfT contains at least one non-zero-dimensional integer array, all elements ofT must be broadcast against each other to determine a common shapeS2=(s1,s2,...,sN) according to standard broadcasting rules (seeBroadcasting). If one or more elements inT are not broadcast-compatible with the others, an exception must be raised.

  • After broadcasting elements ofT to a common shapeS2, the resulting tupleU=(u1,u2,...,uN) must only contain integer arrays having shapeS2 (i.e.,u1=broadcast_to(t1,S2),u2=broadcast_to(t2,S2), et cetera).

  • Each element inU must specify a multi-dimensional indexv_i=(u1[i],u2[i],...,uN[i]), wherei ranges overS2. The result ofA[U] must be constructed by gathering elements fromA at each coordinate tuplev_i. For example, letA have shape(4,4) andU contain integer arrays equivalent to([0,1],[2,3]), withu1=[0,1] andu2=[2,3]. The resulting coordinate tuples must be(0,2) and(1,3), respectively, and the resulting array must have shape(2,) and contain elementsA[(0,2)] andA[(1,3)].

  • The result ofA[U] must be an array having the broadcasted shapeS2.

Boolean Array Indexing

Data-dependent output shape

For common boolean array use cases (e.g., using a dynamically-sized boolean array mask to filter the values of another array), the shape of the output array is data-dependent; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find boolean array indexing difficult to implement. Accordingly, such libraries may choose to omit boolean array indexing. SeeData-dependent output shapes section for more details.

An array must support indexing where thesole index is anM-dimensional boolean arrayB with shapeS1=(s1,...,sM) according to the following rules. LetA be anN-dimensional array with shapeS2=(s1,...,sM,...,sN).

Note

The prohibition against combining boolean array indices with other single-axis indexing expressions includes the use ofNone. To expand dimensions of the returned array, use repeated invocation ofexpand_dims().

  • IfN>=M, thenA[B] must replace the firstM dimensions ofA with a single dimension having a size equal to the number ofTrue elements inB. The values in the resulting array must be in row-major (C-style order); this is equivalent toA[nonzero(B)].

    Note

    For example, ifN==M==2, indexingA via a boolean arrayB will return a one-dimensional array whose size is equal to the number ofTrue elements inB.

  • IfN<M, then anIndexError exception must be raised.

  • The size of each dimension inB must equal the size of the corresponding dimension inA or be0, beginning with the first dimension inA. If a dimension size does not equal the size of the corresponding dimension inA and is not0, then anIndexError exception must be raised.

  • The elements of a boolean index array must be iterated in row-major, C-style order, with the exception of zero-dimensional boolean arrays.

  • A zero-dimensional boolean index array (equivalent toTrue orFalse) must follow the same axis replacement rules stated above. Namely, a zero-dimensional boolean index array removes zero dimensions and adds a single dimension of length1 if the index array’s value isTrue and of length0 if the index array’s value isFalse. Accordingly, for a zero-dimensional boolean index arrayB, the result ofA[B] has shapeS=(1,s1,...,sN) if the index array’s value isTrue and has shapeS=(0,s1,...,sN) if the index array’s value isFalse.

Return Values

The result of an indexing operation (e.g., multi-axis indexing, boolean array indexing, etc) must be an array of the same data type as the indexed array.

Note

The specified return value behavior includes indexing operations which return a single value (e.g., accessing a single element within a one-dimensional array).


[8]ページ先頭

©2009-2025 Movatter.jp