Python API

Bohrium inherit must of the NumPy API – it is not all functions that are accelerated but they are all usable and can be found under the same name as in NumPy. The following is the part of the Bohrium API that is special to Bohrium.

Bohrium’s ndarray

class bohrium._bh.ndarray
all(axis=None, out=None)

Test whether all array elements along a given axis evaluate to True.

Refer to numpy.all for full documentation.

any(axis=None, out=None)

Test whether any array element along a given axis evaluates to True.

Refer to numpy.any for full documentation.

argmax(axis=None, out=None)

Returns the indices of the maximum values along an axis.

Refer to numpy.argmax for full documentation.

argmin(axis=None, out=None)

Returns the indices of the minimum values along an axis.

Refer to numpy.argmin for full documentation.

astype(dtype, order='C', subok=True, copy=True)

Copy of the array, cast to a specified type.

bhc_dynamic_view_info

The information regarding dynamic changes to a view within a do_while loop

bhc_mmap_allocated

Is the base data allocated with mmap?

conj(x[, out])

Return the complex conjugate, element-wise.

Refer to numpy.conj for full documentation.

conjugate(x[, out])

Return the complex conjugate, element-wise.

Refer to numpy.conj for full documentation.

copy(order='C')

Return a copy of the array.

copy2numpy()

Copy the array in C-style memory layout to a regular NumPy array

cumprod(axis=None, dtype=None, out=None)

Return the cumulative product of the array elements over the given axis

Refer to numpy.cumprod for full documentation.

cumsum(axis=None, dtype=None, out=None)

Return the cumulative sum of the array elements over the given axis.

Refer to bohrium.cumsum for full documentation.

dot(b, out=None)

Compute the dot product.

fill(value)

Fill the array with a scalar value.

flatten()

Return a copy of the array collapsed into one dimension.

max(axis=None, out=None)

Return the maximum along a given axis.

Refer to numpy.amax for full documentation.

mean(axis=None, dtype=None, out=None)

Compute the arithmetic mean along the specified axis.

min(axis=None, out=None)

Return the minimum along a given axis.

Refer to numpy.amin for full documentation.

prod(axis=None, dtype=None, out=None)

Return the product of the array elements over the given axis

Refer to numpy.prod for full documentation.

put(indices, values, mode='raise')

Set a.flat[n] = values[n] for all n in indices.

ravel()

Return a copy of the array collapsed into one dimension.

reshape(shape)

Returns an array containing the same data with a new shape.

Refer to bohrium.reshape for full documentation.

resize()

Change shape and size of array in-place

sum(axis=None, dtype=None, out=None)

Return the sum of the array elements over the given axis.

Refer to bohrium.sum for full documentation.

take()

a.take(indices, axis=None, out=None, mode=’raise’).

tofile(fid, sep="", format="%s")

Write array to a file as text or binary (default).

trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)

Return the sum along diagonals of the array.

Module contents

The module initialization of npbackend/bohrium imports and exposes all methods required to become a drop-in replacement for numpy.

bohrium.flush()

Evaluate all delayed array operations

bohrium.array(obj, dtype=None, copy=False, order=None, subok=False, ndmin=0, bohrium=True)

Create an array – Bohrium or NumPy ndarray.

Parameters:
obj : array_like

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.

dtype : data-type, optional

The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.

copy : bool, optional

If true, then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

order : {‘C’, ‘F’, ‘A’}, optional

Specify the order of the array. If order is ‘C’ (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is ‘F’, then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is ‘A’, then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous).

subok : bool, optional

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).

ndmin : int, optional

Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.

bohrium : boolean, optional

Determines whether it is a Bohrium array (bohrium.ndarray) or a regular NumPy array (numpy.ndarray)

Returns:
out : ndarray

An array object satisfying the specified requirements.

See also

empty, empty_like, zeros, zeros_like, ones, ones_like, fill

Examples

>>> np.array([1, 2, 3])
array([1, 2, 3])

Upcasting:

>>> np.array([1, 2, 3.0])
array([ 1.,  2.,  3.])

More than one dimension:

>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
       [3, 4]])

Minimum dimensions 2:

>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])

Type provided:

>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j,  2.+0.j,  3.+0.j])

Data-type consisting of more than one element:

>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])

Creating an array from sub-classes:

>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
       [3, 4]])
>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
        [3, 4]])

bohrium.backend_messaging module

Send and receive a message through the Bohrium component stack

bohrium.backend_messaging.cuda_use_current_context()

Tell the CUDA backend to use the current CUDA context (useful for PyCUDA interop)

bohrium.backend_messaging.gpu_disable()

