Python API

BhBase and BhArray

class bh107.BhBase(dtype, nelem)

A base array that represent a block of memory. A base array is always the sole owner of a complete memory allocation.

dtype = None

The data type of the base array

itemsize = None

Size of an element in bytes

nbytes = None

Total size of the base array in bytes

nelem = None

Number of elements

class bh107.BhArray(shape, dtype, strides=None, offset=0, base=None, is_scalar=False)

A array that represent a view of a base array. Multiple array views can point to the same base array.

asnumpy(self)

Returns a NumPy array that points to the same memory as this BhArray

astype(self, dtype, always_copy=True)
base = None

The base array

copy(self)

Return a copy of the array.

Returns:
out : BhArray

Copy of self

copy2numpy(self)

Returns a NumPy array that is a copy of this BhArray

dtype
empty(self)
fill(self, value)

Fill the array with a scalar value.

Parameters:
value : scalar

All elements of a will be assigned this value.

Examples

>>> a = bh107.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = bh107.empty(2)
>>> a.fill(1)
>>> a
array([ 1.,  1.])
flatten(self, always_copy=True)

Return a copy of the array collapsed into one dimension.

Parameters:
always_copy : boolean

When False, a copy is only made when necessary

Returns:
y : ndarray

A copy of the array, flattened to one dimension.

Notes

The order of the data in memory is always row-major (C-style).

Examples

>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
classmethod from_numpy(cls, numpy_array)
classmethod from_object(cls, obj)
classmethod from_scalar(cls, scalar)
isbehaving(self)
iscontiguous(self)
isscalar(self)
ndim
ravel(self)

Return a contiguous flattened array.

A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

Returns:
y : ndarray

A copy or view of the array, flattened to one dimension.

reshape(self, shape)
shape
size
strides

Gets the strides in elements

strides_in_bytes

Gets the strides in bytes

transpose(self, axes=None)

Permute the dimensions of an array.

Parameters:
axes : list of ints, optional

By default, reverse the dimensions, otherwise permute the axes according to the values given.

view(self)

Returns a new view that points to the same base as this BhArray

Array Creation

bh107.array(obj, dtype=None, copy=False)

Create an BhArray.

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 obj isn’t a BhArray of the correct dtype already

Returns:
out : BhArray

An array of dtype.

Examples

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

Upcasting:

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

More than one dimension:

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

Type provided:

>>> bh.array([1, 2, 3], dtype=complex)
array([ 1.+0.j,  2.+0.j,  3.+0.j])
bh107.empty(shape, dtype=<type 'numpy.float64'>)

Return a new matrix of given shape and type, without initializing entries.

Parameters:
shape : int or tuple of int

Shape of the empty matrix.

dtype : data-type, optional

Desired output data-type.

See also

empty_like, zeros

Notes

The order of the data in memory is always row-major (C-style).

empty, unlike zeros, does not set the matrix values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.

bh107.zeros(shape, dtype=<type 'float'>)

Array of zeros.

Return an array of given shape and type, filled with zeros.

Parameters:
shape : {sequence of ints, int}

Shape of the array

dtype : data-type, optional

The desired data-type for the array, default is np.float64.

Returns:
out : bharray

Array of zeros of given shape, dtype, and order.

bh107.ones(shape, dtype=<type 'numpy.float64'>)

Array of ones.

Return an array of given shape and type, filled with ones.

Parameters:
shape : {sequence of ints, int}

Shape of the array

dtype : data-type, optional

The desired data-type for the array, default is np.float64.

Returns:
out : bharray

Array of ones of given shape, dtype, and order.

bh107.empty_like(a, dtype=None)

Return a new array with the same shape and type as a given array.

Parameters:
a : array_like

The shape and data-type of a define these same attributes of the returned array.

dtype : data-type, optional

Overrides the data type of the result.

Returns:
out : ndarray

Array of uninitialized (arbitrary) data with the same shape and type as a.

See also

