Skip to content

Add (CMake) example #256

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions .azure-pipelines/unix-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ steps:
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=$CONDA_PREFIX -DPYTHON_EXECUTABLE=`which python` -DDOWNLOAD_GTEST=ON $(Build.SourcesDirectory)
make install
displayName: Configure xtensor-python
workingDirectory: $(Build.BinariesDirectory)

- script: |
source activate xtensor-python
make -j2 test_xtensor_python
displayName: Build xtensor-python
workingDirectory: $(Build.BinariesDirectory)/build

- script: |
source activate xtensor-python
cd test
Expand All @@ -32,3 +33,19 @@ steps:
py.test -s
displayName: Test xtensor-python (Python)
workingDirectory: $(Build.SourcesDirectory)

- script: |
source activate xtensor-python
cmake . -DPYTHON_EXECUTABLE=`which python`
cmake --build .
python example.py
displayName: Example - readme 1
workingDirectory: $(Build.SourcesDirectory)/docs/source/examples/readme_example_1

- script: |
source activate xtensor-python
cmake . -DPYTHON_EXECUTABLE=`which python`
cmake --build .
python example.py
displayName: Example - SFINAE
workingDirectory: $(Build.SourcesDirectory)/docs/source/examples/sfinae
22 changes: 15 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ Both containers enable the numpy-style APIs of xtensor (see [the numpy to xtenso

```cpp
#include <numeric> // Standard library import for std::accumulate
#include "pybind11/pybind11.h" // Pybind11 import to define Python bindings
#include "xtensor/xmath.hpp" // xtensor import for the C++ universal functions
#include <pybind11/pybind11.h> // Pybind11 import to define Python bindings
#include <xtensor/xmath.hpp> // xtensor import for the C++ universal functions
#define FORCE_IMPORT_ARRAY
#include "xtensor-python/pyarray.hpp" // Numpy bindings
#include <xtensor-python/pyarray.hpp> // Numpy bindings

double sum_of_sines(xt::pyarray<double>& m)
{
Expand All @@ -77,7 +77,7 @@ import xtensor_python_test as xt

v = np.arange(15).reshape(3, 5)
s = xt.sum_of_sines(v)
s
print(s)
```

**Outputs**
Expand All @@ -86,14 +86,22 @@ s
1.2853996391883833
```

**Working example**

Get the working example here:

* [`CMakeLists.txt`](docs/source/examples/readme_example_1/CMakeLists.txt)
* [`main.cpp`](docs/source/examples/readme_example_1/main.cpp)
* [`example.py`](docs/source/examples/readme_example_1/example.py)

### Example 2: Create a universal function from a C++ scalar function

**C++ code**

```cpp
#include "pybind11/pybind11.h"
#include <pybind11/pybind11.h>
#define FORCE_IMPORT_ARRAY
#include "xtensor-python/pyvectorize.hpp"
#include <xtensor-python/pyvectorize.hpp>
#include <numeric>
#include <cmath>

Expand Down Expand Up @@ -122,7 +130,7 @@ import xtensor_python_test as xt
x = np.arange(15).reshape(3, 5)
y = [1, 2, 3, 4, 5]
z = xt.vectorized_func(x, y)
z
print(z)
```

**Outputs**
Expand Down
100 changes: 100 additions & 0 deletions docs/source/examples.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@

****************
(CMake) Examples
****************

Basic example (from readme)
===========================

Consider the following C++ code:

:download:`main.cpp <examples/readme_example_1/main.cpp>`

.. literalinclude:: examples/readme_example_1/main.cpp
:language: cpp

There are several options to build the module,
whereby we will CMake here with the following ``CMakeLists.txt``:

:download:`CMakeLists.txt <examples/readme_example_1/CMakeLists.txt>`

.. literalinclude:: examples/readme_example_1/CMakeLists.txt
:language: cmake

Then we can test the module:

:download:`example.py <examples/readme_example_1/example.py>`

.. literalinclude:: examples/readme_example_1/example.py
:language: cmake

.. note::

Since we did not install the module,
we should compile and run the example from the same folder.
To install, please consult
`this pybind11 / CMake example <https://github.com/pybind/cmake_example>`_.


Type restriction with SFINAE
============================

.. seealso::

`Medium post by Johan Mabille <https://medium.com/@johan.mabille/designing-language-bindings-with-xtensor-f32aa0f20db>`__
This example covers "Option 4".

In this example we will design a module with a function that accepts an ``xt::xtensor`` as argument,
but in such a way that an ``xt::pyxtensor`` can be accepted in the Python module.
This is done by having a templated function

.. code-block:: cpp

template <class T>
void times_dimension(T& t);

As this might be a bit too permissive for your liking, we will show you how to limit the
scope to *xtensor* types, and allow other overloads using the principle of SFINAE
(Substitution Failure Is Not An Error).
In particular:

:download:`mymodule.hpp <examples/sfinae/mymodule.hpp>`

.. literalinclude:: examples/sfinae/mymodule.hpp
:language: cpp

Consequently from C++, the interaction with the module's function is trivial

:download:`main.cpp <examples/sfinae/main.cpp>`

.. literalinclude:: examples/sfinae/main.cpp
:language: cpp

For the Python module we just have to specify the template to be
``xt::pyarray`` or ``xt::pytensor``. E.g.

:download:`src/python.cpp <examples/sfinae/python.cpp>`

.. literalinclude:: examples/sfinae/python.cpp
:language: cpp

We will again use CMake to compile, with the following ``CMakeLists.txt``:

:download:`CMakeLists.txt <examples/sfinae/CMakeLists.txt>`

.. literalinclude:: examples/sfinae/CMakeLists.txt
:language: cmake

Then we can test the module:

:download:`example.py <examples/readme_example_1/example.py>`

.. literalinclude:: examples/readme_example_1/example.py
:language: cmake

.. note::

Since we did not install the module,
we should compile and run the example from the same folder.
To install, please consult
`this pybind11 / CMake example <https://github.com/pybind/cmake_example>`_.
13 changes: 13 additions & 0 deletions docs/source/examples/readme_example_1/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
cmake_minimum_required(VERSION 3.1..3.19)

project(mymodule)

find_package(pybind11 CONFIG REQUIRED)
find_package(xtensor REQUIRED)
find_package(xtensor-python REQUIRED)
find_package(Python REQUIRED COMPONENTS NumPy)

pybind11_add_module(mymodule main.cpp)
target_link_libraries(mymodule PUBLIC pybind11::module xtensor-python Python::NumPy)

target_compile_definitions(mymodule PRIVATE VERSION_INFO=0.1.0)
6 changes: 6 additions & 0 deletions docs/source/examples/readme_example_1/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import mymodule
import numpy as np

a = np.array([1, 2, 3])
assert np.isclose(np.sum(np.sin(a)), mymodule.sum_of_sines(a))

18 changes: 18 additions & 0 deletions docs/source/examples/readme_example_1/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include <numeric>
#include <xtensor.hpp>
#include <pybind11/pybind11.h>
#define FORCE_IMPORT_ARRAY
#include <xtensor-python/pyarray.hpp>

double sum_of_sines(xt::pyarray<double>& m)
{
auto sines = xt::sin(m); // sines does not actually hold values.
return std::accumulate(sines.begin(), sines.end(), 0.0);
}

PYBIND11_MODULE(mymodule, m)
{
xt::import_numpy();
m.doc() = "Test module for xtensor python bindings";
m.def("sum_of_sines", sum_of_sines, "Sum the sines of the input values");
}
16 changes: 16 additions & 0 deletions docs/source/examples/sfinae/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
cmake_minimum_required(VERSION 3.1..3.19)

project(mymodule)

find_package(pybind11 CONFIG REQUIRED)
find_package(xtensor REQUIRED)
find_package(xtensor-python REQUIRED)
find_package(Python REQUIRED COMPONENTS NumPy)

pybind11_add_module(mymodule python.cpp)
target_link_libraries(mymodule PUBLIC pybind11::module xtensor-python Python::NumPy)

target_compile_definitions(mymodule PRIVATE VERSION_INFO=0.1.0)

add_executable(myexec main.cpp)
target_link_libraries(myexec PUBLIC xtensor)
8 changes: 8 additions & 0 deletions docs/source/examples/sfinae/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import mymodule
import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64)
b = np.array(a, copy=True)
mymodule.times_dimension(b) # changing in-place!
assert np.allclose(2 * a, b)

10 changes: 10 additions & 0 deletions docs/source/examples/sfinae/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#include "mymodule.hpp"
#include <xtensor/xio.hpp>

int main()
{
xt::xtensor<size_t, 2> a = xt::arange<size_t>(2 * 3).reshape({2, 3});
mymodule::times_dimension(a);
std::cout << a << std::endl;
return 0;
}
32 changes: 32 additions & 0 deletions docs/source/examples/sfinae/mymodule.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <xtensor/xtensor.hpp>

namespace mymodule {

template <class T>
struct is_std_vector
{
static const bool value = false;
};

template <class T>
struct is_std_vector<std::vector<T> >
{
static const bool value = true;
};

// any xtensor object
template <class T, std::enable_if_t<xt::is_xexpression<T>::value, bool> = true>
void times_dimension(T& t)
{
using value_type = typename T::value_type;
t *= (value_type)(t.dimension());
}

// an std::vector
template <class T, std::enable_if_t<is_std_vector<T>::value, bool> = true>
void times_dimension(T& t)
{
// do nothing
}

}
11 changes: 11 additions & 0 deletions docs/source/examples/sfinae/python.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#include "mymodule.hpp"
#include <pybind11/pybind11.h>
#define FORCE_IMPORT_ARRAY
#include <xtensor-python/pyarray.hpp>

PYBIND11_MODULE(mymodule, m)
{
xt::import_numpy();
m.doc() = "Test module for xtensor python bindings";
m.def("times_dimension", &mymodule::times_dimension<xt::pyarray<double>>);
}
9 changes: 5 additions & 4 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ What are ``xtensor`` and ``xtensor-python``?
- ``xtensor`` is a C++ library for multi-dimensional arrays enabling numpy-style broadcasting and lazy computing.
- ``xtensor-python`` enables inplace use of numpy arrays with all the benefits from ``xtensor``

- C++ universal functions and broadcasting
- C++ universal functions and broadcasting
- STL - compliant APIs.


Expand Down Expand Up @@ -62,6 +62,7 @@ This software is licensed under the BSD-3-Clause license. See the LICENSE file f
basic_usage
array_tensor
numpy_capi
examples
cookiecutter

.. toctree::
Expand All @@ -79,7 +80,7 @@ This software is licensed under the BSD-3-Clause license. See the LICENSE file f

.. _NumPy: http://www.numpy.org
.. _`Buffer Protocol`: https://docs.python.org/3/c-api/buffer.html
.. _`numpy to xtensor cheat sheet`: http://xtensor.readthedocs.io/en/latest/numpy.html
.. _`numpy to xtensor cheat sheet`: http://xtensor.readthedocs.io/en/latest/numpy.html
.. _xtensor: https://github.com/xtensor-stack/xtensor
.. _pybind11: https://github.com/pybind/pybind11
.. _xtensor-python-cookiecutter: https://github.com/xtensor-stack/xtensor-python-cookiecutter
.. _pybind11: https://github.com/pybind/pybind11
.. _xtensor-python-cookiecutter: https://github.com/xtensor-stack/xtensor-python-cookiecutter