Disable the GPU backend in the current runtime stack

bohrium.backend_messaging.gpu_enable()

Enable the GPU backend in the current runtime stack

bohrium.backend_messaging.runtime_info()

Return a YAML string describing the current Bohrium runtime

bohrium.backend_messaging.statistic()

Return a YAML string of Bohrium statistic

bohrium.backend_messaging.statistic_enable_and_reset()

Reset and enable the Bohrium statistic

bohrium.bhary module

This module consist of bohrium.ndarray methods

The functions here serve as a means to determine whether a given array is a numpy.ndarray or a bohrium.ndarray as well as moving between the two “spaces”.

— License — This file is part of Bohrium and copyright (c) 2012 the Bohrium http://bohrium.bitbucket.org

Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

Bohrium is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.

bohrium.bhary.check()

Returns True if ‘ary’ is a Bohrium array

bohrium.bhary.check_biclass_bh_over_np()

Returns True if ‘ary’ is a Bohrium view with a NumPy base array

bohrium.bhary.check_biclass_np_over_bh()

Returns True if ‘ary’ is a NumPy view with a Bohrium base array

bohrium.bhary.fix_biclass()

Makes sure that when ‘ary’ or its base is a Bohrium array, both of them are.

bohrium.bhary.fix_biclass_wrapper()

Function decorator that makes sure that the function doesn’t reads or writes biclass arrays

bohrium.bhary.get_base()

Get the final base array of ‘ary’.

bohrium.bhary.is_base()

Return True when ‘ary’ is a base array.

bohrium.blas module

Basic Linear Algebra Subprograms (BLAS)

Utilize BLAS directly from Python

bohrium.blas.gemm(a, b, alpha=1.0, c=None, beta=0.0)

C := alpha * A * B + beta * C

bohrium.blas.gemmt(a, b, alpha=1.0, c=None, beta=0.0)

C := alpha * A^T * B + beta * C

bohrium.blas.hemm(a, b, alpha=1.0, c=None, beta=0.0)

C := alpha * A * B + beta * C

bohrium.blas.her2k(a, b, alpha=1.0, c=None, beta=0.0)

C := alpha * A * B**H + conjg(alpha) * B * A**H + beta * C

bohrium.blas.herk(a, alpha=1.0, c=None, beta=0.0)

C := alpha * A * A**H + beta * C

bohrium.blas.symm(a, b, alpha=1.0, c=None, beta=0.0)

C := alpha * A * B + beta * C

bohrium.blas.syr2k(a, b, alpha=1.0, c=None, beta=0.0)

C := alpha * A * B**T + alpha * B * A**T + beta * C

bohrium.blas.syrk(a, alpha=1.0, c=None, beta=0.0)

C := alpha * A * A**T + beta * C

bohrium.blas.trmm(a, b, alpha=1.0)

B := alpha * A * B

bohrium.blas.trsm(a, b)

Solves: A * X = B

bohrium.concatenate module

Array concatenate functions

bohrium.concatenate.atleast_1d(*arys)

Convert inputs to arrays with at least one dimension.

Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

Parameters:
arys1, arys2, … : array_like

One or more input arrays.

Returns:
ret : ndarray

An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.

Examples

>>> np.atleast_1d(1.0)
array_create.array([ 1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array_create.array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])
>>> np.atleast_1d(x) is x
True
>>> np.atleast_1d(1, [3, 4])
[array_create.array([1]), array_create.array([3, 4])]
bohrium.concatenate.atleast_2d(*arys)

View inputs as arrays with at least two dimensions.

Parameters:
arys1, arys2, … : array_like

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

Returns:
res, res2, … : ndarray

An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.

Examples

>>> np.atleast_2d(3.0)
array_create.array([[ 3.]])
>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array_create.array([[ 0.,  1.,  2.]])
>>> np.atleast_2d(x).base is x
True
>>> np.atleast_2d(1, [1, 2], [[1, 2]])
[array_create.array([[1]]), array_create.array([[1, 2]]), array_create.array([[1, 2]])]
bohrium.concatenate.atleast_3d(*arys)

View inputs as arrays with at least three dimensions.

Parameters:
arys1, arys2, … : array_like

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

Returns:
res1, res2, … : ndarray

An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

Examples

