% -*- latex -*-

\chapter{Array Handles}
\label{chap:ArrayHandle}

\index{array handle|(}

An \keyterm{array handle}, implemented with the \vtkmcont{ArrayHandle}
class, manages an array of data that can be accessed or manipulated by VTK-m
algorithms. It is typical to construct an array handle in the control
environment to pass data to an algorithm running in the execution
environment. It is also typical for an algorithm running in the execution
environment to allocate and populate an array handle, which can then be
read back in the control environment. It is also possible for an array
handle to manage data created by one VTK-m algorithm and passed to another,
remaining in the execution environment the whole time and never copied to
the control environment.

\begin{didyouknow}
  The array handle may have up to two copies of the array, one for the
  control environment and one for the execution environment. However,
  depending on the device and how the array is being used, the array handle
  will only have one copy when possible. Copies between the environments
  are implicit and lazy. They are copied only when an operation needs data
  in an environment where the data is not.
\end{didyouknow}

\vtkmcont{ArrayHandle} behaves like a shared smart pointer in that when the
C++ object is copied, each copy holds a reference to the same array. These
copies are reference counted so that when all copies of the
\vtkmcont{ArrayHandle} are destroyed, any allocated memory is released.

An \textidentifier{ArrayHandle} defines the following methods.

\begin{description}
\item[{\classmember[ArrayHandle]{GetNumberOfValues}}]
  Returns the number of entries in the array.
\item[{\classmember[ArrayHandle]{Allocate}}]
  Resizes the array to include the number of entries given.
  Any previously stored data might be discarded.
\item[{\classmember[ArrayHandle]{Shrink}}]
  Resizes the array to the number of entries given.
  Any data stored in the array is preserved.
  The number of entries must be less than those given in the last call to \classmember{Allocate}.
\item[{\classmember[ArrayHandle]{ReleaseResourcesExecution}}]
  If the \textidentifier{ArrayHandle} is holding any data on a device (such as a GPU), that memory is released to be used elsewhere.
  No data is lost from this call.
  Any data on the released resources is copied to the control environment (the local CPU) before the memory is released.
\item[{\classmember[ArrayHandle]{ReleaseResources}}]
  Releases all memory managed by this \textidentifier{ArrayHandle}.
  Any data in this memory is lost.
\item[{\classmember[ArrayHandle]{SyncControlArray}}]
  Makes sure any data in the execution environment is also available in the control environment.
  This method is useful when timing parallel algorithms and you want to include the time to transfer data between parallel devices and their hosts.
\item[{\classmember[ArrayHandle]{GetPortalControl}}]
  Returns an array portal that can be used to access the data in the array handle in the control environment.
  Array portals are described in Section~\ref{sec:ArrayPortals}.
\item[{\classmember[ArrayHandle]{GetPortalConstControl}}]
  Like \classmember{GetPortalControl} but returns a read-only array portal rather than a read/write array portal.
\item[{\classmember[ArrayHandle]{PrepareForInput}}]
  Readies the data as input to a parallel algorithm.
  See Section~\ref{sec:ArrayHandle:InterfaceToExecutionEnvironment} for more details.
\item[{\classmember[ArrayHandle]{PrepareForOutput}}]
  Readies the data as output to a parallel algorithm.
  See Section~\ref{sec:ArrayHandle:InterfaceToExecutionEnvironment} for more details.
\item[{\classmember[ArrayHandle]{PrepareForInPlace}}]
  Readies the data as input and output to a parallel algorithm.
  See Section~\ref{sec:ArrayHandle:InterfaceToExecutionEnvironment} for more details.
\item[{\classmember[ArrayHandle]{GetDeviceAdapterId}}]
  Returns a \vtkmcont{DeviceAdapterId} describing on which device adapter, if any, the array h
  andle's data is available.
  Device adapter ids are described in Section~\ref{sec:DeviceAdapterTraits}.
\item[{\classmember[ArrayHandle]{GetStorage}}]
  Returns the \vtkmcont{Storage} object that manages the data.
  The type of the storage object is defined by the storage tag template parameter of the \textidentifier{ArrayHandle}.
  Storage objects are described in detail in Chapter~\ref{chap:Storage}.
\end{description}


\section{Creating Array Handles}
\label{sec:CreatingArrayHandles}

\vtkmcont{ArrayHandle} is a templated class with two template parameters.
The first template parameter is the only one required and specifies the
base type of the entries in the array. The second template parameter
specifies the storage used when storing data in the control environment.
Storage objects are discussed later in Chapter~\ref{chap:Storage}, and for
now we will use the default value.

\begin{vtkmexample}{Declaration of the \protect\vtkmcont{ArrayHandle} templated class.}
template<
    typename T,
    typename StorageTag = VTKM_DEFAULT_STORAGE_TAG>
class ArrayHandle;
\end{vtkmexample}

There are multiple ways to create and populate an array handle. The default
\vtkmcont{ArrayHandle} constructor will create an empty array with nothing
allocated in either the control or execution environment. This is
convenient for creating arrays used as the output for algorithms.

\vtkmlisting{Creating an \textidentifier{ArrayHandle} for output data.}{CreateArrayHandle.cxx}

Constructing an \textidentifier{ArrayHandle} that points to a provided C array or
\textcode{std::vector} is straightforward with the
\vtkmcont{make\_ArrayHandle} functions. These functions will make an array
handle that points to the array data that you provide.

\vtkmlisting{Creating an \textidentifier{ArrayHandle} that points to a provided C array.}{ArrayHandleFromCArray.cxx}

\vtkmlisting[ex:ArrayHandleFromVector]{Creating an \textidentifier{ArrayHandle} that points to a provided \textcode{std::vector}.}{ArrayHandleFromVector.cxx}

\emph{Be aware} that \vtkmcont{make\_ArrayHandle} makes a shallow pointer
copy. This means that if you change or delete the data provided, the
internal state of \textidentifier{ArrayHandle} becomes invalid and
undefined behavior can ensue. The most common manifestation of this error
happens when a \textcode{std::vector} goes out of scope. This subtle
interaction will cause the \vtkmcont{ArrayHandle} to point to an
unallocated portion of the memory heap. For example, if the code in
Example~\ref{ex:ArrayHandleFromVector} where to be placed within a callable
function or method, it could cause the \vtkmcont{ArrayHandle} to become
invalid.

\begin{commonerrors}
  Because \textidentifier{ArrayHandle} does not manage data provided by
  \textidentifier{make\_ArrayHandle}, you should only use these as
  temporary objects. Example~\ref{ex:ArrayOutOfScope} demonstrates a method
  of copying one of these temporary arrays into safe managed memory, and
  Section~\ref{sec:ArrayHandle:Populate} describes how to put data directly
  into an \textidentifier{ArrayHandle} object.
\end{commonerrors}

\vtkmlisting[ex:ArrayOutOfScope]{Invalidating an \textidentifier{ArrayHandle} by letting the source \textcode{std::vector} leave scope.}{ArrayOutOfScope.cxx}


\section{Array Portals}
\label{sec:ArrayPortals}

\index{array portal|(}
\index{array handle!portal|(}

An array handle defines auxiliary structures called \keyterm{array portals}
that provide direct access into its data. An array portal is a simple
object that is somewhat functionally equivalent to an STL-type iterator, but
with a much simpler interface. Array portals can be read-only (const) or
read-write and they can be accessible from either the control environment
or the execution environment. All these variants have similar interfaces
although some features that are not applicable can be left out.

An array portal object contains each of the following:
\begin{description}
\item[\classmember{ValueType}] The type for each item in the array.
\item[\classmember{GetNumberOfValues}] A method that returns the number of
  entries in the array.
\item[\classmember{Get}] A method that returns the value at a given index.
\item[\classmember{Set}] A method that changes the value at a given
  index. This method does not need to exist for read-only (const) array
  portals.
\end{description}

The following code example defines an array portal for a simple C array of
scalar values. This definition has no practical value (it is covered by the
more general \vtkmcontinternal{ArrayPortalFromIterators}), but demonstrates
the function of each component.

\vtkmlisting{A simple array portal implementation.}{SimpleArrayPortal.cxx}

Although array portals are simple to implement and use, and array portals'
functionality is similar to iterators, there exists a great deal of code
already based on STL iterators and it is often convienient to interface
with an array through an iterator rather than an array portal. The
\vtkmcont{ArrayPortalToIterators} class can be used to convert an array
portal to an STL-compatible iterator. The class is templated on the array
portal type and has a constructor that accepts an instance of the array
portal. It contains the following features.
\begin{description}
\item[{\classmember[ArrayPortalToIterators]{IteratorType}}]
  The type of an STL-compatible random-access iterator that can provide the same access as the array portal.
\item[{\classmember[ArrayPortalToIterators]{GetBegin}}]
  A method that returns an STL-compatible iterator of type \classmember{IteratorType} that points to the beginning of the array.
\item[{\classmember[ArrayPortalToIterators]{GetEnd}}]
  A method that returns an STL-compatible iterator of type \classmember{IteratorType} that points to the end of the array.
\end{description}

\vtkmlisting{Using \textidentifier{ArrayPortalToIterators}.}{ArrayPortalToIterators.cxx}

As a convenience, \vtkmheader{vtkm/cont}{ArrayPortalToIterators.h} also
defines a pair of functions named \vtkmcont*{ArrayPortalToIteratorBegin}
and \vtkmcont*{ArrayPortalToIteratorEnd}
that each take an array portal as an
argument and return a begin and end iterator, respectively.

\vtkmlisting{Using \textidentifier{ArrayPortalToIteratorBegin} and \textidentifier{ArrayPortalToIteratorEnd}.}{ArrayPortalToIteratorBeginEnd.cxx}

\textidentifier{ArrayHandle} contains two internal type definitions for array
portal types that are capable of interfacing with the underlying data in
the control environment. These are \classmember{PortalControl}
and \classmember{PortalConstControl},
which define read-write and read-only (const)
array portals, respectively.

\textidentifier{ArrayHandle} also contains similar type definitions for
array portals in the execution environment. Because these types are
dependent on the device adapter used for execution, these type definitions are
embedded in a templated class named \classmember{ExecutionTypes}.
Within \classmember{ExecutionTypes} are the type definitions
\classmember{Portal} and \classmember{PortalConst} defining the read-write and
read-only (const) array portals, respectively, for the execution
environment for the given device adapter tag.

Because \vtkmcont{ArrayHandle} is control environment object, it provides the methods \classmember{GetPortalControl} and \classmember{GetPortalConstControl} to get the associated array portal objects.
These methods also have the side effect of refreshing the control environment copy of the data as if you called \classmember{SyncControlArray}.
%Be aware that when an \textidentifier{ArrayHandle} is created with a pointer or \textcode{std::vector}, it is put in a read-only mode, and \classmember{GetPortalControl} can fail (although \classmember{GetPortalConstControl} will still work).
Be aware that calling \classmember{GetPortalControl} will invalidate any copy in the execution environment, meaning that any subsequent use will cause the data to be copied back again.

\vtkmlisting{Using portals from an \textidentifier{ArrayHandle}.}{ControlPortals.cxx}

\begin{didyouknow}
  Most operations on arrays in VTK-m should really be done in the execution
  environment. Keep in mind that whenever doing an operation using a
  control array portal, that operation will likely be slow for large
  arrays. However, some operations, like performing file I/O, make sense in
  the control environment.
\end{didyouknow}

\index{array handle!portal|)}
\index{array portal|)}


\section{Allocating and Populating Array Handles}
\label{sec:ArrayHandle:Allocate}
\label{sec:ArrayHandle:Populate}

\index{array handle!allocate}
\index{Allocate}

\vtkmcont{ArrayHandle} is capable of allocating its own memory. The most
straightforward way to allocate memory is to call the \classmember[ArrayHandle]{Allocate}
method. The \classmember{Allocate} method takes a single argument, which is
the number of elements to make the array.

\vtkmlisting{Allocating an \textidentifier{ArrayHandle}.}{ArrayHandleAllocate.cxx}

\begin{commonerrors}
  The ability to allocate memory is a key difference between
  \textidentifier{ArrayHandle} and many other common forms of smart
  pointers. When one \textidentifier{ArrayHandle} allocates new memory, all
  other \textidentifier{ArrayHandle}s pointing to the same managed memory
  get the newly allocated memory. This can be particularly surprising when
  the originally managed memory is empty. For example, older versions of
  \textcode{std::vector} initialized all its values by setting them to the
  same object. When a \textcode{vector} of \textidentifier{ArrayHandle}s
  was created and one entry was allocated, all entries changed to the same
  allocation.
\end{commonerrors}

\index{array handle!populate}
\index{GetPortalControl}

Once an \textidentifier{ArrayHandle} is allocated, it can be populated by
using the portal returned from \classmember[ArrayHandle]{GetPortalControl}, as described in
Section~\ref{sec:ArrayPortals}. This is roughly the method used by the
readers in the I/O package (Chapter~\ref{chap:FileIO}).

\vtkmlisting{Populating a newly allocated \textidentifier{ArrayHandle}.}{ArrayHandlePopulate.cxx}


\section{Fancy Arrays}
\label{sec:ProvidedFancyArrays}
\label{sec:FancyArrays}

\index{array handle!fancy|(}
\index{fancy array handle|(}

One of the features of using \textidentifier{ArrayHandle}s is that they hide the implementation and layout of the array behind a generic interface.
This gives us the opportunity to replace a simple C array with some custom definition of the data and the code using the \textidentifier{ArrayHandle} is none the wiser.

This gives us the opportunity to implement \keyterm{fancy} arrays that do more than simply look up a value in an array.
For example, arrays can be augmented on the fly by mutating their indices or values.
Or values could be computed directly from the index so that no storage is required for the array at all.

VTK-m provides many of the fancy arrays, which we explore in this section.
Later in Chapter \ref{chap:Storage} we explore how to create custom arrays that adapt new memory layouts or augment other types of arrays.

\begin{didyouknow}
  One of the advantages of \VTKm's implementation of fancy arrays is that they can define whole arrays without actually storing and values.
  For example, \textidentifier{ArrayHandleConstant}, \textidentifier{ArrayHandleCounting}, and \textidentifier{ArrayHandleIndex} do not store data in any array in memory.
  Rather, they construct the value for an index at runtime.
  Likewise, arrays like \textidentifier{ArrayHandlePermute} construct new arrays from the values of other arrays without having to create a copy of the data.
\end{didyouknow}

\subsection{Constant Arrays}
\label{sec:ConstantArrays}

\index{array handle!constant|(}
\index{constant array handle|(}

A constant array is a fancy array handle that has the same value in all of
its entries. The constant array provides this array without actually using
any memory.

Specifying a constant array in VTK-m is straightforward. VTK-m has a class
named \vtkmcont{ArrayHandleConstant}. \textidentifier{ArrayHandleConstant}
is a templated class with a single template argument that is the type of
value for each element in the array. The constructor for
\textidentifier{ArrayHandleConstant} takes the value to provide by the
array and the number of values the array should present. The following
example is a simple demonstration of the constant array handle.

\vtkmlisting{Using \textidentifier{ArrayHandleConstant}.}{ArrayHandleConstant.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleConstant.h} header also contains the
templated convenience function \vtkmcont{make\_ArrayHandleConstant} that
takes a value and a size for the array. This function can sometimes be used
to avoid having to declare the full array type.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleConstant}.}{MakeArrayHandleConstant.cxx}

\index{constant array handle|)}
\index{array handle!constant|)}

\subsection{Counting Arrays}
\label{sec:CountingArrays}

\index{array handle!counting|(}
\index{counting array handle|(}

A counting array is a fancy array handle that provides a sequence of
numbers. These fancy arrays can represent the data without actually using
any memory.

\index{array handle!index|(}
\index{index array handle|(}

VTK-m provides two versions of a counting array. The first version is an
index array that provides a specialized but common form of a counting array
called an index array. An index array has values of type \vtkm{Id} that
start at 0 and count up by 1 (i.e. $0, 1, 2, 3,\ldots$). The index array
mirrors the array's index.

Specifying an index array in VTK-m is done with a class named
\vtkmcont{ArrayHandleIndex}. The constructor for
\textidentifier{ArrayHandleIndex} takes the size of the array to create.
The following example is a simple demonstration of the index array handle.

\vtkmlisting{Using \textidentifier{ArrayHandleIndex}.}{ArrayHandleIndex.cxx}

\index{index array handle|)}
\index{array handle!index|)}

The \vtkmcont{ArrayHandleCounting} class provides a more general form of
counting. \textidentifier{ArrayHandleCounting} is a templated class with a
single template argument that is the type of value for each element in the
array. The constructor for \textidentifier{ArrayHandleCounting} takes three
arguments: the start value (used at index 0), the step from one value to
the next, and the length of the array. The following example is a simple
demonstration of the counting array handle.

\vtkmlisting{Using \textidentifier{ArrayHandleCounting}.}{ArrayHandleCountingBasic.cxx}

\begin{didyouknow}
  In addition to being simpler to declare,
  \textidentifier{ArrayHandleIndex} is slightly faster than
  \textidentifier{ArrayHandleCounting}. Thus, when applicable, you should
  prefer using \textidentifier{ArrayHandleIndex}.
\end{didyouknow}

The \vtkmheader{vtkm/cont}{ArrayHandleCounting.h} header also contains the
templated convenience function \vtkmcont{make\_ArrayHandleCounting} that
also takes the start value, step, and length as arguments. This function
can sometimes be used to avoid having to declare the full array type.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleCounting}.}{MakeArrayHandleCountingBasic.cxx}

There are no fundamental limits on how \textidentifier{ArrayHandleCounting}
counts. For example, it is possible to count backwards.

\vtkmlisting{Counting backwards with \textidentifier{ArrayHandleCounting}.}{ArrayHandleCountingBackward.cxx}

It is also possible to use \textidentifier{ArrayHandleCounting} to make
sequences of \vtkm{Vec} values with piece-wise counting in each of the
components.

\vtkmlisting{Using \textidentifier{ArrayHandleCounting} with \protect\vtkm{Vec} objects.}{ArrayHandleCountingVec.cxx}

\index{counting array handle|)}
\index{array handle!counting|)}

