This submodule contains PyViennaCL’s core functionality, including types for representing and manipulating scalars, vectors and matrices on the host and compute device, with a variety of numerical data types (equivalent to the NumPy concept of dtype).
Also provided are routines for type conversion, arithmetic and linear algebra, to BLAS level 3. Vector and matrix types can be sensibly converted to and from NumPy arrays, and support for SciPy sparse matrix types is forth- coming.
Because in heterogeneous computing systems copying data across the bus from host memory to device memory (or vice versa) commonly incurs a proportionally substantial wait, PyViennaCL adopts a policy of delayed execution. Arithmetical expressions are represented as a binary tree, and are only dispatched to be computed when the result of the computation is necessary.
Thus, the result of adding two Matrix objects is not another Matrix object, but an Add object, which is converted to a Matrix when the result is accessed. Consequently, this submodule provides a number of classes for elementary arithmetical operations, such as Add, for representation in an expression tree. Each of these expression tree classes is a subclass of Node type, with Node providing basic functionality for the construction of the expression tree.
In the language of ViennaCL, ‘data’ classes such as Scalar, Vector and Matrix constitute leaves on the expression tree, and as such, each of these data classes inherits from the Leaf type, which provides general functionality for leaf construction.
Node and Leaf instances are flattened into a Statement object when the expression is executed. The Statement class recursively constructs the C++ object equivalent to the expression tree as represented in Python, and this is then dispatched to the compute device. The result is cached so that multiple identical computations are not made.
For the same reasons of bus and compute latency, PyViennaCL does not support the elementwise construction of Matrix or Vector objects, or the accessing of individual scalar elements from any such type; the waits incurred make such access painfully slow.
Instead, you must construct dense matrices and vectors using preconstructed types: NumPy array``s can be supplied to construct both matrices and vectors -- as long as the arrays are of the correct dimensionality -- and Python lists can be supplied to construct vectors, as long as the ``dtype of the list is comprehensible. Construction from lists, but not arrays, is supported if the element type is a PyViennaCL scalar type. In both the list case and the array case, you can use Python or NumPy numeric data types: NumPy ``dtype``s are recommended, since these are more explicit.
Elementwise accesses to array-like PyViennaCL types incur the computation of any expression, the transfer of the result to the host, the representation of that result as a NumPy ndarray (which may incur a large memory cost), and then the accessing of the element from that array.
The exception to this rule is the set of PyViennaCL sparse matrix types, which do support elementwise construction and access, because they are backed by a transparent host-memory cache which is only flushed to and from the device when necessary, in the manner of the delayed execution described above.
To force the execution of an expression or the flushing of a matrix, access the result attribute. To retrieve a NumPy array containing the data of the PyViennaCL Leaf or Node, use the as_ndarray() method. If you are not particularly concerned about the type of object you retrieve, access the value attribute: for PyViennaCL scalars, this provides a NumPy / Python scalar object; for vectors and matrices, it provides an appropriate NumPy array.
Ranges and slices of matrices and vectors are well supported, including the assignment of one matrix to a sub-matrix of another, as long as the matrix dimensions are commensurable. For instance:
>>> a[5:10, 5:10] = b
HostScalar | Represents a scalar in host memory |
Scalar | Represents a scalar in compute device memory |
Vector | Represents a vector in compute device memory |
CompressedMatrix | Represents a sparse matrix with compressed-row storage in compute device memory |
CoordinateMatrix | Represents a sparse matrix with a coordinate storage format in compute device memory |
ELLMatrix | Represents a sparse matrix with an ELL storage format in compute device memory |
HybridMatrix | Represents a sparse matrix with a hybrid storage format, combining ELL and compressed-row storage, in compute device memory |
Matrix | Represents a dense matrix, with either row-major (default) or column-major storage. |
Many operations are only currently supported using a floating poit numeric data type, but wider numeric support is forthcoming in later versions.
Norm_1 | Order-1 norm |
Norm_2 | Order-2 norm |
Norm_Inf | Infinity norm |
ElementAbs | Elementwise abs |
ElementAcos | Elementwise acos |
ElementAsin | Elementwise asin |
ElementAtan | Elementwise atan |
ElementCeil | Elementwise ceil |
ElementCos | Elementwise cos |
ElementCosh | Elementwise cosh |
ElementExp | Elementwise exp |
ElementFabs | Elementwise fabs |
ElementFloor | Elementwise floor |
ElementLog | Elementwise log |
ElementLog10 | Elementwise log10 |
ElementSin | Elementwise sin |
ElementSinh | Elementwise sinh |
ElementSqrt | Elementwise sqrt |
ElementTan | Elementwise tan |
ElementTanh | Elementwise tanh |
Trans | Matrix transpose |
Assign | Assign (copy) the values of one object to another of the same type. You can Assign across different matrix layouts. |
InplaceAdd | In-place addition |
InplaceSub | In-place subtraction |
Add | Addition (allocates returns a new object) |
Sub | Subtraction (allocates returns a new object) |
Mul | Multiplication: * Scalar by scalar -> scalar; * scalar by vector -> scaled vector; * scalar by matrix -> scaled matrix; * vector by vector -> undefined; * vector by matrix -> undefined; * matrix by vector -> matrix-vector product; * matrix by matrix -> matrix-matrix product. The concern in defining these semantics has been to preserve the dimensionality of the operands in the result. The Mul class does not map directly onto the * operator for every class. |
Div | Scalar division |
ElementProd | Elementwise scalar multiplication |
ElementDiv | Elementwise scalar division |
Dot | Inner (dot) product of two vectors |
Most of these expression classes are implicitly constructed by arithmetical convenience functions, including the standard Python arithmetic operators. For instance, for two commensurate objects a and b:
>>> ((a + b) == p.Add(a, b)).all()
True
For more information about the semantics of the arithmetic operators, such as , +, -, *, / and //, see the docstrings for the individual classes involved; for the default semantics, see the docstrings for the MagicMethods class.
The equality operator falls back to NumPy’s equal function for all classes that are not scalars, or that do not produce scalars as a result; in the scalar case, simple numerical equality is used.
Represent the addition of one object to another.
Represent the assignment (copy) of one object’s content to another.
For example: x = y is represented by Assign(x, y).
This class represents a sparse matrix on the ViennaCL compute device, in a compressed-row storage format.
For information on construction, see the help for SparseMatrixBase.
This class represents a sparse matrix on the ViennaCL compute device, in a coordinate storage format: entries are stored as triplets (i, j, val), where i is the row index, j is the column index and val is the entry.
For information on construction, see the help for SparseMatrixBase.
Represents the division of a Matrix or Vector by a scalar.
Represents the computation of the inner (dot) product of two vectors.
This class represents a sparse matrix on the ViennaCL compute device, in ELL storage format. In this format, the matrix is stored in a block of memory of size N by n_max, where N is the number of rows of the matrix and n_max is the maximum number of nonzeros per row. Rows with less than n_max entries are padded with zeros. In a second memory block, the respective column indices are stored.
The ELL format is well suited for matrices where most rows have approximately the same number of nonzeros. This is often the case for matrices arising from the discretization of partial differential equations using e.g. the finite element method. On the other hand, the ELL format introduces substantial overhead if the number of nonzeros per row varies a lot. [description adapted from the ViennaCL manual]
For information on construction, see the help for SparseMatrixBase.
Represent the elementwise computation of abs on an object.
Represent the elementwise computation of acos on an object.
Represent the elementwise computation of asin on an object.
Represent the elementwise computation of atan on an object.
Represent the elementwise computation of ceil on an object.
Represent the elementwise computation of cos on an object.
Represent the elementwise computation of cosh on an object.
Represents the elementwise multiplication of one object by another of the same type.
Represent the elementwise computation of exp on an object.
Represent the elementwise computation of fabs on an object.
Represent the elementwise computation of floor on an object.
Represent the elementwise computation of log (base e) on an object.
Represent the elementwise computation of log (base 10) on an object.
Represents the elementwise multiplication of one object by another of the same type.
Represent the elementwise computation of sin on an object.
Represent the elementwise computation of sinh on an object.
Represent the elementwise computation of sqrt on an object.
Represent the elementwise computation of tan on an object.
Represent the elementwise computation of tanh on an object.
This class is used to represent a host scalar: a scalar type that is stored in main CPU RAM, and that is usually represented using a standard NumPy scalar dtype, such as int32 or float64.
It derives from ScalarBase.
This class represents a sparse matrix on the ViennaCL compute device, in a hybrid storage format, combining the higher performance of the ELL format for matrices with approximately the same number of entries per row with the higher flexibility of the compressed row format. The main part of the matrix is stored in ELL format and excess entries are stored in compressed row format. [description adapted from the ViennaCL manual]
For information on construction, see the help for SparseMatrixBase.
Represent the computation of the in-place addition of one object to another.
Derives from Assign rather than directly from Node because in-place operations are mathematically similar to assignation.
Represent the computation of the in-place subtraction of one object to another.
Derives from Assign rather than directly from Node because in-place operations are mathematically similar to assignation.
This is the base class for all leaves in the ViennaCL expression tree system. A leaf is any type that can store data for use in an operation, such as a scalar, a vector, or a matrix.
Return a NumPy ndarray containing the data within the underlying ViennaCL type.
Construct a human-readable version of a ViennaCL expression tree statement from this leaf.
Override this function to implement caching functionality.
The result of an expression or subexpression consisting of a leaf is just the leaf itself.
The result_container_type for a leaf is always its own type.
Return a NumPy ndarray containing the data within the underlying ViennaCL type.
A class to provide convenience methods for arithmetic and BLAS access.
Classes derived from this will inherit lots of useful features applicable to PyViennaCL. For more information, see the individual methods below.
Returns a new instance of this class representing a new copy of this instance’s data.
Returns the elementwise division of self and rhs, for some rhs (right-hand side).
Returns the elementwise product of self and rhs, for some rhs (right-hand side).
Returns the elementwise product of self and rhs, for some rhs (right-hand side).
Returns a norm of this instance, if that is defined.
The norm returned depends on the ord parameter, as in SciPy. * If this instance is a Matrix, then ord must be None,
and the only norm supported is the Frobenius norm.
Returns (self * rhs).
This function should be overridden, with the following semantics.
None
This class represents a dense matrix object on the compute device, and it can be constructed in a number of ways: * with no parameters, as an empty matrix; * from an integer tuple: produces an empty Matrix of that shape; * from a tuple: first two values shape, third scalar value for each
element;
Both ROW_MAJOR and COL_MAJOR layouts are supported; to determine, provide layout as a keyword argument to the initialisation. The default layout is row-major.
Thus, to construct a 5-by-5 column-major Matrix instance with a numeric data type of float32 (C++ float) and each element being equal to 3.141, type:
>>> import pyviennacl as p
>>> mat = p.Matrix(10, 10, 3.141, dtype=p.float32, layout=p.COL_MAJOR)
>>> print(mat)
[[ 3.14100003 3.14100003 3.14100003 3.14100003 3.14100003]
[ 3.14100003 3.14100003 3.14100003 3.14100003 3.14100003]
[ 3.14100003 3.14100003 3.14100003 3.14100003 3.14100003]
[ 3.14100003 3.14100003 3.14100003 3.14100003 3.14100003]
[ 3.14100003 3.14100003 3.14100003 3.14100003 3.14100003]]
Return the matrix transpose.
Solve an eigenvalue problem for matrix A, with results depending on tag.
A : Matrix tag : eigenvalue computation tag instance
Must be one of * power_iter_tag * lanczos_tag See the help for each tag class for more information.
Solve the linear system expressed by A x = B for x.
Return the matrix transpose.
Represents the multiplication of one object by another.
The semantics are as follows: * Scalar by scalar -> scalar; * scalar by vector -> scaled vector; * scalar by matrix -> scaled matrix; * vector by vector -> undefined; * vector by matrix -> undefined; * matrix by vector -> matrix-vector product; * matrix by matrix -> matrix-matrix product.
The concern in defining these semantics has been to preserve the dimensionality of the operands in the result. The Mul class does not map directly onto the * operator for every class.
This no-op class is used to represent when some ViennaCL operation produces no explicit result, aside from any effects it may have on the operands.
For instance, in-place operations can return NoResult, as can Assign.
This is the base class for all nodes in the ViennaCL expression tree. A node is any binary or unary operation, such as addition. This class provides logic for expression tree construction and result type deduction, in order that expression statements can be executed correctly.
If you’re extending ViennaCL by adding an operation and want support for it in Python, then you should derive from this class.
Return the value of computing the operation represented by this Node as a NumPy ndarray.
The complexity of the ViennaCL expression, given as the number of Node instances in the expression tree.
Determine the dtype of the scalar element(s) of the result of the operation encoded by this Node, according to the NumPy type promotion rules.
Execute the expression tree taking this instance as the root, and then cache and return the result.
Produce a human readable representation of the expression graph including all nodes and leaves connected to this one, which constitutes the root node.
This function returns the correct function for setting the underlying ViennaCL statement_node object’s operand(s) in the correct way: each different container type and dtype are mapped onto a different set_operand_to function in the underlying object, in order to avoid type ambiguity at the Python/C++ interface.
Recursively determine the storage layout for the result type, if the result is a Matrix.
Notably, this ensures that any Matrix operands have the same layout, since this is a condition of all ViennaCL operations, except for the matrix-matrix product.
The result of computing the operation represented by this Node instance. Returns the cached result if there is one, otherwise executes the corresponding expression, caches the result, and returns that.
Determine the container type (ie, Scalar, Vector, etc) needed to store the result of the operation encoded by this Node. If the operation has some effect (eg, in-place), but does not produce a distinct result, then return NoResult. If the operation is not supported for the given operand types, then return None.
Determine the maximum size of any axis required to store the result of any operation on the given operands.
This can be overridden by the particular Node subclass, in order to compute the correct size for the result container.
Determine the maximum number of dimensions required to store the result of any operation on the given operands.
This can be overridden by the particular Node subclass, in order to compute the correct size for the result container.
Determine the upper-bound shape of the object needed to store the result of any operation on the given operands. The len of this tuple is the number of dimensions, with each element of the tuple determining the upper-bound size of the corresponding dimension.
If the shape is set manually, then this routine is overridden, and the manually set value is returned.
The value of the result of computing the operation represented by this Node; if the result is array-like, then the type is a NumPy ndarray, otherwise, a scalar is returned.
Represent the computation of the L^1-norm of a Vector.
Represent the computation of the L^2-norm of a Vector.
Represent the computation of the L^inf-norm of a Vector.
This class is used to represent a ViennaCL scalar: a scalar type that is usually stored in OpenCL global memory, but which can be converted to a HostScalar, and thence to a standard NumPy scalar dtype, such as int32 or float64.
It derives from ScalarBase.
This is the base class for all scalar types, regardless of their memory and backend context. It represents the dtype and the value of the scalar independently of one another.
Because scalars are leaves in the ViennaCL expression graph, this class derives from the Leaf base class.
Return a point-like ndarray containing only the value of this Scalar, with the dtype set accordingly.
Scalars are 0-dimensional and thus have no shape.
The stored value of the scalar.
This is the base class for all sparse matrix types, regardless of their storage format.
Because sparse matrices are leaves in the ViennaCL expression graph, this class derives from the Leaf base class. It is not expected that any instances of this class will be created, but instead its functionality is provided to derived sparse matrix types.
The specific sparse matrix subclass representing data on the compute device is not actually constructed until it is required; data is initially and transparently cached in RAM for speed of construction and access.
A sparse matrix instance can be constructed in a number of ways: * as an empty instance, with no parameters; * by passing a 2-tuple representing the shape or a 3-tuple representing
both the shape and the number of nonzeros, to pre-allocate memory;
Support for converting PyViennaCL sparse matrix types to and from SciPy sparse matrix types is not currently available, but is planned.
Returns the sparse matrix as a dense PyViennaCL Matrix.
Returns the sparse matrix as a dense NumPy ndarray.
Solve an eigenvalue problem for matrix A, with results depending on tag.
A : Matrix tag : eigenvalue computation tag instance
Must be one of * power_iter_tag * lanczos_tag See the help for each tag class for more information.
The number of nonzero elements stored in the matrix, as an integer.
A list of coordinates of the nonzero elements of the matrix.
The shape of the matrix as a 2-tuple, with one entry for each axis.
The flat size (area) of the matrix, as it would be in dense form.
The size of the first axis of the matrix.
The size of the second axis of the matrix.
Solve the linear system expressed by A x = B for x.
The underlying C++ ViennaCL object representing the matrix on the compute device.
Derived classes should construct and return the C++ object representing the appropriate sparse matrix on the compute device by overriding this function.
This class represents the ViennaCL statement corresponding to an expression graph. It employs type deduction information to calculate the resultant types, and generates the appropriate underlying ViennaCL C++ object.
Execute the statement – don’t do anything else – then return the result (if any).
Represent the subtraction of one object from another.
Represent the computation of the matrix transpose.
A generalised Vector class: represents ViennaCL vector objects of all supported scalar types. Can be constructed in a number of ways: * from an ndarray of the correct dtype * from a list * from an integer: produces an empty Vector of that size * from a tuple: first element an int (for size), second for scalar value
Also provides convenience functions for arithmetic.
Returns a representation of this instance as a column Matrix.
Returns a representation of this instance as a diagonal Matrix.
Returns a representation of this instance as a row Matrix.
Returns an expression representing the inner product of self and rhs: Dot(self, rhs).
Returns the index of the L^inf norm on the vector.
Returns an expression representing the inner product of self and rhs: Dot(self, rhs).
Returns the outer product of self and rhs.
rhs : Vector
result : Matrix
ViennaCL currently does not support outer product computation in the expression tree, so this forces the computation of rhs, if rhs represents a complex expression.
This class represents a C++ ViennaCL range or slice, as a ‘view’ on an object. A View instance is object-independent; i.e., it represents an abstract view.