ones_like
Return an array of ones with shape and type of input.
zeros_like
Return an array of zeros with shape and type of input.
empty
Return a new uninitialized array.
ones
Return a new array setting values to one.
zeros
Return a new array setting values to zero.

Notes

The order of the data in memory is always row-major (C-style).

This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be marginally faster than the functions that do set the array values.

Examples

>>> a = ([1,2,3], [4,5,6])                         # a is array-like
>>> bh.empty_like(a)
array([[-1073741821, -1073741821,           3],    #random
       [          0,           0, -1073741821]])
>>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> bh.empty_like(a)
array([[ -2.00000715e+000,   1.48219694e-323,  -2.00000572e+000],#random
       [  4.38791518e-305,  -2.00000715e+000,   4.17269252e-309]])
bh107.zeros_like(a, dtype=None)

Return an array of zeros with the same shape and type as a given array.

With default parameters, is equivalent to a.copy().fill(0).

Parameters:
a : array_like

The shape and data-type of a define these same attributes of the returned array.

dtype : data-type, optional

Overrides the data type of the result.

Returns:
out : ndarray

Array of zeros with the same shape and type as a.

See also

ones_like
Return an array of ones with shape and type of input.
empty_like
Return an empty array with shape and type of input.
zeros
Return a new array setting values to zero.
ones
Return a new array setting values to one.
empty
Return a new uninitialized array.

Notes

The order of the data in memory is always row-major (C-style).

Examples

>>> x = bh.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> bh.zeros_like(x)
array([[0, 0, 0],
       [0, 0, 0]])
>>> y = bh.arange(3, dtype=bh.float)
>>> y
array([ 0.,  1.,  2.])
>>> bh.zeros_like(y)
array([ 0.,  0.,  0.])
bh107.ones_like(a, dtype=None)

Return an array of ones with the same shape and type as a given array.

With default parameters, is equivalent to a.copy().fill(1).

Parameters:
a : array_like

The shape and data-type of a define these same attributes of the returned array.

dtype : data-type, optional

Overrides the data type of the result.

Returns:
out : ndarray

Array of zeros with the same shape and type as a.

See also

zeros_like
Return an array of zeros with shape and type of input.
empty_like
Return an empty array with shape and type of input.
zeros
Return a new array setting values to zero.
ones
Return a new array setting values to one.
empty
Return a new uninitialized array.

Notes

The order of the data in memory is always row-major (C-style).

Examples

>>> x = bh.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> bh.ones_like(x)
array([[1, 1, 1],
       [1, 1, 1]])
>>> y = bh.arange(3, dtype=bh.float)
>>> y
array([ 0.,  1.,  2.])
>>> bh.ones_like(y)
array([ 1.,  1.,  1.])

Random

class bh107.random.RandomState(seed=None)

Methods

exponential(self[, scale, shape]) Exponential distribution.
get_state(self) Return a tuple representing the internal state of the generator.
rand(self, \*shape) Random values in a given shape.
randint(self, low[, high, shape]) Return random integers from low (inclusive) to high (exclusive).
random(self[, shape]) Return random floats in the half-open interval [0.0, 1.0).
random123(self, shape) New array of uniform pseudo numbers based on the random123 philox2x32 algorithm.
random_integers(self, low[, high, shape]) Return random integers between low and high, inclusive.
random_of_dtype(self, dtype[, shape]) Return random array of dtype.
random_sample(self, shape) Return random floats in the half-open interval [0.0, 1.0).
ranf(self[, shape]) Return random floats in the half-open interval [0.0, 1.0).
sample(self[, shape]) Return random floats in the half-open interval [0.0, 1.0).
seed(self[, seed]) Seed the generator.
set_state(self, state) Set the internal state of the generator from a tuple.
standard_exponential(self[, shape]) Draw samples from the standard exponential distribution.
uniform(self[, low, high, shape]) Draw samples from a uniform distribution.
exponential(self, scale=1.0, shape=None)

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\).