\subsection{Cast Arrays}
\label{sec:CastArrays}

\index{array handle!cast|(}
\index{cast array handle|(}

A cast array is a fancy array that changes the type of the elements in an
array. The cast array provides this re-typed array without actually copying
or generating any data. Instead, casts are performed as the array is
accessed.

VTK-m has a class named \vtkmcont{ArrayHandleCast} to perform this implicit
casting. \textidentifier{ArrayHandleCast} is a templated class with two
template arguments. The first argument is the type to cast values to. The
second argument is the type of the original \textidentifier{ArrayHandle}.
The constructor to \textidentifier{ArrayHandleCast} takes the
\textidentifier{ArrayHandle} to modify by casting.

\vtkmlisting{Using \textidentifier{ArrayHandleCast}.}{ArrayHandleCast.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleCast.h} header also contains the
templated convenience function \vtkmcont{make\_ArrayHandleCast} that
constructs the cast array. The first argument is the original
\textidentifier{ArrayHandle} original array to cast. The optional second
argument is of the type to cast to (or you can optionally specify the
cast-to type as a template argument.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleCast}.}{MakeArrayHandleCast.cxx}

\index{cast array handle|)}
\index{array handle!cast|)}

\subsection{Discard Arrays}
\label{sec:DiscardArrays}