>>> np.atleast_3d(3.0)
array_create.array([[[ 3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x.base  # x is a reshape, so not base itself
True
>>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
...     print(arr, arr.shape)
...
[[[1]
  [2]]] (1, 2, 1)
[[[1]
  [2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2)
bohrium.concatenate.concatenate((a1, a2, ...), axis=0)

Join a sequence of arrays along an existing axis.

Parameters:
a1, a2, … : sequence of array_like

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

axis : int, optional

The axis along which the arrays will be joined. Default is 0.

Returns:
res : ndarray

The concatenated array.

See also

ma.concatenate
Concatenate function that preserves input masks.
array_split
Split an array into multiple sub-arrays of equal or near-equal size.
split
Split array into a list of multiple sub-arrays of equal size.
hsplit
Split array into multiple sub-arrays horizontally (column wise)
vsplit
Split array into multiple sub-arrays vertically (row wise)
dsplit
Split array into multiple sub-arrays along the 3rd axis (depth).
stack
Stack a sequence of arrays along a new axis.
hstack
Stack arrays in sequence horizontally (column wise)
vstack
Stack arrays in sequence vertically (row wise)
dstack
Stack arrays in sequence depth wise (along third dimension)

Notes

When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead.

Examples

>>> a = np.array_create.array([[1, 2], [3, 4]])
>>> b = np.array_create.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array_create.array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array_create.array([[1, 2, 5],
       [3, 4, 6]])

This function will not preserve masking of MaskedArray inputs.

>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data = [0 -- 2],
             mask = [False  True False],
       fill_value = 999999)
>>> b
array_create.array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data = [0 1 2 2 3 4],
             mask = False,
       fill_value = 999999)
>>> np.ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],
             mask = [False  True False False False False],
       fill_value = 999999)
bohrium.concatenate.hstack(tup)

Stack arrays in sequence horizontally (column wise).

Take a sequence of arrays and stack them horizontally to make a single array. Rebuild arrays divided by hsplit.

This function continues to be supported for backward compatibility, but you should prefer np.concatenate or np.stack. The np.stack function was added in NumPy 1.10.

Parameters:
tup : sequence of ndarrays

All arrays must have the same shape along all but the second axis.

Returns:
stacked : ndarray

The array formed by stacking the given arrays.

See also

stack
Join a sequence of arrays along a new axis.
vstack
Stack arrays in sequence vertically (row wise).
dstack
Stack arrays in sequence depth wise (along third axis).
concatenate
Join a sequence of arrays along an existing axis.
hsplit
Split array along second axis.

Notes

Equivalent to np.concatenate(tup, axis=1)

Examples

>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array_create.array([1, 2, 3, 2, 3, 4])
>>> a = np.array_create.array([[1],[2],[3]])
>>> b = np.array_create.array([[2],[3],[4]])
>>> np.hstack((a,b))
array_create.array([[1, 2],
       [2, 3],
       [3, 4]])
bohrium.concatenate.stack(arrays, axis=0)

Join a sequence of arrays along a new axis.

The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

New in version 1.10.0.

Parameters:
arrays : sequence of array_like

Each array must have the same shape.

axis : int, optional

The axis in the result array along which the input arrays are stacked.

Returns:
stacked : ndarray

The stacked array has one more dimension than the input arrays.

See also

concatenate
Join a sequence of arrays along an existing axis.
split
Split array into a list of multiple sub-arrays of equal size.

Examples

>>> arrays = [np.random.randn(3, 4) for _ in range(10)]
>>> np.stack(arrays, axis=0).shape
(10, 3, 4)
>>> np.stack(arrays, axis=1).shape
(3, 10, 4)
>>> np.stack(arrays, axis=2).shape
(3, 4, 10)
>>> a = np.array_create.array([1, 2, 3])
>>> b = np.array_create.array([2, 3, 4])
>>> np.stack((a, b))
array_create.array([[1, 2, 3],
       [2, 3, 4]])
>>> np.stack((a, b), axis=-1)
array_create.array([[1, 2],
       [2, 3],
       [3, 4]])
bohrium.concatenate.vstack(tup)

Stack arrays in sequence vertically (row wise).

Take a sequence of arrays and stack them vertically to make a single array. Rebuild arrays divided by vsplit.

This function continues to be supported for backward compatibility, but you should prefer np.concatenate or np.stack. The np.stack function was added in NumPy 1.10.

Parameters:
tup : sequence of ndarrays

Tuple containing arrays to be stacked. The arrays must have the same shape along all but the first axis.

Returns:
stacked : ndarray

The array formed by stacking the given arrays.

See also

stack
Join a sequence of arrays along a new axis.
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays along an existing axis.
vsplit
Split array into a list of multiple sub-arrays vertically.

Notes

Equivalent to np.concatenate(tup, axis=0) if tup contains arrays that are at least 2-dimensional.

Examples

>>> a = np.array_create.array([1, 2, 3])
>>> b = np.array_create.array([2, 3, 4])
>>> np.vstack((a,b))
array_create.array([[1, 2, 3],
       [2, 3, 4]])
>>> a = np.array_create.array([[1], [2], [3]])
>>> b = np.array_create.array([[2], [3], [4]])
>>> np.vstack((a,b))
array_create.array([[1],
       [2],
       [3],
       [2],
       [3],
       [4]])

bohrium.contexts module

Bohrium Contexts

class bohrium.contexts.DisableBohrium

Disable Bohrium within the context

class bohrium.contexts.DisableGPU

Disable the GPU backend within the context.

class bohrium.contexts.EnableBohrium

Enable Bohrium within the context

class bohrium.contexts.Profiling

Profiling the Bohrium backends within the context.

bohrium.interop_numpy module

Interop NumPy

bohrium.interop_numpy.get_array(bh_ary)

Return a NumPy array wrapping the memory of the Bohrium array ary.

Parameters:
bh_ary : ndarray (Bohrium array)

Must be a Bohrium base array

Returns:
out : ndarray (regular NumPy array)

Notes

Changing or deallocating bh_ary invalidates the returned NumPy array!

bohrium.interop_pycuda module

Interop PyCUDA

bohrium.interop_pycuda.available()

Is CUDA available?

bohrium.interop_pycuda.get_gpuarray(bh_ary)

Return a PyCUDA GPUArray object that points to the same device memory as bh_ary.

Parameters:
bh_ary : ndarray (Bohrium array)

Must be a Bohrium base array

Returns:
out : GPUArray

Notes

Changing or deallocating bh_ary invalidates the returned GPUArray array!

bohrium.interop_pycuda.init()

Initiate the PyCUDA module. Must be called before any other PyCUDA calls and preferable also before any Bohrium operations

bohrium.interop_pycuda.max_local_memory(cuda_device=None)

Returns the maximum allowed local memory (memory per block) on cuda_device. If cuda_device is None, use current device

bohrium.interop_pycuda.type_np2cuda_str(np_type)

Converts a NumPy type to a CUDA type string

bohrium.interop_pyopencl module

Interop PyOpenCL

bohrium.interop_pyopencl.available()

Is PyOpenCL available?

bohrium.interop_pyopencl.get_buffer(bh_ary)

Return a OpenCL Buffer object wrapping the Bohrium array ary.

Parameters:
bh_ary : ndarray (Bohrium array)

Must be a Bohrium base array

Returns:
out : pyopencl.Buffer

Notes

Changing or deallocating bh_ary invalidates the returned pyopencl.Buffer!

bohrium.interop_pyopencl.get_context()

Return a PyOpenCL context

bohrium.interop_pyopencl.kernel_info(opencl_kernel, queue)

Info about the opencl_kernel Returns 4-tuple:

  • Max work-group size
  • Recommended work-group multiple
  • Local mem used by kernel
  • Private mem used by kernel
bohrium.interop_pyopencl.max_local_memory(opencl_device)

Returns the maximum allowed local memory on opencl_device

bohrium.interop_pyopencl.set_buffer(bh_ary, buffer)

Assign a OpenCL Buffer object to a Bohrium array ary.

Parameters:
bh_ary : ndarray (Bohrium array)

Must be a Bohrium base array

buffer : pyopencl.Buffer

The PyOpenCL device buffer

bohrium.interop_pyopencl.type_np2opencl_str(np_type)

Converts a NumPy type to a OpenCL type string

bohrium.linalg module

LinAlg

Common linear algebra functions

bohrium.linalg.gauss

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.lu

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.solve

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.jacobi

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.matmul

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.dot

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.norm

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.tensordot

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.solve_tridiagonal

Invokes ‘func’ and strips “biclass” from the result.

bohrium.linalg.cg

Invokes ‘func’ and strips “biclass” from the result.

bohrium.loop module

Bohrium Loop

class bohrium.loop.DynamicViewInfo(dynamic_changes, shape, stride, resets={})

Bases: object

Object for storing information about dynamic changes to the view

Methods

add_dynamic_change(self, dim, slide, …[, …]) Add dynamic changes to the dynamic changes information of the view.
changes_in_dim(self, dim) Returns a list of all dynamic changes in a dimension.
dim_shape_change(self, dim) Returns the summed shape change in the given dimension.
dims_with_changes(self) Returns a list of all dimensions with dynamic changes.
get_shape_changes(self) Returns a dictionary of all changes to the shape.
has_changes(self) Returns whether the object contains any dynamic changes.
has_changes_in_dim(self, dim) Check whether there are any dynamic changes in the given dimension.
index_into(self, dvi) Modifies the dynamic change such that is reflects being indexed into another view with dynamic changes.
add_dynamic_change(self, dim, slide, shape_change, step_delay, shape=None, stride=None)

Add dynamic changes to the dynamic changes information of the view.

Parameters:
dim : int

The relevant dimension

slide : int

The change to the offset in the given dimension (can be both positive and negative)

shape_change : int

The amount the shape changes in the given dimension (can also be both positive and negative)

step_delay : int

If the change is based on an iterator in a grid, it is the changes can be delayed until the inner iterators have been updated step_delay times.

shape : int

The shape that the view can slide within. If not given, self.shape[dim] is used instead

stride : int

The stride that the view can slide within. If not given, self.stride[dim] is used instead

changes_in_dim(self, dim)

Returns a list of all dynamic changes in a dimension. If the dimension does not contain any dynamic changes, an empty list is returned.

Parameters:
dim : int

The relevant dimension

dim_shape_change(self, dim)

Returns the summed shape change in the given dimension.

Parameters:
dim : int

The relevant dimension

dims_with_changes(self)

Returns a list of all dimensions with dynamic changes.

get_shape_changes(self)

Returns a dictionary of all changes to the shape. The dimension is the key and the shape change in the dimension is the value.

has_changes(self)

Returns whether the object contains any dynamic changes.

has_changes_in_dim(self, dim)

Check whether there are any dynamic changes in the given dimension.

Parameters:
dim : int

The relevant dimension

index_into(self, dvi)

Modifies the dynamic change such that is reflects being indexed into another view with dynamic changes.

Parameters:
dim : DynamicViewInfo

The infomation about dynamic changes within the view which is indexed into

class bohrium.loop.Iterator(max_iter, value, step_delay=1, reset=None)

Bases: object

Iterator used for sliding views within loops.

Notes

Supports addition, subtraction and multiplication.

exception bohrium.loop.IteratorIllegalBroadcast(dim, a_shape, a_shape_change, bcast_shape, bcast_shape_change)

Bases: exceptions.Exception

Exception thrown when a view consists of a mix of iterator depths.

exception bohrium.loop.IteratorIllegalDepth

Bases: exceptions.Exception

Exception thrown when a view consists of a mix of iterator depths.

exception bohrium.loop.IteratorOutOfBounds(dim, shape, first_index, last_index)

Bases: exceptions.Exception

Exception thrown when a view goes out of bounds after the maximum iterations.

bohrium.loop.add_slide_info(a)
Checks whether a view is dynamic and adds the relevant
information to the view structure within BXX if it is.
Parameters:
a : array view

A view into an array

bohrium.loop.do_while(func, niters, *args, **kwargs)

Repeatedly calls the func with the *args and **kwargs as argument.

The func is called while func returns True or None and the maximum number of iterations, niters, hasn’t been reached.

Parameters:
func : function

The function to run in each iterations. func can take any argument and may return a boolean bharray with one element.

niters: int or None

Maximum number of iterations in the loop (number of times func is called). If None, there is no maximum.

*args, **kwargs : list and dict

The arguments to func

Notes

func can only use operations supported natively in Bohrium.

Examples

>>> def loop_body(a):
...     a += 1
>>> a = bh.zeros(4)
>>> bh.do_while(loop_body, 5, a)
>>> a
array([5, 5, 5, 5])
>>> def loop_body(a):
...     a += 1
...     return bh.sum(a) < 10
>>> a = bh.zeros(4)
>>> bh.do_while(loop_body, None, a)
>>> a
array([3, 3, 3, 3])
bohrium.loop.get_grid(max_iter, *args)

Returns n iterators in a grid, corresponding to nested loops.

Parameters:
args : pointer to two or more integers

The first integer is the maximum iterations of the loop, used for checking boundaries. The rest are the shape of the grid.

Notes

get_grid can only be used within a bohrium loop function. Within the loop max_iter is set by a lambda function. There are no upper bound on the amount of grid values.

Examples

>>> def kernel(a):
...     i, j, k = get_grid(3,3,3)
...     a[i,j,k] += 1

correspondes to

>>> for i in range(3):
...     for j in range(3):
...         for k in range(3):
...             a[i,j,k] += 1
bohrium.loop.get_iterator(max_iter, val, step_delay=1)
Returns an iterator with a given starting value. An iterator behaves like
an integer, but is used to slide view between loop iterations.
Parameters:
max_iter : int

The maximum amount of iterations of the loop. Used for checking boundaries.

val : int

The initial value of the iterator.

Notes

get_iterator can only be used within a bohrium loop function. Within the loop max_iter is set by a lambda function. This is also the case in the example.

Examples

>>> def kernel(a):
...     i = get_iterator(1)
...     a[i] *= a[i-1]
>>> a = bh.arange(1,6)
>>> bh.do_while(kernel, 4, a)
array([1, 2, 6, 24, 120])
bohrium.loop.has_iterator(*s)

Checks whether a (multidimensional) slice contains an iterator

Parameters:
s : pointer to an integer, iterator or a tuple of integers/iterators

Notes

Only called from __getitem__ and __setitem__ in bohrium arrays (see _bh.c).

bohrium.loop.inherit_dynamic_changes(a, sliced)

Creates a view into another view which has dynamic changes. The new view inherits the dynamic changes.

bohrium.random123 module

Random

Random functions

bohrium.random123.seed(seed=None)

Seed the generator.

This method is called when RandomState is initialized. It can be called again to re-seed the generator. For details, see RandomState.

Parameters:
seed : int or array_like, optional

Seed for RandomState.

See also

RandomState
bohrium.random123.random_sample()

Return random floats in the half-open interval [0.0, 1.0).

Results are from the “continuous uniform” distribution over the stated interval. To sample \(Unif[a, b), b > a\) multiply the output of random by (b-a) and add a:

(b - a) * random() + a
Parameters:
shape : int or tuple of ints, optional

Defines the shape of the returned array of random floats. If None (the default), returns a single float.

Returns:
out : float or ndarray of floats

Array of random floats of shape shape (unless shape=None, in which case a single float is returned).

Examples

>>> np.random.random()
0.47108547995356098
>>> type(np.random.random())
<type 'float'>
>>> np.random.random((5,))
array([ 0.30220482,  0.86820401,  0.1654503 ,  0.11659149,  0.54323428])

Three-by-two array of random numbers from [-5, 0):

>>> 5 * np.random.random((3, 2)) - 5
array([[-3.99149989, -0.52338984],
       [-2.99091858, -0.79479508],
       [-1.23204345, -1.75224494]])
bohrium.random123.uniform(low=0.0, high=1.0, size=None, dtype=float, bohrium=True)

Draw samples from a uniform distribution.

Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

Parameters:
low : float, optional

Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.

high : float

Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns:
out : ndarray

Drawn samples, with shape size.

See also

randint
Discrete uniform distribution, yielding integers.
random_integers
Discrete uniform distribution over the closed interval [low, high].
random_sample
Floats uniformly distributed over [0, 1).
random
Alias for random_sample.
rand
Convenience function that accepts dimensions as input, e.g., rand(2,2) would generate a 2-by-2 array of floats, uniformly distributed over [0, 1).

Notes

The probability density function of the uniform distribution is

\[p(x) = \frac{1}{b - a}\]

anywhere within the interval [a, b), and zero elsewhere.

same as: random_sample(size) * (high - low) + low

Examples

Draw samples from the distribution:

>>> s = np.random.uniform(-1,0,1000)

All values are within the given interval:

>>> np.all(s >= -1)
True
>>> np.all(s < 0)
True

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 15, normed=True)
>>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
>>> plt.show()
bohrium.random123.rand(d0, d1, ..., dn, dtype=float, bohrium=True)

Random values in a given shape.

Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:
out : ndarray, shape (d0, d1, ..., dn)

Random values.

See also

random

Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

Examples

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random
bohrium.random123.randn(d0, d1, ..., dn, dtype=float, bohrium=True)

Return a sample (or samples) from the “standard normal” distribution.

If positive, int_like or int-convertible arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1 (if any of the \(d_i\) are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided.

This is a convenience function. If you want an interface that takes a tuple as the first argument, use numpy.random.standard_normal instead.

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned.

Returns:
Z : ndarray or float

A (d0, d1, ..., dn)-shaped array of floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied.

See also

random.standard_normal
Similar, but takes a tuple as its argument.

Notes

For random samples from \(N(\mu, \sigma^2)\), use:

sigma * np.random.randn(...) + mu

Examples

>>> np.random.randn()
2.1923875335537315 #random

Two-by-four array of samples from N(3, 6.25):

>>> 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],  #random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]]) #random
bohrium.random123.random_integers(low, high=None, size=None, dtype=int, bohrium=True)

Return random integers between low and high, inclusive.

Return random integers from the “discrete uniform” distribution in the closed interval [low, high]. If high is None (the default), then results are from [1, low].

Parameters:
low : int

Lowest (signed) integer to be drawn from the distribution (unless high=None, in which case this parameter is the highest such integer).

high : int, optional

If provided, the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None).

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns:
out : int or ndarray of ints

