pybind11_diagram_utils.h
1 /* This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
2  * See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
3  * Author(s): Marc Glisse
4  *
5  * Copyright (C) 2020 Inria
6  *
7  * Modification(s):
8  * - YYYY/MM Author: Description of the modification
9  */
10 
11 #include <pybind11/pybind11.h>
12 #include <pybind11/numpy.h>
13 
14 #include <boost/range/counting_range.hpp>
15 #include <boost/range/adaptor/transformed.hpp>
16 
17 namespace py = pybind11;
18 typedef py::array_t<double> Dgm;
19 
20 // Get m[i,0] and m[i,1] as a pair
21 static auto pairify(void* p, py::ssize_t h, py::ssize_t w) {
22  return [=](py::ssize_t i){
23  char* birth = (char*)p + i * h;
24  char* death = birth + w;
25  return std::make_pair(*(double*)birth, *(double*)death);
26  };
27 }
28 
29 inline auto numpy_to_range_of_pairs(py::array_t<double> dgm) {
30  py::buffer_info buf = dgm.request();
31  // shape (n,2) or (0) for empty
32  if((buf.ndim!=2 || buf.shape[1]!=2) && (buf.ndim!=1 || buf.shape[0]!=0))
33  throw std::runtime_error("Diagram must be an array of size n x 2");
34  // In the case of shape (0), avoid reading non-existing strides[1] even if we won't use it.
35  py::ssize_t stride1 = buf.ndim == 2 ? buf.strides[1] : 0;
36  auto cnt = boost::counting_range<py::ssize_t>(0, buf.shape[0]);
37  return boost::adaptors::transform(cnt, pairify(buf.ptr, buf.strides[0], stride1));
38  // Be careful that the returned range cannot contain references to dead temporaries.
39 }
GUDHIdev  Version 3.5.0  - C++ library for Topological Data Analysis (TDA) and Higher Dimensional Geometry Understanding.  - Copyright : MIT Generated on Wed Apr 6 2022 19:26:28 for GUDHIdev by Doxygen 1.9.1