\index{discard array handle|(}
\index{array handle!discard|(}

It is sometimes the case where you will want to run an operation in \VTKm that fills values in two (or more) arrays, but you only want the values that are stored in one of the arrays.
It is possible to allocate space for both arrays and then throw away the values that you do not want, but that is a waste of memory.
It is also possible to rewrite the functionality to output only what you want, but that is a poor use of developer time.

To solve this problem easily, \VTKm provides \vtkmcont{ArrayHandleDiscard}.
This array behaves similar to a regular \textidentifier{ArrayHandle} in that it can be ``allocated'' and has size, but any values that are written to it are immediately discarded.
\textidentifier{ArrayHandleDiscard} takes up no memory.

\vtkmlisting{Using \textidentifier{ArrayHandleDiscard}.}{ArrayHandleDiscard.cxx}

\index{array handle!discard|)}
\index{discard array handle|)}


\subsection{Permuted Arrays}
\label{sec:PermutedArrays}

\index{array handle!permutation|(}
\index{permuted array handle|(}

A permutation array is a fancy array handle that reorders the elements in
an array. Elements in the array can be skipped over or replicated. The
permutation array provides this reordered array without actually coping any
data. Instead, indices are adjusted as the array is accessed.

Specifying a permutation array in VTK-m is straightforward. VTK-m has a
class named \vtkmcont{ArrayHandlePermutation} that takes two arrays: an
array of values and an array of indices that maps an index in the
permutation to an index of the original values. The index array is
specified first. The following example is a simple demonstration of the
permutation array handle.

\vtkmlisting{Using \textidentifier{ArrayHandlePermutation}.}{ArrayHandlePermutation.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandlePermutation.h} header also contains the
templated convenience function \vtkmcont{make\_ArrayHandlePermutation} that
takes instances of the index and value array handles and returns a
permutation array. This function can sometimes be used to avoid having to
declare the full array type.

\vtkmlisting{Using \textidentifier{make\_ArrayHandlePermutation}.}{MakeArrayHandlePermutation.cxx}

\begin{commonerrors}
  When using an \textidentifier{ArrayHandlePermutation}, take care that all
  the provided indices in the index array point to valid locations in the
  values array. Bad indices can cause reading from or writing to invalid
  memory locations, which can be difficult to debug.
\end{commonerrors}

\begin{didyouknow}
  You can write to a \textidentifier{ArrayHandlePermutation} by, for
  example, using it as an output array. Writes to the
  \textidentifier{ArrayHandlePermutation} will go to the respective
  location in the source array. However,
  \textidentifier{ArrayHandlePermutation} cannot be resized.
\end{didyouknow}

\index{permuted array handle|)}
\index{array handle!permutation|)}