size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.

See also

random.randint
Similar to random_integers, only for the half-open interval [low, high), and 0 is the lowest value if high is omitted.

Notes

To sample from N evenly spaced floating-point numbers between a and b, use:

a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)

Examples

>>> np.random.random_integers(5)
4
>>> type(np.random.random_integers(5))
<type 'int'>
>>> np.random.random_integers(5, size=(3.,2.))
array([[5, 4],
       [3, 3],
       [4, 5]])

Choose five random numbers from the set of five evenly-spaced numbers between 0 and 2.5, inclusive (i.e., from the set \({0, 5/8, 10/8, 15/8, 20/8}\)):

>>> 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4.
array([ 0.625,  1.25 ,  0.625,  0.625,  2.5  ])

Roll two six sided dice 1000 times and sum the results:

>>> d1 = np.random.random_integers(1, 6, 1000)
>>> d2 = np.random.random_integers(1, 6, 1000)
>>> dsums = d1 + d2

Display results as a histogram:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(dsums, 11, normed=True)
>>> plt.show()
bohrium.random123.standard_normal(size=None, dtype=float, bohrium=True)

Returns samples from a Standard Normal distribution (mean=0, stdev=1).

Parameters:
size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns:
out : float or ndarray

Drawn samples.

Examples

>>> s = np.random.standard_normal(8000)
>>> s
array([ 0.6888893 ,  0.78096262, -0.89086505, ...,  0.49876311, #random
       -0.38672696, -0.4685006 ])                               #random
