From NumPy to xtensor — xtensor documentation (original) (raw)
Containers
Two container types are provided. xt::xarray (dynamic number of dimensions) and xt::xtensor (static number of dimensions).
Initializers
Lazy helper functions return tensor expressions. Return types don’t hold any value and are evaluated upon access or assignment. They can be assigned to a container or directly used in expressions.
xtensor’s meshgrid implementation corresponds to numpy’s 'ij' indexing order.
Slicing and indexing
See numpy indexing page.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| a[3, 2] | a(3, 2) |
| a.flat[4] | a.flat(4) |
| a[3] | xt::view(a, 3, xt::all()) xt::row(a, 3) |
| a[:, 2] | xt::view(a, xt::all(), 2) xt::col(a, 2) |
| a[:5, 1:] | xt::view(a, xt::range(_, 5), xt::range(1, _)) |
| a[5:1:-1, :] | xt::view(a, xt::range(5, 1, -1), xt::all()) |
| a[..., 3] | xt::strided_view(a, {xt::ellipsis(), 3}) |
| a[:, np.newaxis] | xt::view(a, xt::all(), xt::newaxis()) |
Broadcasting
xtensor offers lazy numpy-style broadcasting, and universal functions. Unlike numpy, no copy or temporary variables are created.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.broadcast(a, [4, 5, 7]) | xt::broadcast(a, {4, 5, 7}) |
| np.vectorize(f) | xt::vectorize(f) |
| a[a > 5] | xt::filter(a, a > 5) |
| a[[0, 1], [0, 0]] | xt::index_view(a, {{0, 0}, {1, 0}}) |
Random
The random module provides simple ways to create random tensor expressions, lazily. See numpy.random and xtensor random page.
Concatenation, splitting, squeezing
Concatenating expressions does not allocate memory, it returns a tensor or view expression holding closures on the specified arguments.
Rearrange elements
In the same spirit as concatenation, the following operations do not allocate any memory and do not modify the underlying xexpression.
Iteration
xtensor follows the idioms of the C++ STL providing iterator pairs to iterate on arrays in different fashions.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| for x in np.nditer(a): | for(auto it=a.begin(); it!=a.end(); ++it) |
| Iterating over a with a prescribed broadcasting shape | a.begin({3, 4}) a.end({3, 4}) |
| Iterating over a in a row-major fashion | a.beginxt::layout\_type::row\_major() a.beginxt::layout\_type::row\_major() |
| Iterating over a in a column-major fashion | a.beginxt::layout\_type::column\_major() a.endxt::layout\_type::column\_major() |
Logical
Logical universal functions are truly lazy.xt::where(condition, a, b) does not evaluate a where conditionis falsy, and it does not evaluate b where condition is truthy.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.where(a > 5, a, b) | xt::where(a > 5, a, b) |
| np.where(a > 5) | xt::where(a > 5) |
| np.argwhere(a > 5) | xt::argwhere(a > 5) |
| np.any(a) | xt::any(a) |
| np.all(a) | xt::all(a) |
| np.isin(a, b) | xt::isin(a, b) |
| np.in1d(a, b) | xt::in1d(a, b) |
| np.logical_and(a, b) | a && b |
| np.logical_or(a, b) | a | |
| np.isclose(a, b) | xt::isclose(a, b) |
| np.allclose(a, b) | xt::allclose(a, b) |
| a = ~b | a = !b |
Indices
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.ravel_multi_index(indices, a.shape) | xt::ravel_indices(indices, a.shape()) |
Comparisons
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.equal(a, b) | xt::equal(a, b) |
| np.not_equal(a, b) | xt::not_equal(a, b) |
| np.less(a, b) | xt::less(a, b) a < b |
| np.less_equal(a, b) | xt::less_equal(a, b) a <= b |
| np.greater(a, b) | xt::greater(a, b) a > b |
| np.greater_equal(a, b) | xt::greater_equal(a, b) a >= b |
| np.nonzero(a) | xt::nonzero(a) |
| np.flatnonzero(a) | xt::flatnonzero(a) |
Minimum, Maximum, Sorting
Complex numbers
Functions xt::real() and xt::imag() respectively return views on the real and imaginary part of a complex expression. The returned value is an expression holding a closure on the passed argument.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.real(a) | xt::real(a) |
| np.imag(a) | xt::imag(a) |
| np.conj(a) | xt::conj(a) |
- The constness and value category (rvalue / lvalue) of xt::real(a) is the same as that of
a. Hence, ifais a non-const lvalue, real(a) is an non-const lvalue reference, to which one can assign a real expression. - If
ahas complex values, the same holds for xt::imag(a). The constness and value category ofxt::imag(a) is the same as that ofa. - If
ahas real values, xt::imag(a) returns xt::zeros(a.shape()).
Reducers
Reducers accumulate values of tensor expressions along specified axes. When no axis is specified, values are accumulated along all axes. Reducers are lazy, meaning that returned expressions don’t hold any values and are computed upon access or assignment.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.sum(a, axis=(0, 1)) | xt::sum(a, {0, 1}) |
| np.sum(a, axis=1) | xt::sum(a, 1) |
| np.sum(a) | xt::sum(a) |
| np.prod(a, axis=(0, 1)) | xt::prod(a, {0, 1}) |
| np.prod(a, axis=1) | xt::prod(a, 1) |
| np.prod(a) | xt::prod(a) |
| np.mean(a, axis=(0, 1)) | xt::mean(a, {0, 1}) |
| np.mean(a, axis=1) | xt::mean(a, 1) |
| np.mean(a) | xt::mean(a) |
| np.std(a, [axis]) | xt::stddev(a, [axis]) |
| np.var(a, [axis]) | xt::variance(a, [axis]) |
| np.diff(a[, n, axis]) | xt::diff(a[, n, axis]) |
| np.trapz(a, dx=2.0, axis=-1) | xt::trapz(a, 2.0, -1) |
| np.trapz(a, x=b, axis=-1) | xt::trapz(a, b, -1) |
| np.count_nonzero(a, axis=(0, 1)) | xt::count_nonzero(a, {0, 1}) |
| np.count_nonzero(a, axis=1) | xt::count_nonzero(a, 1) |
| np.count_nonzero(a) | xt::count_nonzero(a) |
More generally, one can use the xt::reduce(function, input, axes) which allows the specification of an arbitrary binary function for the reduction. The binary function must be commutative and associative up to rounding errors.
NaN functions
NaN functions allow disregarding NaNs during computation, changing the effective number of elements considered in reductions.
I/O
Print options
These options determine the way floating point numbers, tensors and other xtensor expressions are displayed.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.set_printoptions(precision=4) | xt::print_options::set_precision(4) |
| np.set_printoptions(threshold=5) | xt::print_options::set_threshold(5) |
| np.set_printoptions(edgeitems=3) | xt::print_options::set_edgeitems(3) |
| np.set_printoptions(linewidth=100) | xt::print_options::set_line_width(100) |
Reading npy, csv file formats
Functions xt::load_csv() and xt::dump_csv() respectively take input and output streams as arguments.
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.load(filename) | xt::load_npy(filename) |
| np.save(filename, arr) | xt::dump_npy(filename, arr) |
| np.loadtxt(filename, delimiter=',') | xt::load_csv(stream) |
Mathematical functions
xtensor universal functions are provided for a large set number of mathematical functions.
Basic functions:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.absolute(a) | xt::abs(a) |
| np.sign(a) | xt::sign(a) |
| np.remainder(a, b) | xt::remainder(a, b) |
| np.minimum(a, b) | xt::minimum(a, b) |
| np.maximum(a, b) | xt::maximum(a, b) |
| np.clip(a, min, max) | xt::clip(a, min, max) |
| xt::fma(a, b, c) | |
| np.interp(x, xp, fp, [,left, right]) | xt::interp(x, xp, fp, [,left, right]) |
| np.rad2deg(a) | xt::rad2deg(a) |
| np.degrees(a) | xt::degrees(a) |
| np.deg2rad(a) | xt::deg2rad(a) |
| np.radians(a) | xt::radians(a) |
Exponential functions:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.exp(a) | xt::exp(a) |
| np.expm1(a) | xt::expm1(a) |
| np.log(a) | xt::log(a) |
| np.log1p(a) | xt::log1p(a) |
Power functions:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.power(a, p) | xt::pow(a, b) |
| np.sqrt(a) | xt::sqrt(a) |
| np.square(a) | xt::square(a) xt::cube(a) |
| np.cbrt(a) | xt::cbrt(a) |
Trigonometric functions:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.sin(a) | xt::sin(a) |
| np.cos(a) | xt::cos(a) |
| np.tan(a) | xt::tan(a) |
Hyperbolic functions:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.sinh(a) | xt::sinh(a) |
| np.cosh(a) | xt::cosh(a) |
| np.tanh(a) | xt::tanh(a) |
Error and gamma functions:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| scipy.special.erf(a) | xt::erf(a) |
| scipy.special.gamma(a) | xt::tgamma(a) |
| scipy.special.gammaln(a) | xt::lgamma(a) |
Classification functions:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.isnan(a) | xt::isnan(a) |
| np.isinf(a) | xt::isinf(a) |
| np.isfinite(a) | xt::isfinite(a) |
| np.searchsorted(a, v[, side]) | xt::searchsorted(a, v[, right]) |
Histogram:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.histogram(a, bins[, weights][, density]) | xt::histogram(a, bins[, weights][, density]) |
| np.histogram_bin_edges(a, bins[, weights][, left, right][, bins][, mode]) | xt::histogram_bin_edges(a, bins[, weights][, left, right][, bins][, mode]) |
| np.bincount(arr) | xt::bincount(arr) |
| np.digitize(data, bin_edges[, right]) | xt::digitize(data, bin_edges[, right][, assume_sorted]) |
See Histogram.
Numerical constants:
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| numpy.pi | xt::numeric_constants::PI |
Linear algebra
Many functions found in the numpy.linalg module are implemented in xtensor-blas, a separate package offering BLAS and LAPACK bindings, as well as a convenient interface replicating the linalg module.
Please note, however, that while we’re trying to be as close to NumPy as possible, some features are not implemented yet. Most prominently that is broadcasting for all functions except for xt::linalg::dot().
Matrix, vector and tensor products
Decompositions
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.linalg.cholesky(a) | xt::linalg::cholesky(a) |
| np.linalg.qr(a) | xt::linalg::qr(a) |
| np.linalg.svd(a) | xt::linalg::svd(a) |
Matrix eigenvalues
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.linalg.eig(a) | xt::linalg::eig(a) |
| np.linalg.eigvals(a) | xt::linalg::eigvals(a) |
| np.linalg.eigh(a) | xt::linalg::eigh(a) |
| np.linalg.eigvalsh(a) | xt::linalg::eigvalsh(a) |
Norms and other numbers
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.linalg.norm(a, order=2) | xt::linalg::norm(a, 2) |
| np.linalg.cond(a) | xt::linalg::cond(a) |
| np.linalg.det(a) | xt::linalg::det(a) |
| np.linalg.matrix_rank(a) | xt::linalg::matrix_rank(a) |
| np.linalg.slogdet(a) | xt::linalg::slogdet(a) |
| np.trace(a) | xt::linalg::trace(a) |
Solving equations and inverting matrices
| Python 3 - NumPy | C++ 14 - xtensor |
|---|---|
| np.linalg.inv(a) | xt::linalg::inv(a) |
| np.linalg.pinv(a) | xt::linalg::pinv(a) |
| np.linalg.solve(A, b) | xt::linalg::solve(A, b) |
| np.linalg.lstsq(A, b) | xt::linalg::lstsq(A, b) |