\subsection{Zipped Arrays}
\label{sec:ZippedArrays}

\index{array handle!zip|(}
\index{zipped array handles|(}

A zip array is a fancy array handle that combines two arrays of the same
size to pair up the corresponding values. Each element in the zipped array
is a \vtkm{Pair} containing the values of the two respective arrays. These
pairs are not stored in their own memory space. Rather, the pairs are
generated as the array is used. Writing a pair to the zipped array writes
the values in the two source arrays.

Specifying a zipped array in VTK-m is straightforward. VTK-m has a class
named \vtkmcont{ArrayHandleZip} that takes the two arrays providing values
for the first and second entries in the pairs. The following example is a
simple demonstration of creating a zip array handle.

\vtkmlisting{Using \textidentifier{ArrayHandleZip}.}{ArrayHandleZip.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleZip.h} header also contains the
templated convenience function \vtkmcont{make\_ArrayHandleZip} that takes
instances of the two array handles and returns a zip array. This function
can sometimes be used to avoid having to declare the full array type.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleZip}.}{MakeArrayHandleZip.cxx}

\index{zipped array handles|)}
\index{array handle!zip|)}

\subsection{Coordinate System Arrays}
\label{sec:CoordinateSystemArrays}

Many of the data structures we use in VTK-m are described in a 3D
coordinate system. Although, as we will see in Chapter~\ref{chap:DataSets},
we can use any \textidentifier{ArrayHandle} to store point coordinates,
including a raw array of 3D vectors, there are some common patterns for
point coordinates that we can use specialized arrays to better represent
the data.