>>> s.shape
(8000,)
>>> s = np.random.standard_normal(size=(3, 4, 2))
>>> s.shape
(3, 4, 2)
bohrium.random123.normal(loc=0.0, scale=1.0, size=None, dtype=float, bohrium=True)

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2], is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2].

Parameters:
loc : float

Mean (“centre”) of the distribution.

scale : float

Standard deviation (spread or “width”) of the distribution.

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

See also

scipy.stats.distributions.norm
probability density function, distribution or cumulative density function, etc.

Notes

The probability density for the Gaussian distribution is

\[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },\]

where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance.

The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x - \sigma\) [2]). This implies that numpy.random.normal is more likely to return samples lying close to the mean, rather than those far away.

References

[1]Wikipedia, “Normal distribution”, http://en.wikipedia.org/wiki/Normal_distribution
[2](1, 2, 3) P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.

Examples

Draw samples from the distribution:

>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

Verify the mean and the variance:

>>> abs(mu - np.mean(s)) < 0.01
True
>>> abs(sigma - np.std(s, ddof=1)) < 0.01
True

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
>>> plt.show()
bohrium.random123.standard_exponential(size=None, dtype=float, bohrium=True)

Draw samples from the standard exponential distribution.

standard_exponential is identical to the exponential distribution with a scale parameter of 1.