shape : 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.

Returns:
out : BhArray

Drawn samples.

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
get_state(self)

Return a tuple representing the internal state of the generator.

For more details, see set_state.

Returns:
out : tuple(str, np.uint64, np.uint32)

The returned tuple has the following items:

  1. the string ‘Random123’.
  2. an integer index.
  3. an integer key.

See also

set_state

Notes

set_state and get_state are not needed to work with any of the random distributions in Bohrium. If the internal state is manually altered, the user should know exactly what he/she is doing.

rand(self, *shape)

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 : BhArray, 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
randint(self, low, high=None, shape=None)

Return random integers from low (inclusive) to high (exclusive).

Return random integers from the “discrete uniform” distribution in the “half-open” interval [low, high). If high is None (the default), then results are from [0, 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, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None).

shape : 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 : BhArray 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.random_integers
similar to randint, only for the closed interval [low, high], and 1 is the lowest value if high is omitted. In particular, this other one is the one to use to generate uniformly distributed discrete non-integers.

Examples

>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Generate a 2 x 4 array of ints between 0 and 4, inclusive:

>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
       [3, 2, 2, 0]])
random(self, shape=None)

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

Alias for random_sample

random123(self, shape)

New array of uniform pseudo numbers based on the random123 philox2x32 algorithm. NB: dtype is np.uint64 always

Parameters:
shape : int or tuple of ints
Defines the shape of the returned array of random floats.
Returns:
out : Array of uniform pseudo numbers
random_integers(self, low, high=None, shape=None)

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).

shape : 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 : BhArray of ints

size-shaped array of random integers from the appropriate distribution.

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) * (bh107.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()
random_of_dtype(self, dtype, shape=None)

Return random array of dtype. The values are in the interval of the dtype.

Parameters:
dtype : data-type

The desired data-type for the array.

shape : int or tuple of ints

Defines the shape of the returned array of random floats.

Returns:
out : BhArray of floats

Array of random floats of shape shape.

random_sample(self, shape)

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_sample by (b-a) and add a:

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

Defines the shape of the returned array of random floats.

Returns:
out : BhArray of floats

Array of random floats of shape shape.

Examples

>>> 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]])
ranf(self, shape=None)

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

Alias for random_sample

sample(self, shape=None)

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

Alias for random_sample

seed(self, 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
set_state(self, state)

Set the internal state of the generator from a tuple.

For use if one has reason to manually (re-)set the internal state of the “Mersenne Twister”[1]_ pseudo-random number generating algorithm.

Parameters:
state : tuple(str, np.uint64, np.uint32)

The returned tuple has the following items:

  1. the string ‘Random123’.
  2. an integer index.
  3. an integer key.
Returns:
out : None

Returns ‘None’ on success.

See also

get_state

Notes

set_state and get_state are not needed to work with any of the random distributions in Bohrium. If the internal state is manually altered, the user should know exactly what he/she is doing.

standard_exponential(self, shape=None)

Draw samples from the standard exponential distribution.

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

Parameters:
shape : 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 : BhArray

Drawn samples.

Examples

Output a 3x8000 array:

>>> n = np.random.standard_exponential((3, 8000))
uniform(self, low=0.0, high=1.0, shape=None)

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.

shape : 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 : BhArray

Drawn samples, with shape shape.

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()

User Kernels

bh107.user_kernel.dtype_to_c99(dtype)

Returns the C99 name of dtype

bh107.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 = bh107.ones(100, np.double) b = bh107.ones(100, np.double) res = bh107.empty_like(a) bh107.user_kernel.execute(kernel, [a, b, res])

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

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

bh107.user_kernel.get_default_compiler_command()

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

bh107.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
  • Points to the first element in the underlying base array (no offset)
  • Has the same total length as its base
Parameters:
ary : BhArray

The array to make behaving

dtype : boolean, optional

The return array is converted to dtype if not None

Returns:
A behaving BhArray that might be a copy of ary