\index{array handle!uniform point coordinates|(}
\index{uniform point coordinates array handle|(}

There are two fancy array handles that each handle a special form of
coordinate system. The first such array handle is
\vtkmcont{ArrayHandleUniformPointCoordinates}, which represents a uniform
sampling of space. The constructor for
\textidentifier{ArrayHandleUniformPointCoordinates} takes three arguments.
The first argument is a \vtkm{Id3} that specifies the number of samples in
the $x$, $y$, and $z$ directions. The second argument, which is optional,
specifies the origin (the location of the first point at the lower left
corner). If not specified, the origin is set to $[0,0,0]$. The third
argument, which is also optional, specifies the distance between samples in
the $x$, $y$, and $z$ directions. If not specified, the spacing is set to
$1$ in each direction.

\vtkmlisting{Using \textidentifier{ArrayHandleUniformPointCoordinates}.}{ArrayHandleUniformPointCoordinates.cxx}

\index{uniform point coordinates array handle|)}
\index{array handle!uniform point coordinates|)}

\index{array handle!Cartesian product|(}
\index{array handle!rectilinear point coordinates|(}
\index{Cartesian product array handle|(}
\index{rectilinear point coordinates array handle|(}

The second fancy array handle for special coordinate systems is
\vtkmcont{ArrayHandleCartesianProduct}, which represents a rectilinear
sampling of space where the samples are axis aligned but have variable
spacing. Sets of coordinates of this type are most efficiently represented
by having a separate array for each component of the axis, and then for
each $[i,j,k]$ index of the array take the value for each component from
each array using the respective index. This is equivalent to performing a
Cartesian product on the arrays.

\textidentifier{ArrayHandleCartesianProduct} is a templated class. It has
three template parameters, which are the types of the arrays used for the
$x$, $y$, and $z$ axes. The constructor for
\textidentifier{ArrayHandleCartesianProduct} takes the three arrays.

\vtkmlisting{Using a \textidentifier{ArrayHandleCartesianProduct}.}{ArrayHandleCartesianProduct.cxx}

The \vtkmheader{vtkm/cont/ArrayHandleCartesianProduct.h} header also
contains the templated convenience function
\vtkmcont{make\_ArrayHandleCartesianProduct} that takes the three axis
arrays and returns an array of the Cartesian product. This function can
sometimes be used to avoid having to declare the full array type.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleCartesianProduct}.}{MakeArrayHandleCartesianProduct.cxx}

\index{rectilinear point coordinates array handle|)}
\index{Cartesian product array handle|)}
\index{array handle!rectilinear point coordinates|)}
\index{array handle!Cartesian product|)}

\begin{didyouknow}
  These specialized arrays for coordinate systems greatly reduce the code
  duplication in VTK-m. Most scientific visualization systems need separate
  implementations of algorithms for uniform, rectilinear, and unstructured
  grids. But in VTK-m an algorithm can be written once and then applied to
  all these different grid structures by using these specialized array
  handles and letting the compiler's templates optimize the code.
\end{didyouknow}

\subsection{Composite Vector Arrays}
\label{sec:CompositeVectorArrays}

\index{array handle!composite vector arrays|(}
\index{composite vector array handle|(}

A composite vector array is a fancy array handle that combines two to four
arrays of the same size and value type and combines their corresponding
values to form a \vtkm{Vec}. A composite vector array is similar in nature
to a zipped array (described in Section~\ref{sec:ZippedArrays}) except that
values are combined into \vtkm{Vec}s instead of \vtkm{Pair}s. The created
\vtkm{Vec}s are not stored in their own memory space. Rather, the
\textidentifier{Vec}s are generated as the array is used. Writing
\textidentifier{Vec}s to the composite vector array writes values into the
components of the source arrays.

A composite vector array can be created using the
\vtkmcont{ArrayHandleCompositeVector} class. This class has a variadic
template argument that is a ``signature'' for the arrays to be combined.
The constructor for \textidentifier{ArrayHandleCompositeVector} takes
instances of the array handles to combine.

\vtkmlisting{Using \textidentifier{ArrayHandleCompositeVector}.}{ArrayHandleCompositeVectorBasic.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleCompositeVector.h} header also
contains the templated convenience function
\vtkmcont{make\_ArrayHandleCompositeVector} which takes a variable number of array
handles and returns an \textidentifier{ArrayHandleCompositeVector}. This
function can sometimes be used to avoid having to declare the full array
type. \textidentifier{ArrayHandleCompositeVector} is also often used to combine
scalar arrays into vector arrays.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleCompositeVector}.}{MakeArrayHandleCompositeVector.cxx}

\index{composite vector array handle|)}
\index{array handle!composite vector arrays|)}

\subsection{Extract Component Arrays}
\label{sec:ExtractComponentArrays}

\index{array handle!extract component|(}
\index{extract component array handle|(}

Component extraction allows access to a single component of an \textidentifier{ArrayHandle} with a \vtkm{Vec} \classmember{ValueType}.
\vtkmcont{ArrayHandleExtractComponent} allows one component of a vector array to be extracted without creating a copy of the data.
\textidentifier{ArrayHandleExtractComponent} can also be combined with \textidentifier{ArrayHandleCompositeVector} (described in Section~\ref{sec:CompositeVectorArrays}) to arbitrarily stitch several components from multiple arrays together.

As a simple example, consider an \textidentifier{ArrayHandle} containing 3D coordinates for a collection of points and a filter that only operates on the points' elevations (Z, in this example).
We can easily create the elevation array on-the-fly without allocating a new array as in the following example.

\vtkmlisting{Extracting components of \textidentifier{Vec}s in an array with \textidentifier{ArrayHandleExtractComponent}.}{ArrayHandleExtractComponent.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleExtractComponent.h} header also contains the templated convenience function \vtkmcont{make\_ArrayHandleExtractComponent} that takes an \textidentifier{ArrayHandle} of \textidentifier{Vec}s and \vtkm{IdComponent} which returns an appropriately typed \textidentifier{ArrayHandleExtractComponent} containing the values for a specified component.
The index of the component to extract is provided as an argument to \textidentifier{make\_ArrayHandleExtractComponent}, which is required.
The use of \textidentifier{make\_ArrayHandleExtractComponent} can be used to avoid having to declare the full array type.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleExtractComponent}.}{MakeArrayHandleExtractComponent.cxx}