Parameters:
size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns:
out : float or ndarray

Drawn samples.

Examples

Output a 3x8000 array:

>>> n = np.random.standard_exponential((3, 8000))
bohrium.random123.exponential(scale=1.0, size=None, dtype=float, bohrium=True)

Exponential distribution.

Its probability density function is

\[f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),\]

for x > 0 and 0 elsewhere. \(\beta\) is the scale parameter, which is the inverse of the rate parameter \(\lambda = 1/\beta\). The rate parameter is an alternative, widely used parameterization of the exponential distribution [3].

The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms [1], or the time between page requests to Wikipedia [2].

Parameters:
scale : float

The scale parameter, \(\beta = 1/\lambda\).

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

References

[1]Peyton Z. Peebles Jr., “Probability, Random Variables and Random Signal Principles”, 4th ed, 2001, p. 57.
[2]“Poisson Process”, Wikipedia, http://en.wikipedia.org/wiki/Poisson_process
[3]“Exponential Distribution, Wikipedia, http://en.wikipedia.org/wiki/Exponential_distribution

bohrium.signal module

Signal Processing

Common signal processing functions, which often handle multiple dimension

bohrium.summations module

Summations and products

bohrium.summations.average(a, axis=None, dtype=None, out=None)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. Parameters ———- a : array_like

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. .. versionadded:: 1.7.0 If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.
out : ndarray, optional
Alternate output array in which to place the result. The default is None; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See doc.ufuncs for details.
Returns:
m : ndarray, see dtype parameter above

If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

See Also
average : Weighted average
std, var, nanmean, nanstd, nanvar
Notes
The arithmetic mean is the sum of the elements along the axis divided
by the number of elements.
Note that for floating-point input, the mean is computed using the
same precision the input has. Depending on the input data, this can
cause the results to be inaccurate, especially for float32 (see
example below). Specifying a higher-precision accumulator using the
dtype keyword can alleviate this issue.
By default, float16 results are computed using float32 intermediates
for extra precision.
Examples
>>> a = np.array([[1, 2], [3, 4]])
    ..
>>> np.mean(a)
    ..
2.5
>>> np.mean(a, axis=0)
    ..
array([ 2., 3.])
>>> np.mean(a, axis=1)
    ..
array([ 1.5, 3.5])
In single precision, mean can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
    ..
>>> a[0, :] = 1.0
    ..
>>> a[1, :] = 0.1
    ..
>>> np.mean(a)
    ..
0.54999924
Computing the mean in float64 is more accurate:
>>> np.mean(a, dtype=np.float64)
    ..
0.55000000074505806
bohrium.summations.mean(a, axis=None, dtype=None, out=None)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. Parameters ———- a : array_like

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. .. versionadded:: 1.7.0 If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.
out : ndarray, optional
Alternate output array in which to place the result. The default is None; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See doc.ufuncs for details.
Returns:
m : ndarray, see dtype parameter above