\index{extract component array handle|)}
\index{array handle!extract component|)}

\subsection{Swizzle Arrays}
\label{sec:SwizzleArrays}

\index{swizzle array handle|(}
\index{array handle!swizzle|(}

It is often useful to reorder or remove specific components from an \textidentifier{ArrayHandle} with a \vtkm{Vec} \classmember{ValueType}.
\vtkmcont{ArrayHandleSwizzle} provides an easy way to accomplish this.

The template parameters of ArrayHandleSwizzle specify a ``component map,'' which defines the swizzle operation.
This map consists of the components from the input \textidentifier{ArrayHandle}, which will be exposed in the ArrayHandleSwizzle.
For instance, \vtkmcont{ArrayHandleSwizzle}\tparams{Some3DArrayType, 3} with Some3DArray and \protect\vtkm{Vec}\tparams{\protect\vtkm{IdComponent}, 3}(0, 2, 1) as constructor arguments will allow access to a 3D array, but with the Y and Z components exchanged.
This rearrangement does not create a copy, and occurs on-the-fly as data are accessed through the \textidentifier{ArrayHandleSwizzle}'s portal.
This fancy array handle can also be used to eliminate unnecessary components from an \textidentifier{ArrayHandle}'s data, as shown below.

\vtkmlisting{Swizzling components of \textidentifier{Vec}s in an array with \textidentifier{ArrayHandleSwizzle}.}{ArrayHandleSwizzle.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleSwizzle.h} header also contains the templated convenience function \vtkmcont{make\_ArrayHandleSwizzle} that takes an \textidentifier{ArrayHandle} of \textidentifier{Vec}s and returns an appropriately typed \textidentifier{ArrayHandleSwizzle} containing swizzled vectors.
The indices of the swizzled components are provided as arguments to \textidentifier{make\_ArrayHandleSwizzle} after the \textidentifier{ArrayHandle}.
The use of \textidentifier{make\_ArrayHandleSwizzle} can be used to avoid having to declare the full array type.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleSwizzle}.}{MakeArrayHandleSwizzle.cxx}

\index{array handle!swizzle|)}
\index{swizzle array handle|)}

\subsection{Grouped Vector Arrays}
\label{sec:GroupedVectorArrays}

\index{array handle!group vector|(}
\index{group vector array handle|(}

A grouped vector array is a fancy array handle that groups consecutive
values of an array together to form a \vtkm{Vec}. The source array must be
of a length that is divisible by the requested \textidentifier{Vec} size.
The created \vtkm{Vec}s are not stored in their own memory space. Rather,
the \textidentifier{Vec}s are generated as the array is used. Writing
\textidentifier{Vec}s to the grouped vector array writes values into the
the source array.

A grouped vector array is created using the \vtkmcont{ArrayHandleGroupVec}
class. This templated class has two template arguments. The first argument
is the type of array being grouped and the second argument is an integer
specifying the size of the \textidentifier{Vec}s to create (the number of
values to group together).

\vtkmlisting{Using \textidentifier{ArrayHandleGroupVec}.}{ArrayHandleGroupVecBasic.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleGroupVec.h} header also contains the
templated convenience function \vtkmcont{make\_ArrayHandleGroupVec} that
takes an instance of the array to group into \textidentifier{Vec}s. You
must specify the size of the \textidentifier{Vec}s as a template parameter
when using \vtkmcont{make\_ArrayHandleGroupVec}.

\vtkmlisting{Using \textidentifier{make\_ArrayHandleGroupVec}.}{MakeArrayHandleGroupVec.cxx}

\textidentifier{ArrayHandleGroupVec} is handy when you need to build an array of vectors that are all of the same length, but what about when you need an array of vectors of different lengths?
One common use case for this is if you are defining a collection of polygons of different sizes (triangles, quadrilaterals, pentagons, and so on).
We would like to define an array such that the data for each polygon were stored in its own \textidentifier{Vec} (or, rather, \Veclike) object.
\vtkmcont{ArrayHandleGroupVecVariable} does just that.

\textidentifier{ArrayHandleGroupVecVariable} takes two arrays. The first array, identified as the ``source'' array, is a flat representation of the values (much like the array used with \textidentifier{ArrayHandleGroupVec}).
The second array, identified as the ``offsets'' array, provides for each vector the index into the source array where the start of the vector is.
The offsets array must be monotonically increasing.
The first and second template parameters to \textidentifier{ArrayHandleGroupVecVariable} are the types for the source and offset arrays, respectively.

It is often the case that you will start with a group of vector lengths rather than offsets into the source array.
If this is the case, then the \vtkmcont{ConvertNumComponentsToOffsets} helper function can convert an array of vector lengths to an array of offsets.
The first argument to this function is always the array of vector lengths.
The second argument, which is optional, is a reference to a \textidentifier{ArrayHandle} into which the offsets should be stored.
If this offset array is not specified, an \textidentifier{ArrayHandle} will be returned from the function instead.
The third argument, which is also optional, is a reference to a \vtkm{Id} into which the expected size of the source array is put.
Having the size of the source array is often helpful, as it can be used to allocate data for the source array or check the source array's size.
It is also OK to give the expected size reference but not the offset array reference.

\vtkmlisting{Using \textidentifier{ArrayHandleGroupVecVariable}.}{ArrayHandleGroupVecVariable.cxx}

The \vtkmheader{vtkm/cont}{ArrayHandleGroupVecVariable.h} header also contains the templated convenience function \vtkmcont{make\_ArrayHandleGroupVecVariable} that takes an instance of the source array to group into \Veclike objects and the offset array.

\vtkmlisting{Using \textidentifier{MakeArrayHandleGroupVecVariable}.}{MakeArrayHandleGroupVecVariable.cxx}

\begin{didyouknow}
  You can write to \textidentifier{ArrayHandleGroupVec} and \textidentifier{ArrayHandleGroupVecVariable} by, for example, using it as an output array.
  Writes to these arrays will go to the respective location in the source array.
  \textidentifier{ArrayHandleGroupVec} can also be allocated and resized (which in turn causes the source array to be allocated).
  However, \textidentifier{ArrayHandleGroupVecVariable} cannot be resized and the source array must be pre-allocated.
  You can use the source array size value returned from \textidentifier{ConvertNumComponentsToOffsets} to allocate source arrays.
\end{didyouknow}

\begin{commonerrors}
  Keep in mind that the values stored in a \textidentifier{ArrayHandleGroupVecVariable} are not actually \vtkm{Vec} objects.
  Rather, they are ``\Veclike'' objects, which has some subtle but important ramifications.
  First, the type will not match the \vtkm{Vec} template, and there is no automatic conversion to \vtkm{Vec} objects.
  Thus, many functions that accept \vtkm{Vec} objects as parameters will not accept the \Veclike object.
  Second, the size of \Veclike objects are not known until runtime.
  See Sections \ref{sec:VectorTypes} and \ref{sec:VectorTraits} for more information on the difference between \vtkm{Vec} and \Veclike objects.
\end{commonerrors}

\index{group vector array handle|)}
\index{array handle!group vector|)}