If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

See Also
average : Weighted average
std, var, nanmean, nanstd, nanvar
Notes
The arithmetic mean is the sum of the elements along the axis divided
by the number of elements.
Note that for floating-point input, the mean is computed using the
same precision the input has. Depending on the input data, this can
cause the results to be inaccurate, especially for float32 (see
example below). Specifying a higher-precision accumulator using the
dtype keyword can alleviate this issue.
By default, float16 results are computed using float32 intermediates
for extra precision.
Examples
>>> a = np.array([[1, 2], [3, 4]])
    ..
>>> np.mean(a)
    ..
2.5
>>> np.mean(a, axis=0)
    ..
array([ 2., 3.])
>>> np.mean(a, axis=1)
    ..
array([ 1.5, 3.5])
In single precision, mean can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
    ..
>>> a[0, :] = 1.0
    ..
>>> a[1, :] = 0.1
    ..
>>> np.mean(a)
    ..
0.54999924
Computing the mean in float64 is more accurate:
>>> np.mean(a, dtype=np.float64)
    ..
0.55000000074505806

bohrium.user_kernel module

bohrium.user_kernel.dtype_to_c99(dtype)

Returns the C99 name of dtype

bohrium.user_kernel.execute(kernel_source, operand_list, compiler_command=None, tag='openmp', param=None, only_behaving_operands=True)

Compile and execute the function execute() with the arguments in operand_list

Parameters:
kernel_source : str

The kernel source code that most define the function execute() that should take arguments corresponding to the operand_list

operand_list : list of bohrium arrays

The arrays given to the execute() function defined in kernel_source

compiler_command : str, optional

The compiler command to use when comping the kernel. {OUT} and {IN} in the command are replaced with the name of the binary and source path. When this options isn’t specified, the default command are used see get_default_compiler_command().

tag : str, optional

Name of the backend that should handle this kernel.

param : dict, optional

Backend specific parameters (e.g. OpenCL needs global_work_size and local_work_size).

only_behaving_operands : bool, optional
Set to False in order to allow non-behaving operands. Requirements for a behaving array:
  • Is a bohrium array
  • Is C-style contiguous
  • Points to the first element in the underlying base array (no offset)
  • Has the same total length as its base

See make_behaving()

Examples

# Simple addition kernel import bohrium as bh kernel = r’‘’ #include <stdint.h> void execute(double *a, double *b, double *c) {

for(uint64_t i=0; i<100; ++i) {
c[i] = a[i] + b[i] + i;

}

}’‘’ a = bh.ones(100, bh.double) b = bh.ones(100, bh.double) res = bh.empty_like(a) bh.user_kernel.execute(kernel, [a, b, res])

bohrium.user_kernel.gen_function_prototype(operand_list, operand_name_list=None)

Returns the execute() definition based on the arrays in `operand_list

bohrium.user_kernel.get_default_compiler_command()

Returns the default compiler command, which is the one typically extended with extra link commands

bohrium.user_kernel.make_behaving(ary, dtype=None)

Make sure that ary is a “behaving” bohrium array of type dtype. Requirements for a behaving array:

  • Is a bohrium array
  • Is C-style contiguous
  • Points to the first element in the underlying base array (no offset)
  • Has the same total length as its base
Parameters:
ary : array_like

The array to make behaving

dtype : boolean, optional

The return array is converted to dtype if not None

Returns:
A behaving Bohrium array that might be a copy of ary