\section{Virtual Arrays}
\label{sec:VirtualArrays}
\label{sec:ArrayHandleVirtual}

\index{array handle!virtual|(}
\index{virtual array handle|(}

One of the complications that all the variations to array handle described in Section~\ref{sec:FancyArrays} introduces is that the actual type of the array might not be known.
That can be problematic when writing functions or methods that operate on arrays.
Often this issue can be resolved by simply making a templated argument that accepts any object that looks like an \textidentifier{ArrayHandle}.
\VTKm provides the macro \vtkmmacro{VTKM\_IS\_ARRAY\_HANDLE} to verify that a template type is in fact an array handle.

\vtkmlisting{Using templates for generic array handles.}{ArrayHandleTemplate.cxx}

However, in some cases using a template in this way is not feasible.
For example, what if you are calling a virtual method, which cannot be practically templated like this?
Or what if you need to store the arrays in a secondary object that cannot be practically templated on all possible array types?
Or what if you need to return an array handle, but you do not know the specific type of array handle until runtime?

\vtkmlisting{A problem that can occur when an array handle type is not known.}{ArrayHandleCastError.cxx}

To get around this problem, \VTKm provides the \vtkmcont{ArrayHandleVirtual} class.
\textidentifier{ArrayHandleVirtual} is a special type of array handle that can be wrapped around a \textidentifier{ArrayHandle}, any of the fancy array handles described in Section \ref{sec:FancyArrays}, or any other possible custom array that can be created.

\textidentifier{ArrayHandleVirtual} can be used like any other array handle.

\vtkmlisting{Using an \textidentifier{ArrayHandleVirtual}.}{UsingArrayHandleVirtual.cxx}

\begin{didyouknow}
  \textidentifier{ArrayHandleVirtual} can be used when you do not know what kind of array you are working with.
  However, you still need to know the type of value stored in the array (floating point, integer, vector, ect.).
  \vtkmcont{VariantArrayHandle}, described in Chapter \ref{chap:VariantArrayHandle}, can instead be used in the case where you do not know the type of values in the array.
\end{didyouknow}

The \textidentifier{ArrayHandleVirtual} class also comes with some special methods to work with types that are not known until runtime.

\begin{description}
\item[{\classmember[ArrayHandleVirtual]{NewInstance}}]
  Creates a new array of the same type.
\item[{\classmember[ArrayHandleVirtual]{IsType}}]
  Given an array handle type, returns true if the array stored in the \textidentifier{ArrayHandleVirtual} is the same type as the one given.
\item[{\classmember[ArrayHandleVirtual]{Cast}}]
  Given an array handle type, casts the array to that type and returns it.
  If the stored array is of the wrong type, and exception is thrown.
\end{description}

One common use case for querying the type stored in a \textidentifier{ArrayHandleVirtual} is to create ``fast paths'' for common types.
The following example demonstrates using casting to create a fast path for a basic \textidentifier{ArrayHandle} but also providing a fallback using the virtual interface, which may be slower due to calling virtual methods to get values.

\vtkmlisting{Casting a \textidentifier{ArrayHandleVirtual} to a known type.}{ArrayHandleVirtualCast.cxx}

\index{virtual array handle|)}
\index{array handle!virtual|)}



\section{Deep Array Copies}
\label{sec:DeepArrayCopies}

\index{deep array copy|(}
\index{array handle!deep copy|(}

As stated previously, an \textidentifier{ArrayHandle} object behaves as a smart pointer that copies references to the data without copying the data itself.
This is clearly faster and more memory efficient than making copies of the data itself and usually the behavior desired.
However, it is sometimes the case that you need to make a separate copy of the data.

To simplify copying the data, \VTKm comes with the \vtkmcont{ArrayCopy} convenience function defined in \vtkmheader{vtkm/cont}{ArrayCopy.h}.
\textidentifier{ArrayCopy} takes the array to copy from (the source) as its first argument and the array to copy to (the destination) as its second argument.
The destination array will be properly reallocated to the correct size.

\vtkmlisting[ex:ArrayCopy]{Using \textidentifier{ArrayCopy}.}{ArrayCopy.cxx}

\begin{didyouknow}
  \textidentifier{ArrayCopy} will copy data in parallel.
  If desired, you can specify the device as the third argument to \textidentifier{ArrayCopy} using either a device adapter tag or a runtime device tracker.
  Both the tags and tracker are described in Chapter~\ref{chap:DeviceAdapter}.
\end{didyouknow}

\index{array handle!deep copy|)}
\index{deep array copy|)}


\section{Compute Array Range}
\label{sec:ComputeArrayRange}

\index{range!array|(}
\index{array handle!range|(}
\index{array handle!minimum|(}
\index{array handle!maximum|(}

It is common to need to know the minimum and/or maximum values in an array.
To help find these values, \VTKm provides the \vtkmcont{ArrayRangeCompute} convenience function defined in \vtkmheader{vtkm/cont}{ArrayRangeCompute.h}.
\textidentifier{ArrayRangeCompute} simply takes an \textidentifier{ArrayHandle} on which to find the range of values.

If given an array with \vtkm{Vec} values, \textidentifier{ArrayRangeCompute} computes the range separately for each component of the \textidentifier{Vec}.
The return value for \textidentifier{ArrayRangeCompute} is \vtkmcont{ArrayHandle}\tparams{\vtkm{Range}}.
This returned array will have one value for each component of the input array's type.
So for example if you call \textidentifier{ArrayRangeCompute} on a \vtkmcont{ArrayHandle}\tparams{\vtkm{Id3}}, the returned array of \textidentifier{Range}s will have 3 values in it.
Of course, when \textidentifier{ArrayRangeCompute} is run on an array of scalar types, you get an array with a single value in it.

Each value of \vtkm{Range} holds the minimum and maximum value for that component.
The \textidentifier{Range} object is documented in Section~\ref{sec:Range}.

\vtkmlisting[ex:ArrayRangeCompute]{Using \textidentifier{ArrayRangeCompute}.}{ArrayRangeCompute.cxx}

\begin{didyouknow}
  \textidentifier{ArrayRangeCompute} will compute the minimum and maximum values in parallel.
  If desired, you can specify the parallel hardware device used for the computation as an optional second argument to \textidentifier{ArrayRangeCompute}.
  You can specify the device using a runtime device tracker, which is documented in Section~\ref{sec:RuntimeDeviceTracker}.
\end{didyouknow}

\index{array handle!maximum|)}
\index{array handle!minimum|)}
\index{array handle!range|)}
\index{range!array|)}


\section{Interface to Execution Environment}
\label{sec:ArrayHandle:InterfaceToExecutionEnvironment}

\index{array handle!execution environment|(}

One of the main functions of the array handle is to allow an array to be
defined in the control environment and then be used in the execution
environment. When using an \textidentifier{ArrayHandle} with filters or
worklets, this transition is handled automatically. However, it is also
possible to invoke the transfer for use in your own scheduled algorithms.

The \textidentifier{ArrayHandle} class manages the transition from control
to execution with a set of three methods that allocate, transfer, and ready
the data in one operation. These methods all start with the prefix
\textmethod{Prepare} and are meant to be called before some operation happens
in the execution environment. The methods are as follows.

\begin{description}
\item[{\classmember[ArrayHandle]{PrepareForInput}}]
  Copies data from the control to the execution environment, if necessary, and readies the data for read-only access.
\item[{\classmember[ArrayHandle]{PrepareForInPlace}}]
  Copies the data from the control to the execution environment, if necessary, and readies the data for both reading and writing.
\item[{\classmember[ArrayHandle]{PrepareForOutput}}]
  Allocates space (the size of which is given as a parameter) in the execution environment, if necessary, and readies the space for writing.
\end{description}

The \classmember{PrepareForInput} and \classmember{PrepareForInPlace} methods
each take a single argument that is the device adapter tag where execution
will take place (see Section~\ref{sec:DeviceAdapterTag} for more
information on device adapter tags). \classmember{PrepareForOutput} takes two
arguments: the size of the space to allocate and the device adapter tag.
Each of these methods returns an array portal that can be used in the
execution environment. \classmember{PrepareForInput} returns an object of type
\classmember[ArrayHandle]{ExecutionTypes}\tparams{\it{}DeviceAdapterTag}\textcode{:\colonhyp}\classmember{PortalConst}
whereas \textcode{PrepareForInPlace} and \textcode{PrepareForOutput} each
return an object of type
\classmember[ArrayHandle]{ExecutionTypes}\tparams{\it{}DeviceAdapterTag}\textcode{:\colonhyp}\classmember{Portal}.

Although these \textmethod{Prepare} methods are called in the control
environment, the returned array portal can only be used in the execution
environment. Thus, the portal must be passed to an invocation of the
execution environment. Typically this is done with a call to
\vtkmcont{Algorithm}[Schedule]. This and other
device adapter algorithms are described in detail in
Section~\ref{sec:DeviceAdapterAlgorithms}, but here is a quick example of
using these execution array portals in a simple functor.

\vtkmlisting{Using an execution array portal from an \textidentifier{ArrayHandle}.}{ExecutionPortals.cxx}
\fix{We should re-think this example.}

It should be noted that the array handle will expect any use of the
execution array portal to finish before the next call to any
\textidentifier{ArrayHandle} method. Since these \textmethod{Prepare} methods
are typically used in the process of scheduling an algorithm in the
execution environment, this is seldom an issue.

\begin{commonerrors}
  There are many operations on \textidentifier{ArrayHandle} that can
  invalidate the array portals, so do not keep them around indefinitely. It
  is generally better to keep a reference to the
  \textidentifier{ArrayHandle} and use one of the \textmethod{Prepare} each
  time the data are accessed in the execution environment.
\end{commonerrors}

\index{array handle!execution environment|)}

\index{array handle|)}
