summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorROUVREAU Vincent <vincent.rouvreau@inria.fr>2019-11-20 09:29:27 +0100
committerROUVREAU Vincent <vincent.rouvreau@inria.fr>2019-11-20 09:29:27 +0100
commit7008061749a52e9717d550b44efe60173f4128b5 (patch)
treef0d53c7a5cb849e3d12d03c45935673969cb4fcb /src
parent8227cd68d5aa7c9eeda5dd474f2536b896b6f491 (diff)
parent445a217f4869c62888a20302491b085fbcaabd1b (diff)
Merge branch 'master' into persistence_graphical_tool_improvements
Diffstat (limited to 'src')
-rw-r--r--src/Alpha_complex/benchmark/Alpha_complex_3d_benchmark.cpp4
-rw-r--r--src/Alpha_complex/doc/Intro_alpha_complex.h11
-rw-r--r--src/Alpha_complex/example/Alpha_complex_from_off.cpp13
-rw-r--r--src/Alpha_complex/example/Alpha_complex_from_points.cpp5
-rw-r--r--src/Alpha_complex/example/CMakeLists.txt16
-rw-r--r--src/Alpha_complex/example/Fast_alpha_complex_from_off.cpp65
-rw-r--r--src/Alpha_complex/example/Weighted_alpha_complex_3d_from_points.cpp12
-rw-r--r--src/Alpha_complex/include/gudhi/Alpha_complex.h55
-rw-r--r--src/Alpha_complex/include/gudhi/Alpha_complex_3d.h81
-rw-r--r--src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp53
-rw-r--r--src/Alpha_complex/test/Alpha_complex_unit_test.cpp13
-rw-r--r--src/Alpha_complex/test/Periodic_alpha_complex_3d_unit_test.cpp37
-rw-r--r--src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp50
-rw-r--r--src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp24
-rw-r--r--src/Alpha_complex/utilities/CMakeLists.txt30
-rw-r--r--src/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp4
-rw-r--r--src/Alpha_complex/utilities/alpha_complex_persistence.cpp107
-rw-r--r--src/Alpha_complex/utilities/alphacomplex.md2
-rw-r--r--src/Cech_complex/doc/Intro_cech_complex.h2
-rw-r--r--src/Doxyfile.in2
-rw-r--r--src/Persistent_cohomology/include/gudhi/Persistent_cohomology.h8
-rw-r--r--src/Persistent_cohomology/test/betti_numbers_unit_test.cpp9
-rw-r--r--src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp8
-rw-r--r--src/Rips_complex/example/example_rips_complex_from_off_file.cpp8
-rw-r--r--src/Rips_complex/utilities/ripscomplex.md1
-rw-r--r--src/Rips_complex/utilities/sparse_rips_persistence.cpp15
-rw-r--r--src/cmake/modules/GUDHI_third_party_libraries.cmake2
-rw-r--r--src/common/doc/main_page.md1
-rw-r--r--src/common/include/gudhi/Unitary_tests_utils.h1
-rw-r--r--src/python/CMakeLists.txt81
-rwxr-xr-xsrc/python/doc/conf.py1
-rw-r--r--src/python/doc/index.rst12
-rw-r--r--src/python/doc/installation.rst16
-rw-r--r--src/python/doc/representations.rst48
-rw-r--r--src/python/doc/representations_sum.inc14
-rw-r--r--src/python/doc/wasserstein_distance_sum.inc14
-rw-r--r--src/python/doc/wasserstein_distance_user.rst40
-rwxr-xr-xsrc/python/example/diagram_vectorizations_distances_kernels.py133
-rw-r--r--src/python/gudhi/__init__.py.in26
-rw-r--r--src/python/gudhi/alpha_complex.pyx19
-rw-r--r--src/python/gudhi/bottleneck.pyx17
-rw-r--r--src/python/gudhi/cubical_complex.pyx21
-rw-r--r--src/python/gudhi/euclidean_strong_witness_complex.pyx19
-rw-r--r--src/python/gudhi/euclidean_witness_complex.pyx19
-rw-r--r--src/python/gudhi/nerve_gic.pyx17
-rw-r--r--src/python/gudhi/off_reader.pyx19
-rw-r--r--src/python/gudhi/periodic_cubical_complex.pyx21
-rw-r--r--src/python/gudhi/persistence_graphical_tools.py17
-rw-r--r--src/python/gudhi/reader_utils.pyx23
-rw-r--r--src/python/gudhi/representations/__init__.py6
-rw-r--r--src/python/gudhi/representations/kernel_methods.py206
-rw-r--r--src/python/gudhi/representations/metrics.py243
-rw-r--r--src/python/gudhi/representations/preprocessing.py305
-rw-r--r--src/python/gudhi/representations/vector_methods.py485
-rw-r--r--src/python/gudhi/rips_complex.pyx17
-rw-r--r--src/python/gudhi/simplex_tree.pyx32
-rw-r--r--src/python/gudhi/strong_witness_complex.pyx19
-rw-r--r--src/python/gudhi/subsampling.pyx31
-rw-r--r--src/python/gudhi/tangential_complex.pyx19
-rw-r--r--src/python/gudhi/wasserstein.py98
-rw-r--r--src/python/gudhi/witness_complex.pyx19
-rw-r--r--src/python/include/Alpha_complex_interface.h11
-rwxr-xr-xsrc/python/test/test_representations.py11
-rwxr-xr-xsrc/python/test/test_wasserstein_distance.py48
64 files changed, 2380 insertions, 386 deletions
diff --git a/src/Alpha_complex/benchmark/Alpha_complex_3d_benchmark.cpp b/src/Alpha_complex/benchmark/Alpha_complex_3d_benchmark.cpp
index 005a712a..99ad94b9 100644
--- a/src/Alpha_complex/benchmark/Alpha_complex_3d_benchmark.cpp
+++ b/src/Alpha_complex/benchmark/Alpha_complex_3d_benchmark.cpp
@@ -115,7 +115,7 @@ void benchmark_weighted_points_on_torus_3D(const std::string& msg) {
std::cout << " Alpha complex 3d on torus with " << nb_points << " points." << std::endl;
std::vector<K::Point_d> points_on_torus = Gudhi::generate_points_on_torus_3D<K>(nb_points, 1.0, 0.5);
- using Point = typename Weighted_alpha_complex_3d::Point_3;
+ using Point = typename Weighted_alpha_complex_3d::Bare_point_3;
using Weighted_point = typename Weighted_alpha_complex_3d::Weighted_point_3;
std::vector<Weighted_point> points;
@@ -206,7 +206,7 @@ void benchmark_weighted_periodic_points(const std::string& msg) {
std::cout << " Weighted periodic alpha complex 3d with " << nb_points * nb_points * nb_points << " points."
<< std::endl;
- using Point = typename Weighted_periodic_alpha_complex_3d::Point_3;
+ using Point = typename Weighted_periodic_alpha_complex_3d::Bare_point_3;
using Weighted_point = typename Weighted_periodic_alpha_complex_3d::Weighted_point_3;
std::vector<Weighted_point> points;
diff --git a/src/Alpha_complex/doc/Intro_alpha_complex.h b/src/Alpha_complex/doc/Intro_alpha_complex.h
index b075d1fc..adc1378f 100644
--- a/src/Alpha_complex/doc/Intro_alpha_complex.h
+++ b/src/Alpha_complex/doc/Intro_alpha_complex.h
@@ -51,6 +51,17 @@ namespace alpha_complex {
* - For people only interested in the topology of the \ref alpha_complex (for instance persistence),
* \ref alpha_complex is equivalent to the \ref cech_complex and much smaller if you do not bound the radii.
* \ref cech_complex can still make sense in higher dimension precisely because you can bound the radii.
+ * - Using the default `CGAL::Epeck_d` makes the construction safe. If you pass exact=true to create_complex, the
+ * filtration values are the exact ones converted to the filtration value type of the simplicial complex. This can be
+ * very slow. If you pass exact=false (the default), the filtration values are only guaranteed to have a small
+ * multiplicative error compared to the exact value, see <code><a class="el" target="_blank"
+ * href="https://doc.cgal.org/latest/Number_types/classCGAL_1_1Lazy__exact__nt.html">
+ * CGAL::Lazy_exact_nt<NT>::set_relative_precision_of_to_double</a></code> for details. A drawback, when computing
+ * persistence, is that an empty exact interval [10^12,10^12] may become a non-empty approximate interval
+ * [10^12,10^12+10^6]. Using `CGAL::Epick_d` makes the computations slightly faster, and the combinatorics are still
+ * exact, but the computation of filtration values can exceptionally be arbitrarily bad. In all cases, we still
+ * guarantee that the output is a valid filtration (faces have a filtration value no larger than their cofaces).
+ * - For performances reasons, it is advised to use `Alpha_complex` with \ref cgal &ge; 5.0.0.
*
* \section pointsexample Example from points
*
diff --git a/src/Alpha_complex/example/Alpha_complex_from_off.cpp b/src/Alpha_complex/example/Alpha_complex_from_off.cpp
index d411e90a..220a66de 100644
--- a/src/Alpha_complex/example/Alpha_complex_from_off.cpp
+++ b/src/Alpha_complex/example/Alpha_complex_from_off.cpp
@@ -2,8 +2,6 @@
// to construct a simplex_tree from alpha complex
#include <gudhi/Simplex_tree.h>
-#include <CGAL/Epick_d.h>
-
#include <iostream>
#include <string>
@@ -23,22 +21,21 @@ int main(int argc, char **argv) {
// ----------------------------------------------------------------------------
// Init of an alpha complex from an OFF file
// ----------------------------------------------------------------------------
- using Kernel = CGAL::Epick_d< CGAL::Dynamic_dimension_tag >;
- Gudhi::alpha_complex::Alpha_complex<Kernel> alpha_complex_from_file(off_file_name);
+ Gudhi::alpha_complex::Alpha_complex<> alpha_complex_from_file(off_file_name);
- std::streambuf* streambufffer;
+ std::streambuf* streambuffer;
std::ofstream ouput_file_stream;
if (argc == 4) {
ouput_file_stream.open(std::string(argv[3]));
- streambufffer = ouput_file_stream.rdbuf();
+ streambuffer = ouput_file_stream.rdbuf();
} else {
- streambufffer = std::cout.rdbuf();
+ streambuffer = std::cout.rdbuf();
}
Gudhi::Simplex_tree<> simplex;
if (alpha_complex_from_file.create_complex(simplex, alpha_square_max_value)) {
- std::ostream output_stream(streambufffer);
+ std::ostream output_stream(streambuffer);
// ----------------------------------------------------------------------------
// Display information about the alpha complex
diff --git a/src/Alpha_complex/example/Alpha_complex_from_points.cpp b/src/Alpha_complex/example/Alpha_complex_from_points.cpp
index 981aa470..6526ca3a 100644
--- a/src/Alpha_complex/example/Alpha_complex_from_points.cpp
+++ b/src/Alpha_complex/example/Alpha_complex_from_points.cpp
@@ -2,12 +2,13 @@
// to construct a simplex_tree from alpha complex
#include <gudhi/Simplex_tree.h>
-#include <CGAL/Epick_d.h>
+#include <CGAL/Epeck_d.h>
#include <iostream>
#include <vector>
-using Kernel = CGAL::Epick_d< CGAL::Dimension_tag<2> >;
+// Explicit dimension 2 Epeck_d kernel
+using Kernel = CGAL::Epeck_d< CGAL::Dimension_tag<2> >;
using Point = Kernel::Point_d;
using Vector_of_points = std::vector<Point>;
diff --git a/src/Alpha_complex/example/CMakeLists.txt b/src/Alpha_complex/example/CMakeLists.txt
index b069b443..b0337934 100644
--- a/src/Alpha_complex/example/CMakeLists.txt
+++ b/src/Alpha_complex/example/CMakeLists.txt
@@ -5,9 +5,12 @@ if (NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
target_link_libraries(Alpha_complex_example_from_points ${CGAL_LIBRARY})
add_executable ( Alpha_complex_example_from_off Alpha_complex_from_off.cpp )
target_link_libraries(Alpha_complex_example_from_off ${CGAL_LIBRARY})
+ add_executable ( Alpha_complex_example_fast_from_off Fast_alpha_complex_from_off.cpp )
+ target_link_libraries(Alpha_complex_example_fast_from_off ${CGAL_LIBRARY})
if (TBB_FOUND)
target_link_libraries(Alpha_complex_example_from_points ${TBB_LIBRARIES})
target_link_libraries(Alpha_complex_example_from_off ${TBB_LIBRARIES})
+ target_link_libraries(Alpha_complex_example_fast_from_off ${TBB_LIBRARIES})
endif()
add_test(NAME Alpha_complex_example_from_points COMMAND $<TARGET_FILE:Alpha_complex_example_from_points>)
@@ -16,7 +19,13 @@ if (NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
"${CMAKE_SOURCE_DIR}/data/points/alphacomplexdoc.off" "60.0" "${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_result_60.txt")
add_test(NAME Alpha_complex_example_from_off_32 COMMAND $<TARGET_FILE:Alpha_complex_example_from_off>
"${CMAKE_SOURCE_DIR}/data/points/alphacomplexdoc.off" "32.0" "${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_result_32.txt")
- if (DIFF_PATH)
+
+ add_test(NAME Alpha_complex_example_fast_from_off_60 COMMAND $<TARGET_FILE:Alpha_complex_example_fast_from_off>
+ "${CMAKE_SOURCE_DIR}/data/points/alphacomplexdoc.off" "60.0" "${CMAKE_CURRENT_BINARY_DIR}/fastalphaoffreader_result_60.txt")
+ add_test(NAME Alpha_complex_example_fast_from_off_32 COMMAND $<TARGET_FILE:Alpha_complex_example_fast_from_off>
+ "${CMAKE_SOURCE_DIR}/data/points/alphacomplexdoc.off" "32.0" "${CMAKE_CURRENT_BINARY_DIR}/fastalphaoffreader_result_32.txt")
+
+if (DIFF_PATH)
# Do not forget to copy test results files in current binary dir
file(COPY "alphaoffreader_for_doc_32.txt" DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/)
file(COPY "alphaoffreader_for_doc_60.txt" DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/)
@@ -25,6 +34,11 @@ if (NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_result_60.txt ${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_for_doc_60.txt)
add_test(Alpha_complex_example_from_off_32_diff_files ${DIFF_PATH}
${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_result_32.txt ${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_for_doc_32.txt)
+
+ add_test(Alpha_complex_example_fast_from_off_60_diff_files ${DIFF_PATH}
+ ${CMAKE_CURRENT_BINARY_DIR}/fastalphaoffreader_result_60.txt ${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_for_doc_60.txt)
+ add_test(Alpha_complex_example_fast_from_off_32_diff_files ${DIFF_PATH}
+ ${CMAKE_CURRENT_BINARY_DIR}/fastalphaoffreader_result_32.txt ${CMAKE_CURRENT_BINARY_DIR}/alphaoffreader_for_doc_32.txt)
endif()
add_executable ( Alpha_complex_example_weighted_3d_from_points Weighted_alpha_complex_3d_from_points.cpp )
diff --git a/src/Alpha_complex/example/Fast_alpha_complex_from_off.cpp b/src/Alpha_complex/example/Fast_alpha_complex_from_off.cpp
new file mode 100644
index 00000000..f181005a
--- /dev/null
+++ b/src/Alpha_complex/example/Fast_alpha_complex_from_off.cpp
@@ -0,0 +1,65 @@
+#include <gudhi/Alpha_complex.h>
+// to construct a simplex_tree from alpha complex
+#include <gudhi/Simplex_tree.h>
+
+#include <CGAL/Epick_d.h>
+
+#include <iostream>
+#include <string>
+
+void usage(int nbArgs, char * const progName) {
+ std::cerr << "Error: Number of arguments (" << nbArgs << ") is not correct\n";
+ std::cerr << "Usage: " << progName << " filename.off alpha_square_max_value [ouput_file.txt]\n";
+ std::cerr << " i.e.: " << progName << " ../../data/points/alphacomplexdoc.off 60.0\n";
+ exit(-1); // ----- >>
+}
+
+int main(int argc, char **argv) {
+ if ((argc != 3) && (argc != 4)) usage(argc, (argv[0] - 1));
+
+ std::string off_file_name {argv[1]};
+ double alpha_square_max_value {atof(argv[2])};
+
+ // WARNING : CGAL::Epick_d is fast but not safe (unlike CGAL::Epeck_d)
+ // (i.e. when the points are on a grid)
+ using Fast_kernel = CGAL::Epick_d<CGAL::Dynamic_dimension_tag>;
+ // ----------------------------------------------------------------------------
+ // Init of an alpha complex from an OFF file
+ // ----------------------------------------------------------------------------
+ Gudhi::alpha_complex::Alpha_complex<Fast_kernel> alpha_complex_from_file(off_file_name);
+
+ std::streambuf* streambuffer;
+ std::ofstream ouput_file_stream;
+
+ if (argc == 4) {
+ ouput_file_stream.open(std::string(argv[3]));
+ streambuffer = ouput_file_stream.rdbuf();
+ } else {
+ streambuffer = std::cout.rdbuf();
+ }
+
+ Gudhi::Simplex_tree<> simplex;
+ if (alpha_complex_from_file.create_complex(simplex, alpha_square_max_value)) {
+ std::ostream output_stream(streambuffer);
+
+ // ----------------------------------------------------------------------------
+ // Display information about the alpha complex
+ // ----------------------------------------------------------------------------
+ output_stream << "Alpha complex is of dimension " << simplex.dimension() <<
+ " - " << simplex.num_simplices() << " simplices - " <<
+ simplex.num_vertices() << " vertices." << std::endl;
+
+ output_stream << "Iterator on alpha complex simplices in the filtration order, with [filtration value]:" <<
+ std::endl;
+ for (auto f_simplex : simplex.filtration_simplex_range()) {
+ output_stream << " ( ";
+ for (auto vertex : simplex.simplex_vertex_range(f_simplex)) {
+ output_stream << vertex << " ";
+ }
+ output_stream << ") -> " << "[" << simplex.filtration(f_simplex) << "] ";
+ output_stream << std::endl;
+ }
+ }
+ ouput_file_stream.close();
+ return 0;
+}
diff --git a/src/Alpha_complex/example/Weighted_alpha_complex_3d_from_points.cpp b/src/Alpha_complex/example/Weighted_alpha_complex_3d_from_points.cpp
index ac11b68c..fcf80802 100644
--- a/src/Alpha_complex/example/Weighted_alpha_complex_3d_from_points.cpp
+++ b/src/Alpha_complex/example/Weighted_alpha_complex_3d_from_points.cpp
@@ -10,7 +10,7 @@
// Complexity = FAST, weighted = true, periodic = false
using Weighted_alpha_complex_3d =
Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, true, false>;
-using Point = Weighted_alpha_complex_3d::Point_3;
+using Bare_point = Weighted_alpha_complex_3d::Bare_point_3;
using Weighted_point = Weighted_alpha_complex_3d::Weighted_point_3;
int main(int argc, char **argv) {
@@ -18,11 +18,11 @@ int main(int argc, char **argv) {
// Init of a list of points and weights from a small molecule
// ----------------------------------------------------------------------------
std::vector<Weighted_point> weighted_points;
- weighted_points.push_back(Weighted_point(Point(1, -1, -1), 4.));
- weighted_points.push_back(Weighted_point(Point(-1, 1, -1), 4.));
- weighted_points.push_back(Weighted_point(Point(-1, -1, 1), 4.));
- weighted_points.push_back(Weighted_point(Point(1, 1, 1), 4.));
- weighted_points.push_back(Weighted_point(Point(2, 2, 2), 1.));
+ weighted_points.push_back(Weighted_point(Bare_point(1, -1, -1), 4.));
+ weighted_points.push_back(Weighted_point(Bare_point(-1, 1, -1), 4.));
+ weighted_points.push_back(Weighted_point(Bare_point(-1, -1, 1), 4.));
+ weighted_points.push_back(Weighted_point(Bare_point(1, 1, 1), 4.));
+ weighted_points.push_back(Weighted_point(Bare_point(2, 2, 2), 1.));
// ----------------------------------------------------------------------------
// Init of an alpha complex from the list of points
diff --git a/src/Alpha_complex/include/gudhi/Alpha_complex.h b/src/Alpha_complex/include/gudhi/Alpha_complex.h
index 8919cdb9..0c2569c8 100644
--- a/src/Alpha_complex/include/gudhi/Alpha_complex.h
+++ b/src/Alpha_complex/include/gudhi/Alpha_complex.h
@@ -20,11 +20,12 @@
#include <math.h> // isnan, fmax
#include <CGAL/Delaunay_triangulation.h>
-#include <CGAL/Epick_d.h>
+#include <CGAL/Epeck_d.h> // For EXACT or SAFE version
+#include <CGAL/Epick_d.h> // For FAST version
#include <CGAL/Spatial_sort_traits_adapter_d.h>
#include <CGAL/property_map.h> // for CGAL::Identity_property_map
-#include <CGAL/NT_converter.h>
#include <CGAL/version.h> // for CGAL_VERSION_NR
+#include <CGAL/NT_converter.h>
#include <Eigen/src/Core/util/Macros.h> // for EIGEN_VERSION_AT_LEAST
@@ -39,17 +40,20 @@
// Make compilation fail - required for external projects - https://github.com/GUDHI/gudhi-devel/issues/10
#if CGAL_VERSION_NR < 1041101000
-# error Alpha_complex_3d is only available for CGAL >= 4.11
+# error Alpha_complex is only available for CGAL >= 4.11
#endif
#if !EIGEN_VERSION_AT_LEAST(3,1,0)
-# error Alpha_complex_3d is only available for Eigen3 >= 3.1.0 installed with CGAL
+# error Alpha_complex is only available for Eigen3 >= 3.1.0 installed with CGAL
#endif
namespace Gudhi {
namespace alpha_complex {
+template<typename D> struct Is_Epeck_D { static const bool value = false; };
+template<typename D> struct Is_Epeck_D<CGAL::Epeck_d<D>> { static const bool value = true; };
+
/**
* \class Alpha_complex Alpha_complex.h gudhi/Alpha_complex.h
* \brief Alpha complex data structure.
@@ -63,17 +67,31 @@ namespace alpha_complex {
*
* Please refer to \ref alpha_complex for examples.
*
- * The complex is a template class requiring an Epick_d <a target="_blank"
+ * The complex is a template class requiring an <a target="_blank"
+ * href="https://doc.cgal.org/latest/Kernel_d/structCGAL_1_1Epeck__d.html">CGAL::Epeck_d</a>,
+ * or an <a target="_blank"
+ * href="https://doc.cgal.org/latest/Kernel_d/structCGAL_1_1Epick__d.html">CGAL::Epick_d</a> <a target="_blank"
* href="http://doc.cgal.org/latest/Kernel_d/index.html#Chapter_dD_Geometry_Kernel">dD Geometry Kernel</a>
* \cite cgal:s-gkd-15b from CGAL as template, default value is <a target="_blank"
- * href="http://doc.cgal.org/latest/Kernel_d/classCGAL_1_1Epick__d.html">CGAL::Epick_d</a>
+ * href="https://doc.cgal.org/latest/Kernel_d/structCGAL_1_1Epeck__d.html">CGAL::Epeck_d</a>
* < <a target="_blank" href="http://doc.cgal.org/latest/Kernel_23/classCGAL_1_1Dynamic__dimension__tag.html">
* CGAL::Dynamic_dimension_tag </a> >
*
- * \remark When Alpha_complex is constructed with an infinite value of alpha, the complex is a Delaunay complex.
- *
+ * \remark
+ * - When Alpha_complex is constructed with an infinite value of alpha, the complex is a Delaunay complex.
+ * - Using the default `CGAL::Epeck_d` makes the construction safe. If you pass exact=true to create_complex, the
+ * filtration values are the exact ones converted to the filtration value type of the simplicial complex. This can be
+ * very slow. If you pass exact=false (the default), the filtration values are only guaranteed to have a small
+ * multiplicative error compared to the exact value, see <code><a class="el" target="_blank"
+ * href="https://doc.cgal.org/latest/Number_types/classCGAL_1_1Lazy__exact__nt.html">
+ * CGAL::Lazy_exact_nt<NT>::set_relative_precision_of_to_double</a></code> for details. A drawback, when computing
+ * persistence, is that an empty exact interval [10^12,10^12] may become a non-empty approximate interval
+ * [10^12,10^12+10^6]. Using `CGAL::Epick_d` makes the computations slightly faster, and the combinatorics are still
+ * exact, but the computation of filtration values can exceptionally be arbitrarily bad. In all cases, we still
+ * guarantee that the output is a valid filtration (faces have a filtration value no larger than their cofaces).
+ * - For performances reasons, it is advised to use `Alpha_complex` with \ref cgal &ge; 5.0.0.
*/
-template<class Kernel = CGAL::Epick_d<CGAL::Dynamic_dimension_tag>>
+template<class Kernel = CGAL::Epeck_d<CGAL::Dynamic_dimension_tag>>
class Alpha_complex {
public:
// Add an int in TDS to save point index in the structure
@@ -184,6 +202,12 @@ class Alpha_complex {
private:
template<typename InputPointRange >
void init_from_range(const InputPointRange& points) {
+ #if CGAL_VERSION_NR < 1050000000
+ if (Is_Epeck_D<Kernel>::value)
+ std::cerr << "It is strongly advised to use a CGAL version >= 5.0 with Epeck_d Kernel for performance reasons."
+ << std::endl;
+ #endif
+
auto first = std::begin(points);
auto last = std::end(points);
@@ -237,6 +261,8 @@ class Alpha_complex {
* @param[in] complex SimplicialComplexForAlpha to be created.
* @param[in] max_alpha_square maximum for alpha square value. Default value is +\f$\infty\f$, and there is very
* little point using anything else since it does not save time.
+ * @param[in] exact Exact filtration values computation. Not exact if `Kernel` is not <a target="_blank"
+ * href="https://doc.cgal.org/latest/Kernel_d/structCGAL_1_1Epeck__d.html">CGAL::Epeck_d</a>.
*
* @return true if creation succeeds, false otherwise.
*
@@ -248,7 +274,8 @@ class Alpha_complex {
template <typename SimplicialComplexForAlpha,
typename Filtration_value = typename SimplicialComplexForAlpha::Filtration_value>
bool create_complex(SimplicialComplexForAlpha& complex,
- Filtration_value max_alpha_square = std::numeric_limits<Filtration_value>::infinity()) {
+ Filtration_value max_alpha_square = std::numeric_limits<Filtration_value>::infinity(),
+ bool exact = false) {
// From SimplicialComplexForAlpha type required to insert into a simplicial complex (with or without subfaces).
typedef typename SimplicialComplexForAlpha::Vertex_handle Vertex_handle;
typedef typename SimplicialComplexForAlpha::Simplex_handle Simplex_handle;
@@ -324,9 +351,13 @@ class Alpha_complex {
if (f_simplex_dim > 0) {
// squared_radius function initialization
Squared_Radius squared_radius = kernel_.compute_squared_radius_d_object();
- CGAL::NT_converter<typename Geom_traits::FT, Filtration_value> cv;
- alpha_complex_filtration = cv(squared_radius(pointVector.begin(), pointVector.end()));
+ CGAL::NT_converter<typename Geom_traits::FT, Filtration_value> cv;
+ auto sqrad = squared_radius(pointVector.begin(), pointVector.end());
+#if CGAL_VERSION_NR >= 1050000000
+ if(exact) CGAL::exact(sqrad);
+#endif
+ alpha_complex_filtration = cv(sqrad);
}
complex.assign_filtration(f_simplex, alpha_complex_filtration);
#ifdef DEBUG_TRACES
diff --git a/src/Alpha_complex/include/gudhi/Alpha_complex_3d.h b/src/Alpha_complex/include/gudhi/Alpha_complex_3d.h
index 13ebb9c1..7f96c94c 100644
--- a/src/Alpha_complex/include/gudhi/Alpha_complex_3d.h
+++ b/src/Alpha_complex/include/gudhi/Alpha_complex_3d.h
@@ -43,7 +43,7 @@
#include <vector>
#include <unordered_map>
#include <stdexcept>
-#include <cstddef>
+#include <cstddef> // for std::size_t
#include <memory> // for std::unique_ptr
#include <type_traits> // for std::conditional and std::enable_if
#include <limits> // for numeric_limits<>
@@ -97,7 +97,7 @@ struct Value_from_iterator<complexity::EXACT> {
* \details
* The data structure is constructing a <a href="https://doc.cgal.org/latest/Alpha_shapes_3/index.html">CGAL 3D Alpha
* Shapes</a> from a range of points (can be read from an OFF file, cf. Points_off_reader).
- * Duplicate points are inserted once in the Alpha_complex. This is the reason why the vertices may be not contiguous.
+ * Duplicate points are inserted once in the Alpha_complex.
*
* \tparam Complexity shall be `Gudhi::alpha_complex::complexity` type. Default value is
* `Gudhi::alpha_complex::complexity::SAFE`.
@@ -225,23 +225,23 @@ class Alpha_complex_3d {
* Must be compatible with double. */
using FT = typename Alpha_shape_3::FT;
- /** \brief Gives public access to the Point_3 type. Here is a Point_3 constructor example:
+ /** \brief Gives public access to the Bare_point_3 (bare aka. unweighed) type.
+ * Here is a Bare_point_3 constructor example:
\code{.cpp}
using Alpha_complex_3d = Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, false, false>;
// x0 = 1., y0 = -1.1, z0 = -1..
-Alpha_complex_3d::Point_3 p0(1., -1.1, -1.);
+Alpha_complex_3d::Bare_point_3 p0(1., -1.1, -1.);
\endcode
* */
- using Point_3 = typename Kernel::Point_3;
+ using Bare_point_3 = typename Kernel::Point_3;
/** \brief Gives public access to the Weighted_point_3 type. A Weighted point can be constructed as follows:
\code{.cpp}
-using Weighted_alpha_complex_3d =
- Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, true, false>;
+using Weighted_alpha_complex_3d = Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, true, false>;
// x0 = 1., y0 = -1.1, z0 = -1., weight = 4.
-Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point_3(1., -1.1, -1.), 4.);
+Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Bare_point_3(1., -1.1, -1.), 4.);
\endcode
*
* Note: This type is defined to void if Alpha complex is not weighted.
@@ -249,6 +249,11 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
* */
using Weighted_point_3 = typename Triangulation_3<Kernel, Tds, Weighted, Periodic>::Weighted_point_3;
+ /** \brief `Alpha_complex_3d::Point_3` type is either a `Alpha_complex_3d::Bare_point_3` (Weighted = false) or a
+ * `Alpha_complex_3d::Weighted_point_3` (Weighted = true).
+ */
+ using Point_3 = typename Alpha_shape_3::Point;
+
private:
using Dispatch =
CGAL::Dispatch_output_iterator<CGAL::cpp11::tuple<CGAL::Object, FT>,
@@ -264,13 +269,12 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
public:
/** \brief Alpha_complex constructor from a list of points.
*
- * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Point_3` or
- * `Alpha_complex_3d::Weighted_point_3`.
+ * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Point_3`.
*
* @pre Available if Alpha_complex_3d is not Periodic.
*
* The type InputPointRange must be a range for which std::begin and std::end return input iterators on a
- * `Alpha_complex_3d::Point_3` or a `Alpha_complex_3d::Weighted_point_3`.
+ * `Alpha_complex_3d::Point_3`.
*/
template <typename InputPointRange>
Alpha_complex_3d(const InputPointRange& points) {
@@ -284,13 +288,13 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
*
* @exception std::invalid_argument In debug mode, if points and weights do not have the same size.
*
- * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Point_3`.
+ * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Bare_point_3`.
* @param[in] weights Range of weights on points. Weights shall be in double.
*
* @pre Available if Alpha_complex_3d is Weighted and not Periodic.
*
* The type InputPointRange must be a range for which std::begin and
- * std::end return input iterators on a `Alpha_complex_3d::Point_3`.
+ * std::end return input iterators on a `Alpha_complex_3d::Bare_point_3`.
* The type WeightRange must be a range for which std::begin and
* std::end return an input iterator on a double.
*/
@@ -318,8 +322,7 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
*
* @exception std::invalid_argument In debug mode, if the size of the cuboid in every directions is not the same.
*
- * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Point_3` or
- * `Alpha_complex_3d::Weighted_point_3`.
+ * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Point_3`.
* @param[in] x_min Iso-oriented cuboid x_min.
* @param[in] y_min Iso-oriented cuboid y_min.
* @param[in] z_min Iso-oriented cuboid z_min.
@@ -330,7 +333,7 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
* @pre Available if Alpha_complex_3d is Periodic.
*
* The type InputPointRange must be a range for which std::begin and std::end return input iterators on a
- * `Alpha_complex_3d::Point_3` or a `Alpha_complex_3d::Weighted_point_3`.
+ * `Alpha_complex_3d::Point_3`.
*
* @note In weighted version, please check weights are greater than zero, and lower than 1/64*cuboid length
* squared.
@@ -366,7 +369,7 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
* @exception std::invalid_argument In debug mode, if a weight is negative, zero, or greater than 1/64*cuboid length
* squared.
*
- * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Point_3`.
+ * @param[in] points Range of points to triangulate. Points must be in `Alpha_complex_3d::Bare_point_3`.
* @param[in] weights Range of weights on points. Weights shall be in double.
* @param[in] x_min Iso-oriented cuboid x_min.
* @param[in] y_min Iso-oriented cuboid y_min.
@@ -378,7 +381,7 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
* @pre Available if Alpha_complex_3d is Weighted and Periodic.
*
* The type InputPointRange must be a range for which std::begin and
- * std::end return input iterators on a `Alpha_complex_3d::Point_3`.
+ * std::end return input iterators on a `Alpha_complex_3d::Bare_point_3`.
* The type WeightRange must be a range for which std::begin and
* std::end return an input iterator on a double.
* The type of x_min, y_min, z_min, x_max, y_max and z_max must be a double.
@@ -452,9 +455,7 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
return false; // ----- >>
}
- // using Filtration_value = typename SimplicialComplexForAlpha3d::Filtration_value;
using Complex_vertex_handle = typename SimplicialComplexForAlpha3d::Vertex_handle;
- using Alpha_shape_simplex_tree_map = std::unordered_map<Alpha_vertex_handle, Complex_vertex_handle>;
using Simplex_tree_vector_vertex = std::vector<Complex_vertex_handle>;
#ifdef DEBUG_TRACES
@@ -474,7 +475,6 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
std::cout << "filtration_with_alpha_values returns : " << objects.size() << " objects" << std::endl;
#endif // DEBUG_TRACES
- Alpha_shape_simplex_tree_map map_cgal_simplex_tree;
using Alpha_value_iterator = typename std::vector<FT>::const_iterator;
Alpha_value_iterator alpha_value_iterator = alpha_values.begin();
for (auto object_iterator : objects) {
@@ -484,7 +484,8 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
if (const Cell_handle* cell = CGAL::object_cast<Cell_handle>(&object_iterator)) {
for (auto i = 0; i < 4; i++) {
#ifdef DEBUG_TRACES
- std::cout << "from cell[" << i << "]=" << (*cell)->vertex(i)->point() << std::endl;
+ std::cout << "from cell[" << i << "] - Point coordinates (" << (*cell)->vertex(i)->point() << ")"
+ << std::endl;
#endif // DEBUG_TRACES
vertex_list.push_back((*cell)->vertex(i));
}
@@ -495,7 +496,8 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
for (auto i = 0; i < 4; i++) {
if ((*facet).second != i) {
#ifdef DEBUG_TRACES
- std::cout << "from facet=[" << i << "]" << (*facet).first->vertex(i)->point() << std::endl;
+ std::cout << "from facet=[" << i << "] - Point coordinates (" << (*facet).first->vertex(i)->point() << ")"
+ << std::endl;
#endif // DEBUG_TRACES
vertex_list.push_back((*facet).first->vertex(i));
}
@@ -506,7 +508,8 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
} else if (const Edge* edge = CGAL::object_cast<Edge>(&object_iterator)) {
for (auto i : {(*edge).second, (*edge).third}) {
#ifdef DEBUG_TRACES
- std::cout << "from edge[" << i << "]=" << (*edge).first->vertex(i)->point() << std::endl;
+ std::cout << "from edge[" << i << "] - Point coordinates (" << (*edge).first->vertex(i)->point() << ")"
+ << std::endl;
#endif // DEBUG_TRACES
vertex_list.push_back((*edge).first->vertex(i));
}
@@ -516,7 +519,7 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
} else if (const Alpha_vertex_handle* vertex = CGAL::object_cast<Alpha_vertex_handle>(&object_iterator)) {
#ifdef DEBUG_TRACES
count_vertices++;
- std::cout << "from vertex=" << (*vertex)->point() << std::endl;
+ std::cout << "from vertex - Point coordinates (" << (*vertex)->point() << ")" << std::endl;
#endif // DEBUG_TRACES
vertex_list.push_back((*vertex));
}
@@ -528,7 +531,8 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
// alpha shape not found
Complex_vertex_handle vertex = map_cgal_simplex_tree.size();
#ifdef DEBUG_TRACES
- std::cout << "vertex [" << the_alpha_shape_vertex->point() << "] not found - insert " << vertex << std::endl;
+ std::cout << "Point (" << the_alpha_shape_vertex->point() << ") not found - insert new vertex id " << vertex
+ << std::endl;
#endif // DEBUG_TRACES
the_simplex.push_back(vertex);
map_cgal_simplex_tree.emplace(the_alpha_shape_vertex, vertex);
@@ -536,7 +540,7 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
// alpha shape found
Complex_vertex_handle vertex = the_map_iterator->second;
#ifdef DEBUG_TRACES
- std::cout << "vertex [" << the_alpha_shape_vertex->point() << "] found in " << vertex << std::endl;
+ std::cout << "Point (" << the_alpha_shape_vertex->point() << ") found as vertex id " << vertex << std::endl;
#endif // DEBUG_TRACES
the_simplex.push_back(vertex);
}
@@ -567,9 +571,32 @@ Weighted_alpha_complex_3d::Weighted_point_3 wp0(Weighted_alpha_complex_3d::Point
return true;
}
+ /** \brief get_point returns the point corresponding to the vertex given as parameter.
+ *
+ * @param[in] vertex Vertex handle of the point to retrieve.
+ * @return The point found.
+ * @exception std::out_of_range In case vertex is not found (cf. std::vector::at).
+ */
+ const Point_3& get_point(std::size_t vertex) {
+ if (map_cgal_simplex_tree.size() != cgal_vertex_iterator_vector.size()) {
+ cgal_vertex_iterator_vector.resize(map_cgal_simplex_tree.size());
+ for (auto map_iterator : map_cgal_simplex_tree) {
+ cgal_vertex_iterator_vector[map_iterator.second] = map_iterator.first;
+ }
+
+ }
+ auto cgal_vertex_iterator = cgal_vertex_iterator_vector.at(vertex);
+ return cgal_vertex_iterator->point();
+ }
+
private:
// use of a unique_ptr on cgal Alpha_shape_3, as copy and default constructor is not available - no need to be freed
std::unique_ptr<Alpha_shape_3> alpha_shape_3_ptr_;
+
+ // Map type to switch from CGAL vertex iterator to simplex tree vertex handle.
+ std::unordered_map<Alpha_vertex_handle, std::size_t> map_cgal_simplex_tree;
+ // Vector type to switch from simplex tree vertex handle to CGAL vertex iterator.
+ std::vector<Alpha_vertex_handle> cgal_vertex_iterator_vector;
};
} // namespace alpha_complex
diff --git a/src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp b/src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp
index 1102838a..cd698a27 100644
--- a/src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp
+++ b/src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp
@@ -56,21 +56,52 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_3d_from_points) {
// -----------------
std::cout << "Fast alpha complex 3d" << std::endl;
- Fast_alpha_complex_3d alpha_complex(get_points<Fast_alpha_complex_3d::Point_3>());
+ std::vector<Fast_alpha_complex_3d::Bare_point_3> points = get_points<Fast_alpha_complex_3d::Bare_point_3>();
+ Fast_alpha_complex_3d alpha_complex(points);
Gudhi::Simplex_tree<> stree;
alpha_complex.create_complex(stree);
+ for (std::size_t index = 0; index < points.size(); index++) {
+ bool found = false;
+ for (auto point : points) {
+ if (point == alpha_complex.get_point(index)) {
+ found = true;
+ break;
+ }
+ }
+ // Check all points from alpha complex are found in the input point cloud
+ BOOST_CHECK(found);
+ }
+ // Exception if we go out of range
+ BOOST_CHECK_THROW(alpha_complex.get_point(points.size()), std::out_of_range);
+
// -----------------
// Exact version
// -----------------
std::cout << "Exact alpha complex 3d" << std::endl;
- Exact_alpha_complex_3d exact_alpha_complex(get_points<Exact_alpha_complex_3d::Point_3>());
+ std::vector<Exact_alpha_complex_3d::Bare_point_3> exact_points = get_points<Exact_alpha_complex_3d::Bare_point_3>();
+ Exact_alpha_complex_3d exact_alpha_complex(exact_points);
Gudhi::Simplex_tree<> exact_stree;
exact_alpha_complex.create_complex(exact_stree);
+ for (std::size_t index = 0; index < exact_points.size(); index++) {
+ bool found = false;
+ Exact_alpha_complex_3d::Bare_point_3 ap = exact_alpha_complex.get_point(index);
+ for (auto point : points) {
+ if ((point.x() == ap.x()) && (point.y() == ap.y()) && (point.z() == ap.z())) {
+ found = true;
+ break;
+ }
+ }
+ // Check all points from alpha complex are found in the input point cloud
+ BOOST_CHECK(found);
+ }
+ // Exception if we go out of range
+ BOOST_CHECK_THROW(exact_alpha_complex.get_point(exact_points.size()), std::out_of_range);
+
// ---------------------
// Compare both versions
// ---------------------
@@ -110,11 +141,27 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_3d_from_points) {
// -----------------
std::cout << "Safe alpha complex 3d" << std::endl;
- Safe_alpha_complex_3d safe_alpha_complex(get_points<Safe_alpha_complex_3d::Point_3>());
+ std::vector<Safe_alpha_complex_3d::Bare_point_3> safe_points = get_points<Safe_alpha_complex_3d::Bare_point_3>();
+ Safe_alpha_complex_3d safe_alpha_complex(safe_points);
Gudhi::Simplex_tree<> safe_stree;
safe_alpha_complex.create_complex(safe_stree);
+ for (std::size_t index = 0; index < safe_points.size(); index++) {
+ bool found = false;
+ Safe_alpha_complex_3d::Bare_point_3 ap = safe_alpha_complex.get_point(index);
+ for (auto point : points) {
+ if ((point.x() == ap.x()) && (point.y() == ap.y()) && (point.z() == ap.z())) {
+ found = true;
+ break;
+ }
+ }
+ // Check all points from alpha complex are found in the input point cloud
+ BOOST_CHECK(found);
+ }
+ // Exception if we go out of range
+ BOOST_CHECK_THROW(safe_alpha_complex.get_point(safe_points.size()), std::out_of_range);
+
// ---------------------
// Compare both versions
// ---------------------
diff --git a/src/Alpha_complex/test/Alpha_complex_unit_test.cpp b/src/Alpha_complex/test/Alpha_complex_unit_test.cpp
index 01e4cee3..40b3fe09 100644
--- a/src/Alpha_complex/test/Alpha_complex_unit_test.cpp
+++ b/src/Alpha_complex/test/Alpha_complex_unit_test.cpp
@@ -15,6 +15,7 @@
#include <CGAL/Delaunay_triangulation.h>
#include <CGAL/Epick_d.h>
+#include <CGAL/Epeck_d.h>
#include <cmath> // float comparison
#include <limits>
@@ -28,12 +29,16 @@
#include <gudhi/Unitary_tests_utils.h>
// Use dynamic_dimension_tag for the user to be able to set dimension
-typedef CGAL::Epick_d< CGAL::Dynamic_dimension_tag > Kernel_d;
+typedef CGAL::Epeck_d< CGAL::Dynamic_dimension_tag > Exact_kernel_d;
// Use static dimension_tag for the user not to be able to set dimension
-typedef CGAL::Epick_d< CGAL::Dimension_tag<3> > Kernel_s;
+typedef CGAL::Epeck_d< CGAL::Dimension_tag<3> > Exact_kernel_s;
+// Use dynamic_dimension_tag for the user to be able to set dimension
+typedef CGAL::Epick_d< CGAL::Dynamic_dimension_tag > Inexact_kernel_d;
+// Use static dimension_tag for the user not to be able to set dimension
+typedef CGAL::Epick_d< CGAL::Dimension_tag<3> > Inexact_kernel_s;
// The triangulation uses the default instantiation of the TriangulationDataStructure template parameter
-typedef boost::mpl::list<Kernel_d, Kernel_s> list_of_kernel_variants;
+typedef boost::mpl::list<Exact_kernel_d, Exact_kernel_s, Inexact_kernel_d, Inexact_kernel_s> list_of_kernel_variants;
BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_from_OFF_file, TestedKernel, list_of_kernel_variants) {
// ----------------------------------------------------------------------------
@@ -86,7 +91,7 @@ BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_from_OFF_file, TestedKernel, list_of
}
// Use static dimension_tag for the user not to be able to set dimension
-typedef CGAL::Epick_d< CGAL::Dimension_tag<4> > Kernel_4;
+typedef CGAL::Epeck_d< CGAL::Dimension_tag<4> > Kernel_4;
typedef Kernel_4::Point_d Point_4;
typedef std::vector<Point_4> Vector_4_Points;
diff --git a/src/Alpha_complex/test/Periodic_alpha_complex_3d_unit_test.cpp b/src/Alpha_complex/test/Periodic_alpha_complex_3d_unit_test.cpp
index ac3791a4..731763fa 100644
--- a/src/Alpha_complex/test/Periodic_alpha_complex_3d_unit_test.cpp
+++ b/src/Alpha_complex/test/Periodic_alpha_complex_3d_unit_test.cpp
@@ -44,11 +44,11 @@ typedef boost::mpl::list<Fast_periodic_alpha_complex_3d, Safe_periodic_alpha_com
BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_periodic_throw, Periodic_alpha_complex_3d, periodic_variants_type_list) {
std::cout << "Periodic alpha complex 3d exception throw" << std::endl;
- using Point_3 = typename Periodic_alpha_complex_3d::Point_3;
- std::vector<Point_3> p_points;
+ using Bare_point_3 = typename Periodic_alpha_complex_3d::Bare_point_3;
+ std::vector<Bare_point_3> p_points;
// Not important, this is not what we want to check
- p_points.push_back(Point_3(0.0, 0.0, 0.0));
+ p_points.push_back(Bare_point_3(0.0, 0.0, 0.0));
std::cout << "Check exception throw in debug mode" << std::endl;
// Check it throws an exception when the cuboid is not iso
@@ -73,13 +73,13 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_periodic) {
// ---------------------
std::cout << "Fast periodic alpha complex 3d" << std::endl;
- using Creator = CGAL::Creator_uniform_3<double, Fast_periodic_alpha_complex_3d::Point_3>;
+ using Creator = CGAL::Creator_uniform_3<double, Fast_periodic_alpha_complex_3d::Bare_point_3>;
CGAL::Random random(7);
- CGAL::Random_points_in_cube_3<Fast_periodic_alpha_complex_3d::Point_3, Creator> in_cube(1, random);
- std::vector<Fast_periodic_alpha_complex_3d::Point_3> p_points;
+ CGAL::Random_points_in_cube_3<Fast_periodic_alpha_complex_3d::Bare_point_3, Creator> in_cube(1, random);
+ std::vector<Fast_periodic_alpha_complex_3d::Bare_point_3> p_points;
for (int i = 0; i < 50; i++) {
- Fast_periodic_alpha_complex_3d::Point_3 p = *in_cube++;
+ Fast_periodic_alpha_complex_3d::Bare_point_3 p = *in_cube++;
p_points.push_back(p);
}
@@ -88,15 +88,30 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_periodic) {
Gudhi::Simplex_tree<> stree;
periodic_alpha_complex.create_complex(stree);
+ for (std::size_t index = 0; index < p_points.size(); index++) {
+ bool found = false;
+ Fast_periodic_alpha_complex_3d::Bare_point_3 ap = periodic_alpha_complex.get_point(index);
+ for (auto point : p_points) {
+ if ((point.x() == ap.x()) && (point.y() == ap.y()) && (point.z() == ap.z())) {
+ found = true;
+ break;
+ }
+ }
+ // Check all points from alpha complex are found in the input point cloud
+ BOOST_CHECK(found);
+ }
+ // Exception if we go out of range
+ BOOST_CHECK_THROW(periodic_alpha_complex.get_point(p_points.size()), std::out_of_range);
+
// ----------------------
// Exact periodic version
// ----------------------
std::cout << "Exact periodic alpha complex 3d" << std::endl;
- std::vector<Exact_periodic_alpha_complex_3d::Point_3> e_p_points;
+ std::vector<Exact_periodic_alpha_complex_3d::Bare_point_3> e_p_points;
for (auto p : p_points) {
- e_p_points.push_back(Exact_periodic_alpha_complex_3d::Point_3(p[0], p[1], p[2]));
+ e_p_points.push_back(Exact_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));
}
Exact_periodic_alpha_complex_3d exact_alpha_complex(e_p_points, -1., -1., -1., 1., 1., 1.);
@@ -142,10 +157,10 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_periodic) {
// ----------------------
std::cout << "Safe periodic alpha complex 3d" << std::endl;
- std::vector<Safe_periodic_alpha_complex_3d::Point_3> s_p_points;
+ std::vector<Safe_periodic_alpha_complex_3d::Bare_point_3> s_p_points;
for (auto p : p_points) {
- s_p_points.push_back(Safe_periodic_alpha_complex_3d::Point_3(p[0], p[1], p[2]));
+ s_p_points.push_back(Safe_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));
}
Safe_periodic_alpha_complex_3d safe_alpha_complex(s_p_points, -1., -1., -1., 1., 1., 1.);
diff --git a/src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp b/src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp
index 44deb930..8035f6e8 100644
--- a/src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp
+++ b/src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp
@@ -43,14 +43,14 @@ typedef boost::mpl::list<Fast_weighted_alpha_complex_3d, Safe_weighted_alpha_com
#ifdef GUDHI_DEBUG
BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted_throw, Weighted_alpha_complex_3d, weighted_variants_type_list) {
- using Point_3 = typename Weighted_alpha_complex_3d::Point_3;
- std::vector<Point_3> w_points;
- w_points.push_back(Point_3(0.0, 0.0, 0.0));
- w_points.push_back(Point_3(0.0, 0.0, 0.2));
- w_points.push_back(Point_3(0.2, 0.0, 0.2));
- // w_points.push_back(Point_3(0.6, 0.6, 0.0));
- // w_points.push_back(Point_3(0.8, 0.8, 0.2));
- // w_points.push_back(Point_3(0.2, 0.8, 0.6));
+ using Bare_point_3 = typename Weighted_alpha_complex_3d::Bare_point_3;
+ std::vector<Bare_point_3> w_points;
+ w_points.push_back(Bare_point_3(0.0, 0.0, 0.0));
+ w_points.push_back(Bare_point_3(0.0, 0.0, 0.2));
+ w_points.push_back(Bare_point_3(0.2, 0.0, 0.2));
+ // w_points.push_back(Bare_point_3(0.6, 0.6, 0.0));
+ // w_points.push_back(Bare_point_3(0.8, 0.8, 0.2));
+ // w_points.push_back(Bare_point_3(0.2, 0.8, 0.6));
// weights size is different from w_points size to make weighted Alpha_complex_3d throw in debug mode
std::vector<double> weights = {0.01, 0.005, 0.006, 0.01, 0.009, 0.001};
@@ -62,14 +62,14 @@ BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted_throw, Weighted_alpha_compl
BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted, Weighted_alpha_complex_3d, weighted_variants_type_list) {
std::cout << "Weighted alpha complex 3d from points and weights" << std::endl;
- using Point_3 = typename Weighted_alpha_complex_3d::Point_3;
- std::vector<Point_3> w_points;
- w_points.push_back(Point_3(0.0, 0.0, 0.0));
- w_points.push_back(Point_3(0.0, 0.0, 0.2));
- w_points.push_back(Point_3(0.2, 0.0, 0.2));
- w_points.push_back(Point_3(0.6, 0.6, 0.0));
- w_points.push_back(Point_3(0.8, 0.8, 0.2));
- w_points.push_back(Point_3(0.2, 0.8, 0.6));
+ using Bare_point_3 = typename Weighted_alpha_complex_3d::Bare_point_3;
+ std::vector<Bare_point_3> w_points;
+ w_points.push_back(Bare_point_3(0.0, 0.0, 0.0));
+ w_points.push_back(Bare_point_3(0.0, 0.0, 0.2));
+ w_points.push_back(Bare_point_3(0.2, 0.0, 0.2));
+ w_points.push_back(Bare_point_3(0.6, 0.6, 0.0));
+ w_points.push_back(Bare_point_3(0.8, 0.8, 0.2));
+ w_points.push_back(Bare_point_3(0.2, 0.8, 0.6));
// weights size is different from w_points size to make weighted Alpha_complex_3d throw in debug mode
std::vector<double> weights = {0.01, 0.005, 0.006, 0.01, 0.009, 0.001};
@@ -91,6 +91,24 @@ BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted, Weighted_alpha_complex_3d,
Gudhi::Simplex_tree<> stree_bis;
alpha_complex_w_p.create_complex(stree_bis);
+ for (std::size_t index = 0; index < weighted_points.size(); index++) {
+ bool found = false;
+ Weighted_point_3 awp = alpha_complex_w_p.get_point(index);
+ for (auto weighted_point : weighted_points) {
+ if ((weighted_point.weight() == awp.weight()) &&
+ (weighted_point.x() == awp.x()) &&
+ (weighted_point.y() == awp.y()) &&
+ (weighted_point.z() == awp.z())) {
+ found = true;
+ break;
+ }
+ }
+ // Check all points from alpha complex are found in the input point cloud
+ BOOST_CHECK(found);
+ }
+ // Exception if we go out of range
+ BOOST_CHECK_THROW(alpha_complex_w_p.get_point(weighted_points.size()), std::out_of_range);
+
// ---------------------
// Compare both versions
// ---------------------
diff --git a/src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp b/src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp
index 670c7799..b09e92d5 100644
--- a/src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp
+++ b/src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp
@@ -47,13 +47,13 @@ BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted_periodic_throw, Weighted_pe
wp_variants_type_list) {
std::cout << "Weighted periodic alpha complex 3d exception throw" << std::endl;
- using Creator = CGAL::Creator_uniform_3<double, typename Weighted_periodic_alpha_complex_3d::Point_3>;
+ using Creator = CGAL::Creator_uniform_3<double, typename Weighted_periodic_alpha_complex_3d::Bare_point_3>;
CGAL::Random random(7);
- CGAL::Random_points_in_cube_3<typename Weighted_periodic_alpha_complex_3d::Point_3, Creator> in_cube(1, random);
- std::vector<typename Weighted_periodic_alpha_complex_3d::Point_3> wp_points;
+ CGAL::Random_points_in_cube_3<typename Weighted_periodic_alpha_complex_3d::Bare_point_3, Creator> in_cube(1, random);
+ std::vector<typename Weighted_periodic_alpha_complex_3d::Bare_point_3> wp_points;
for (int i = 0; i < 50; i++) {
- typename Weighted_periodic_alpha_complex_3d::Point_3 p = *in_cube++;
+ typename Weighted_periodic_alpha_complex_3d::Bare_point_3 p = *in_cube++;
wp_points.push_back(p);
}
std::vector<double> p_weights;
@@ -117,13 +117,13 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_weighted_periodic) {
// ---------------------
std::cout << "Fast weighted periodic alpha complex 3d" << std::endl;
- using Creator = CGAL::Creator_uniform_3<double, Fast_weighted_periodic_alpha_complex_3d::Point_3>;
+ using Creator = CGAL::Creator_uniform_3<double, Fast_weighted_periodic_alpha_complex_3d::Bare_point_3>;
CGAL::Random random(7);
- CGAL::Random_points_in_cube_3<Fast_weighted_periodic_alpha_complex_3d::Point_3, Creator> in_cube(1, random);
- std::vector<Fast_weighted_periodic_alpha_complex_3d::Point_3> p_points;
+ CGAL::Random_points_in_cube_3<Fast_weighted_periodic_alpha_complex_3d::Bare_point_3, Creator> in_cube(1, random);
+ std::vector<Fast_weighted_periodic_alpha_complex_3d::Bare_point_3> p_points;
for (int i = 0; i < 50; i++) {
- Fast_weighted_periodic_alpha_complex_3d::Point_3 p = *in_cube++;
+ Fast_weighted_periodic_alpha_complex_3d::Bare_point_3 p = *in_cube++;
p_points.push_back(p);
}
std::vector<double> p_weights;
@@ -142,10 +142,10 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_weighted_periodic) {
// ----------------------
std::cout << "Exact weighted periodic alpha complex 3d" << std::endl;
- std::vector<Exact_weighted_periodic_alpha_complex_3d::Point_3> e_p_points;
+ std::vector<Exact_weighted_periodic_alpha_complex_3d::Bare_point_3> e_p_points;
for (auto p : p_points) {
- e_p_points.push_back(Exact_weighted_periodic_alpha_complex_3d::Point_3(p[0], p[1], p[2]));
+ e_p_points.push_back(Exact_weighted_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));
}
Exact_weighted_periodic_alpha_complex_3d exact_alpha_complex(e_p_points, p_weights, -1., -1., -1., 1., 1., 1.);
@@ -191,10 +191,10 @@ BOOST_AUTO_TEST_CASE(Alpha_complex_weighted_periodic) {
// ----------------------
std::cout << "Safe weighted periodic alpha complex 3d" << std::endl;
- std::vector<Safe_weighted_periodic_alpha_complex_3d::Point_3> s_p_points;
+ std::vector<Safe_weighted_periodic_alpha_complex_3d::Bare_point_3> s_p_points;
for (auto p : p_points) {
- s_p_points.push_back(Safe_weighted_periodic_alpha_complex_3d::Point_3(p[0], p[1], p[2]));
+ s_p_points.push_back(Safe_weighted_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));
}
Safe_weighted_periodic_alpha_complex_3d safe_alpha_complex(s_p_points, p_weights, -1., -1., -1., 1., 1., 1.);
diff --git a/src/Alpha_complex/utilities/CMakeLists.txt b/src/Alpha_complex/utilities/CMakeLists.txt
index 5295f3cd..57b92942 100644
--- a/src/Alpha_complex/utilities/CMakeLists.txt
+++ b/src/Alpha_complex/utilities/CMakeLists.txt
@@ -7,9 +7,19 @@ if (NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
if (TBB_FOUND)
target_link_libraries(alpha_complex_persistence ${TBB_LIBRARIES})
endif(TBB_FOUND)
- add_test(NAME Alpha_complex_utilities_alpha_complex_persistence COMMAND $<TARGET_FILE:alpha_complex_persistence>
- "${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off" "-p" "2" "-m" "0.45")
-
+ add_test(NAME Alpha_complex_utilities_safe_alpha_complex_persistence COMMAND $<TARGET_FILE:alpha_complex_persistence>
+ "${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off" "-p" "2" "-m" "0.45" "-o" "safe.pers")
+ add_test(NAME Alpha_complex_utilities_fast_alpha_complex_persistence COMMAND $<TARGET_FILE:alpha_complex_persistence>
+ "${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off" "-p" "2" "-m" "0.45" "-o" "fast.pers" "-f")
+ add_test(NAME Alpha_complex_utilities_exact_alpha_complex_persistence COMMAND $<TARGET_FILE:alpha_complex_persistence>
+ "${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off" "-p" "2" "-m" "0.45" "-o" "exact.pers" "-e")
+ if (DIFF_PATH)
+ add_test(Alpha_complex_utilities_diff_exact_alpha_complex ${DIFF_PATH}
+ "exact.pers" "safe.pers")
+ add_test(Alpha_complex_utilities_diff_fast_alpha_complex ${DIFF_PATH}
+ "fast.pers" "safe.pers")
+ endif()
+
install(TARGETS alpha_complex_persistence DESTINATION bin)
add_executable(alpha_complex_3d_persistence alpha_complex_3d_persistence.cpp)
@@ -20,21 +30,21 @@ if (NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
add_test(NAME Alpha_complex_utilities_alpha_complex_3d COMMAND $<TARGET_FILE:alpha_complex_3d_persistence>
"${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off"
- "-p" "2" "-m" "0.45" "-o" "safe.pers")
+ "-p" "2" "-m" "0.45" "-o" "safe_3d.pers")
add_test(NAME Alpha_complex_utilities_exact_alpha_complex_3d COMMAND $<TARGET_FILE:alpha_complex_3d_persistence>
"${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off"
- "-p" "2" "-m" "0.45" "-o" "exact.pers" "-e")
+ "-p" "2" "-m" "0.45" "-o" "exact_3d.pers" "-e")
add_test(NAME Alpha_complex_utilities_safe_alpha_complex_3d COMMAND $<TARGET_FILE:alpha_complex_3d_persistence>
"${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off"
- "-p" "2" "-m" "0.45" "-o" "fast.pers" "-f")
+ "-p" "2" "-m" "0.45" "-o" "fast_3d.pers" "-f")
if (DIFF_PATH)
- add_test(Alpha_complex_utilities_diff_alpha_complex_3d ${DIFF_PATH}
- "exact.pers" "safe.pers")
- add_test(Alpha_complex_utilities_diff_alpha_complex_3d ${DIFF_PATH}
- "fast.pers" "safe.pers")
+ add_test(Alpha_complex_utilities_diff_exact_alpha_complex_3d ${DIFF_PATH}
+ "exact_3d.pers" "safe_3d.pers")
+ add_test(Alpha_complex_utilities_diff_fast_alpha_complex_3d ${DIFF_PATH}
+ "fast_3d.pers" "safe_3d.pers")
endif()
add_test(NAME Alpha_complex_utilities_periodic_alpha_complex_3d_persistence COMMAND $<TARGET_FILE:alpha_complex_3d_persistence>
diff --git a/src/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp b/src/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp
index 2272576e..929fc2e8 100644
--- a/src/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp
+++ b/src/Alpha_complex/utilities/alpha_complex_3d_persistence.cpp
@@ -62,9 +62,9 @@ bool read_cuboid_file(const std::string &cuboid_file, double &x_min, double &y_m
}
template <typename AlphaComplex3d>
-std::vector<typename AlphaComplex3d::Point_3> read_off(const std::string &off_file_points) {
+std::vector<typename AlphaComplex3d::Bare_point_3> read_off(const std::string &off_file_points) {
// Read the OFF file (input file name given as parameter) and triangulate points
- Gudhi::Points_3D_off_reader<typename AlphaComplex3d::Point_3> off_reader(off_file_points);
+ Gudhi::Points_3D_off_reader<typename AlphaComplex3d::Bare_point_3> off_reader(off_file_points);
// Check the read operation was correct
if (!off_reader.is_valid()) {
std::cerr << "Unable to read OFF file " << off_file_points << std::endl;
diff --git a/src/Alpha_complex/utilities/alpha_complex_persistence.cpp b/src/Alpha_complex/utilities/alpha_complex_persistence.cpp
index fab7bd30..486347cc 100644
--- a/src/Alpha_complex/utilities/alpha_complex_persistence.cpp
+++ b/src/Alpha_complex/utilities/alpha_complex_persistence.cpp
@@ -24,63 +24,84 @@
using Simplex_tree = Gudhi::Simplex_tree<>;
using Filtration_value = Simplex_tree::Filtration_value;
-void program_options(int argc, char *argv[], std::string &off_file_points, std::string &output_file_diag,
- Filtration_value &alpha_square_max_value, int &coeff_field_characteristic,
- Filtration_value &min_persistence);
+void program_options(int argc, char *argv[], std::string &off_file_points, bool &exact, bool &fast,
+ std::string &output_file_diag, Filtration_value &alpha_square_max_value,
+ int &coeff_field_characteristic, Filtration_value &min_persistence);
int main(int argc, char **argv) {
std::string off_file_points;
std::string output_file_diag;
+ bool exact_version = false;
+ bool fast_version = false;
Filtration_value alpha_square_max_value;
int coeff_field_characteristic;
Filtration_value min_persistence;
- program_options(argc, argv, off_file_points, output_file_diag, alpha_square_max_value, coeff_field_characteristic,
- min_persistence);
+ program_options(argc, argv, off_file_points, exact_version, fast_version, output_file_diag, alpha_square_max_value,
+ coeff_field_characteristic, min_persistence);
- // ----------------------------------------------------------------------------
- // Init of an alpha complex from an OFF file
- // ----------------------------------------------------------------------------
- using Kernel = CGAL::Epick_d<CGAL::Dynamic_dimension_tag>;
- Gudhi::alpha_complex::Alpha_complex<Kernel> alpha_complex_from_file(off_file_points);
+ if ((exact_version) && (fast_version)) {
+ std::cerr << "You cannot set the exact and the fast version." << std::endl;
+ exit(-1);
+ }
Simplex_tree simplex;
- if (alpha_complex_from_file.create_complex(simplex, alpha_square_max_value)) {
- // ----------------------------------------------------------------------------
- // Display information about the alpha complex
- // ----------------------------------------------------------------------------
- std::cout << "Simplicial complex is of dimension " << simplex.dimension() << " - " << simplex.num_simplices()
- << " simplices - " << simplex.num_vertices() << " vertices." << std::endl;
-
- // Sort the simplices in the order of the filtration
- simplex.initialize_filtration();
-
- std::cout << "Simplex_tree dim: " << simplex.dimension() << std::endl;
- // Compute the persistence diagram of the complex
- Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Gudhi::persistent_cohomology::Field_Zp> pcoh(
- simplex);
- // initializes the coefficient field for homology
- pcoh.init_coefficients(coeff_field_characteristic);
-
- pcoh.compute_persistent_cohomology(min_persistence);
-
- // Output the diagram in filediag
- if (output_file_diag.empty()) {
- pcoh.output_diagram();
- } else {
- std::cout << "Result in file: " << output_file_diag << std::endl;
- std::ofstream out(output_file_diag);
- pcoh.output_diagram(out);
- out.close();
+ if (fast_version) {
+ // WARNING : CGAL::Epick_d is fast but not safe (unlike CGAL::Epeck_d)
+ // (i.e. when the points are on a grid)
+ using Fast_kernel = CGAL::Epick_d<CGAL::Dynamic_dimension_tag>;
+
+ // Init of an alpha complex from an OFF file
+ Gudhi::alpha_complex::Alpha_complex<Fast_kernel> alpha_complex_from_file(off_file_points);
+
+ if (!alpha_complex_from_file.create_complex(simplex, alpha_square_max_value)) {
+ std::cerr << "Fast Alpha complex simplicial complex creation failed." << std::endl;
+ exit(-1);
}
- }
+ } else {
+ using Kernel = CGAL::Epeck_d<CGAL::Dynamic_dimension_tag>;
+ // Init of an alpha complex from an OFF file
+ Gudhi::alpha_complex::Alpha_complex<Kernel> alpha_complex_from_file(off_file_points);
+
+ if (!alpha_complex_from_file.create_complex(simplex, alpha_square_max_value, exact_version)) {
+ std::cerr << "Alpha complex simplicial complex creation failed." << std::endl;
+ exit(-1);
+ }
+ }
+ // ----------------------------------------------------------------------------
+ // Display information about the alpha complex
+ // ----------------------------------------------------------------------------
+ std::cout << "Simplicial complex is of dimension " << simplex.dimension() << " - " << simplex.num_simplices()
+ << " simplices - " << simplex.num_vertices() << " vertices." << std::endl;
+
+ // Sort the simplices in the order of the filtration
+ simplex.initialize_filtration();
+
+ std::cout << "Simplex_tree dim: " << simplex.dimension() << std::endl;
+ // Compute the persistence diagram of the complex
+ Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Gudhi::persistent_cohomology::Field_Zp> pcoh(
+ simplex);
+ // initializes the coefficient field for homology
+ pcoh.init_coefficients(coeff_field_characteristic);
+
+ pcoh.compute_persistent_cohomology(min_persistence);
+
+ // Output the diagram in filediag
+ if (output_file_diag.empty()) {
+ pcoh.output_diagram();
+ } else {
+ std::cout << "Result in file: " << output_file_diag << std::endl;
+ std::ofstream out(output_file_diag);
+ pcoh.output_diagram(out);
+ out.close();
+ }
return 0;
}
-void program_options(int argc, char *argv[], std::string &off_file_points, std::string &output_file_diag,
- Filtration_value &alpha_square_max_value, int &coeff_field_characteristic,
- Filtration_value &min_persistence) {
+void program_options(int argc, char *argv[], std::string &off_file_points, bool &exact, bool &fast,
+ std::string &output_file_diag, Filtration_value &alpha_square_max_value,
+ int &coeff_field_characteristic, Filtration_value &min_persistence) {
namespace po = boost::program_options;
po::options_description hidden("Hidden options");
hidden.add_options()("input-file", po::value<std::string>(&off_file_points),
@@ -88,6 +109,10 @@ void program_options(int argc, char *argv[], std::string &off_file_points, std::
po::options_description visible("Allowed options", 100);
visible.add_options()("help,h", "produce help message")(
+ "exact,e", po::bool_switch(&exact),
+ "To activate exact version of Alpha complex (default is false, not available if fast is set)")(
+ "fast,f", po::bool_switch(&fast),
+ "To activate fast version of Alpha complex (default is false, not available if exact is set)")(
"output-file,o", po::value<std::string>(&output_file_diag)->default_value(std::string()),
"Name of file in which the persistence diagram is written. Default print in std::cout")(
"max-alpha-square-value,r", po::value<Filtration_value>(&alpha_square_max_value)
diff --git a/src/Alpha_complex/utilities/alphacomplex.md b/src/Alpha_complex/utilities/alphacomplex.md
index fcd16a3b..527598a9 100644
--- a/src/Alpha_complex/utilities/alphacomplex.md
+++ b/src/Alpha_complex/utilities/alphacomplex.md
@@ -46,6 +46,8 @@ for the Alpha complex construction.
coefficient field Z/pZ for computing homology.
* `-m [ --min-persistence ]` (default = 0) Minimal lifetime of homology feature
to be recorded. Enter a negative value to see zero length intervals.
+* `-e [ --exact ]` for the exact computation version.
+* `-f [ --fast ]` for the fast computation version.
**Example**
diff --git a/src/Cech_complex/doc/Intro_cech_complex.h b/src/Cech_complex/doc/Intro_cech_complex.h
index 90086de7..80c88dc6 100644
--- a/src/Cech_complex/doc/Intro_cech_complex.h
+++ b/src/Cech_complex/doc/Intro_cech_complex.h
@@ -24,7 +24,7 @@ namespace cech_complex {
* \section cechdefinition ÄŒech complex definition
*
* ÄŒech complex
- * <a target="_blank" href="https://en.wikipedia.org/wiki/%C4%8Cech_cohomology">(Wikipedia)</a> is a
+ * <a target="_blank" href="https://en.wikipedia.org/wiki/%C4%8Cech_complex">(Wikipedia)</a> is a
* <a target="_blank" href="https://en.wikipedia.org/wiki/Simplicial_complex">simplicial complex</a> constructed
* from a proximity graph. The set of all simplices is filtered by the radius of their minimal enclosing ball.
*
diff --git a/src/Doxyfile.in b/src/Doxyfile.in
index 57775498..ec551882 100644
--- a/src/Doxyfile.in
+++ b/src/Doxyfile.in
@@ -765,7 +765,7 @@ INPUT_ENCODING = UTF-8
# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
# *.qsf, *.as and *.js.
-FILE_PATTERNS =
+#FILE_PATTERNS =
# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
diff --git a/src/Persistent_cohomology/include/gudhi/Persistent_cohomology.h b/src/Persistent_cohomology/include/gudhi/Persistent_cohomology.h
index 944b6d35..0f1876d0 100644
--- a/src/Persistent_cohomology/include/gudhi/Persistent_cohomology.h
+++ b/src/Persistent_cohomology/include/gudhi/Persistent_cohomology.h
@@ -600,8 +600,10 @@ class Persistent_cohomology {
* @return A vector of Betti numbers.
*/
std::vector<int> betti_numbers() const {
+ // Don't allocate a vector of negative size for an empty complex
+ int siz = std::max(dim_max_, 0);
// Init Betti numbers vector with zeros until Simplicial complex dimension
- std::vector<int> betti_numbers(dim_max_, 0);
+ std::vector<int> betti_numbers(siz);
for (auto pair : persistent_pairs_) {
// Count never ended persistence intervals
@@ -639,8 +641,10 @@ class Persistent_cohomology {
* @return A vector of persistent Betti numbers.
*/
std::vector<int> persistent_betti_numbers(Filtration_value from, Filtration_value to) const {
+ // Don't allocate a vector of negative size for an empty complex
+ int siz = std::max(dim_max_, 0);
// Init Betti numbers vector with zeros until Simplicial complex dimension
- std::vector<int> betti_numbers(dim_max_, 0);
+ std::vector<int> betti_numbers(siz);
for (auto pair : persistent_pairs_) {
// Count persistence intervals that covers the given interval
// null_simplex test : if the function is called with to=+infinity, we still get something useful. And it will
diff --git a/src/Persistent_cohomology/test/betti_numbers_unit_test.cpp b/src/Persistent_cohomology/test/betti_numbers_unit_test.cpp
index 0a08d200..b9f11607 100644
--- a/src/Persistent_cohomology/test/betti_numbers_unit_test.cpp
+++ b/src/Persistent_cohomology/test/betti_numbers_unit_test.cpp
@@ -284,4 +284,13 @@ BOOST_AUTO_TEST_CASE( betti_numbers )
auto intervals_in_dimension_2 = pcoh.intervals_in_dimension(2);
std::cout << "intervals_in_dimension_2.size() = " << intervals_in_dimension_2.size() << std::endl;
BOOST_CHECK(intervals_in_dimension_2.size() == 0);
+
+ std::cout << "EMPTY COMPLEX" << std::endl;
+ Simplex_tree empty;
+ empty.initialize_filtration();
+ St_persistence pcoh_empty(empty, false);
+ pcoh_empty.init_coefficients(2);
+ pcoh_empty.compute_persistent_cohomology();
+ BOOST_CHECK(pcoh_empty.betti_numbers().size() == 0);
+ BOOST_CHECK(pcoh_empty.persistent_betti_numbers(0,1).size() == 0);
}
diff --git a/src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp b/src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp
index 9e182f1e..b7040453 100644
--- a/src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp
+++ b/src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp
@@ -35,19 +35,19 @@ int main(int argc, char **argv) {
Distance_matrix distances = Gudhi::read_lower_triangular_matrix_from_csv_file<Filtration_value>(csv_file_name);
Rips_complex rips_complex_from_file(distances, threshold);
- std::streambuf* streambufffer;
+ std::streambuf* streambuffer;
std::ofstream ouput_file_stream;
if (argc == 5) {
ouput_file_stream.open(std::string(argv[4]));
- streambufffer = ouput_file_stream.rdbuf();
+ streambuffer = ouput_file_stream.rdbuf();
} else {
- streambufffer = std::cout.rdbuf();
+ streambuffer = std::cout.rdbuf();
}
Simplex_tree stree;
rips_complex_from_file.create_complex(stree, dim_max);
- std::ostream output_stream(streambufffer);
+ std::ostream output_stream(streambuffer);
// ----------------------------------------------------------------------------
// Display information about the Rips complex
diff --git a/src/Rips_complex/example/example_rips_complex_from_off_file.cpp b/src/Rips_complex/example/example_rips_complex_from_off_file.cpp
index de2e4ea4..36b468a7 100644
--- a/src/Rips_complex/example/example_rips_complex_from_off_file.cpp
+++ b/src/Rips_complex/example/example_rips_complex_from_off_file.cpp
@@ -34,19 +34,19 @@ int main(int argc, char **argv) {
Gudhi::Points_off_reader<Point> off_reader(off_file_name);
Rips_complex rips_complex_from_file(off_reader.get_point_cloud(), threshold, Gudhi::Euclidean_distance());
- std::streambuf* streambufffer;
+ std::streambuf* streambuffer;
std::ofstream ouput_file_stream;
if (argc == 5) {
ouput_file_stream.open(std::string(argv[4]));
- streambufffer = ouput_file_stream.rdbuf();
+ streambuffer = ouput_file_stream.rdbuf();
} else {
- streambufffer = std::cout.rdbuf();
+ streambuffer = std::cout.rdbuf();
}
Simplex_tree stree;
rips_complex_from_file.create_complex(stree, dim_max);
- std::ostream output_stream(streambufffer);
+ std::ostream output_stream(streambuffer);
// ----------------------------------------------------------------------------
// Display information about the Rips complex
diff --git a/src/Rips_complex/utilities/ripscomplex.md b/src/Rips_complex/utilities/ripscomplex.md
index 03838085..61f31e3c 100644
--- a/src/Rips_complex/utilities/ripscomplex.md
+++ b/src/Rips_complex/utilities/ripscomplex.md
@@ -99,6 +99,7 @@ where `dim` is the dimension of the homological feature, `birth` and `death` are
* `-h [ --help ]` Produce help message
* `-o [ --output-file ]` Name of file in which the persistence diagram is written. Default print in standard output.
+* `-r [ --max-edge-length ]` (default = inf) Maximal length of an edge for the Rips complex construction.
* `-e [ --approximation ]` (default = .5) Epsilon, where the sparse Rips complex is a (1+epsilon)/(1-epsilon)-approximation of the Rips complex.
* `-d [ --cpx-dimension ]` (default = INT_MAX) Maximal dimension of the Rips complex we want to compute.
* `-p [ --field-charac ]` (default = 11) Characteristic p of the coefficient field Z/pZ for computing homology.
diff --git a/src/Rips_complex/utilities/sparse_rips_persistence.cpp b/src/Rips_complex/utilities/sparse_rips_persistence.cpp
index 1a86eafe..cefd8a67 100644
--- a/src/Rips_complex/utilities/sparse_rips_persistence.cpp
+++ b/src/Rips_complex/utilities/sparse_rips_persistence.cpp
@@ -28,21 +28,24 @@ using Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomolog
using Point = std::vector<double>;
using Points_off_reader = Gudhi::Points_off_reader<Point>;
-void program_options(int argc, char* argv[], std::string& off_file_points, std::string& filediag, double& epsilon,
+void program_options(int argc, char* argv[], std::string& off_file_points, std::string& filediag,
+ Filtration_value& threshold, double& epsilon,
int& dim_max, int& p, Filtration_value& min_persistence);
int main(int argc, char* argv[]) {
std::string off_file_points;
std::string filediag;
+ Filtration_value threshold;
double epsilon;
int dim_max;
int p;
Filtration_value min_persistence;
- program_options(argc, argv, off_file_points, filediag, epsilon, dim_max, p, min_persistence);
+ program_options(argc, argv, off_file_points, filediag, threshold, epsilon, dim_max, p, min_persistence);
Points_off_reader off_reader(off_file_points);
- Sparse_rips sparse_rips(off_reader.get_point_cloud(), Gudhi::Euclidean_distance(), epsilon);
+ Sparse_rips sparse_rips(off_reader.get_point_cloud(), Gudhi::Euclidean_distance(), epsilon,
+ -std::numeric_limits<Filtration_value>::infinity(), threshold);
// Construct the Rips complex in a Simplex Tree
Simplex_tree simplex_tree;
@@ -73,7 +76,8 @@ int main(int argc, char* argv[]) {
return 0;
}
-void program_options(int argc, char* argv[], std::string& off_file_points, std::string& filediag, double& epsilon,
+void program_options(int argc, char* argv[], std::string& off_file_points, std::string& filediag,
+ Filtration_value& threshold, double& epsilon,
int& dim_max, int& p, Filtration_value& min_persistence) {
namespace po = boost::program_options;
po::options_description hidden("Hidden options");
@@ -84,6 +88,9 @@ void program_options(int argc, char* argv[], std::string& off_file_points, std::
visible.add_options()("help,h", "produce help message")(
"output-file,o", po::value<std::string>(&filediag)->default_value(std::string()),
"Name of file in which the persistence diagram is written. Default print in std::cout")(
+ "max-edge-length,r",
+ po::value<Filtration_value>(&threshold)->default_value(std::numeric_limits<Filtration_value>::infinity()),
+ "Maximal length of an edge for the Rips complex construction.")(
"approximation,e", po::value<double>(&epsilon)->default_value(.5),
"Epsilon, where the sparse Rips complex is a (1+epsilon)-approximation of the Rips complex.")(
"cpx-dimension,d", po::value<int>(&dim_max)->default_value(std::numeric_limits<int>::max()),
diff --git a/src/cmake/modules/GUDHI_third_party_libraries.cmake b/src/cmake/modules/GUDHI_third_party_libraries.cmake
index 360a230b..24a34150 100644
--- a/src/cmake/modules/GUDHI_third_party_libraries.cmake
+++ b/src/cmake/modules/GUDHI_third_party_libraries.cmake
@@ -125,6 +125,8 @@ if( PYTHONINTERP_FOUND )
find_python_module("numpy")
find_python_module("scipy")
find_python_module("sphinx")
+ find_python_module("sklearn")
+ find_python_module("ot")
endif()
if(NOT GUDHI_PYTHON_PATH)
diff --git a/src/common/doc/main_page.md b/src/common/doc/main_page.md
index d8cbf97f..e8d11fdf 100644
--- a/src/common/doc/main_page.md
+++ b/src/common/doc/main_page.md
@@ -45,6 +45,7 @@
values of the codimension 1 cofaces that make it not Gabriel otherwise.
All simplices that have a filtration value strictly greater than a given alpha squared value are not inserted into
the complex.<br>
+ For performances reasons, it is advised to use \ref cgal &ge; 5.0.0.
</td>
<td width="15%">
<b>Author:</b> Vincent Rouvreau<br>
diff --git a/src/common/include/gudhi/Unitary_tests_utils.h b/src/common/include/gudhi/Unitary_tests_utils.h
index 4ad4dae8..7d039304 100644
--- a/src/common/include/gudhi/Unitary_tests_utils.h
+++ b/src/common/include/gudhi/Unitary_tests_utils.h
@@ -14,6 +14,7 @@
#include <iostream>
#include <limits> // for std::numeric_limits<>
+#include <cmath> // for std::fabs
template<typename FloatingType >
void GUDHI_TEST_FLOAT_EQUALITY_CHECK(FloatingType a, FloatingType b,
diff --git a/src/python/CMakeLists.txt b/src/python/CMakeLists.txt
index 5508cbc7..9af85eac 100644
--- a/src/python/CMakeLists.txt
+++ b/src/python/CMakeLists.txt
@@ -49,6 +49,9 @@ if(PYTHONINTERP_FOUND)
set(GUDHI_PYTHON_MODULES "${GUDHI_PYTHON_MODULES}'alpha_complex', ")
set(GUDHI_PYTHON_MODULES "${GUDHI_PYTHON_MODULES}'euclidean_witness_complex', ")
set(GUDHI_PYTHON_MODULES "${GUDHI_PYTHON_MODULES}'euclidean_strong_witness_complex', ")
+ # Modules that should not be auto-imported in __init__.py
+ set(GUDHI_PYTHON_MODULES_EXTRA "${GUDHI_PYTHON_MODULES_EXTRA}'representations', ")
+ set(GUDHI_PYTHON_MODULES_EXTRA "${GUDHI_PYTHON_MODULES_EXTRA}'wasserstein', ")
add_gudhi_debug_info("Python version ${PYTHON_VERSION_STRING}")
add_gudhi_debug_info("Cython version ${CYTHON_VERSION}")
@@ -64,6 +67,12 @@ if(PYTHONINTERP_FOUND)
if(SCIPY_FOUND)
add_gudhi_debug_info("Scipy version ${SCIPY_VERSION}")
endif()
+ if(SKLEARN_FOUND)
+ add_gudhi_debug_info("Scikit-learn version ${SKLEARN_VERSION}")
+ endif()
+ if(OT_FOUND)
+ add_gudhi_debug_info("POT version ${OT_VERSION}")
+ endif()
set(GUDHI_PYTHON_EXTRA_COMPILE_ARGS "${GUDHI_PYTHON_EXTRA_COMPILE_ARGS}'-DBOOST_RESULT_OF_USE_DECLTYPE', ")
set(GUDHI_PYTHON_EXTRA_COMPILE_ARGS "${GUDHI_PYTHON_EXTRA_COMPILE_ARGS}'-DBOOST_ALL_NO_LIB', ")
@@ -199,6 +208,8 @@ if(PYTHONINTERP_FOUND)
# Other .py files
file(COPY "gudhi/persistence_graphical_tools.py" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/gudhi")
+ file(COPY "gudhi/representations" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/gudhi/")
+ file(COPY "gudhi/wasserstein.py" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/gudhi")
add_custom_command(
OUTPUT gudhi.so
@@ -371,37 +382,57 @@ if(PYTHONINTERP_FOUND)
# Reader utils
add_gudhi_py_test(test_reader_utils)
+ # Wasserstein
+ if(OT_FOUND)
+ add_gudhi_py_test(test_wasserstein_distance)
+ endif(OT_FOUND)
+
+ # Representations
+ if(SKLEARN_FOUND AND MATPLOTLIB_FOUND)
+ add_gudhi_py_test(test_representations)
+ endif()
+
# Documentation generation is available through sphinx - requires all modules
if(SPHINX_PATH)
if(MATPLOTLIB_FOUND)
if(NUMPY_FOUND)
if(SCIPY_FOUND)
- if(NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
- set (GUDHI_SPHINX_MESSAGE "Generating API documentation with Sphinx in ${CMAKE_CURRENT_BINARY_DIR}/sphinx/")
- # User warning - Sphinx is a static pages generator, and configured to work fine with user_version
- # Images and biblio warnings because not found on developper version
- if (GUDHI_PYTHON_PATH STREQUAL "src/python")
- set (GUDHI_SPHINX_MESSAGE "${GUDHI_SPHINX_MESSAGE} \n WARNING : Sphinx is configured for user version, you run it on developper version. Images and biblio will miss")
- endif()
- # sphinx target requires gudhi.so, because conf.py reads gudhi version from it
- add_custom_target(sphinx
- WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc
- COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}"
- ${SPHINX_PATH} -b html ${CMAKE_CURRENT_SOURCE_DIR}/doc ${CMAKE_CURRENT_BINARY_DIR}/sphinx
- DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/gudhi.so"
- COMMENT "${GUDHI_SPHINX_MESSAGE}" VERBATIM)
-
- add_test(NAME sphinx_py_test
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
- COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}"
- ${SPHINX_PATH} -b doctest ${CMAKE_CURRENT_SOURCE_DIR}/doc ${CMAKE_CURRENT_BINARY_DIR}/doctest)
-
- # Set missing or not modules
- set(GUDHI_MODULES ${GUDHI_MODULES} "python-documentation" CACHE INTERNAL "GUDHI_MODULES")
- else(NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
- message("++ Python documentation module will not be compiled because it requires a Eigen3 and CGAL version >= 4.11.0")
+ if(SKLEARN_FOUND)
+ if(OT_FOUND)
+ if(NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
+ set (GUDHI_SPHINX_MESSAGE "Generating API documentation with Sphinx in ${CMAKE_CURRENT_BINARY_DIR}/sphinx/")
+ # User warning - Sphinx is a static pages generator, and configured to work fine with user_version
+ # Images and biblio warnings because not found on developper version
+ if (GUDHI_PYTHON_PATH STREQUAL "src/python")
+ set (GUDHI_SPHINX_MESSAGE "${GUDHI_SPHINX_MESSAGE} \n WARNING : Sphinx is configured for user version, you run it on developper version. Images and biblio will miss")
+ endif()
+ # sphinx target requires gudhi.so, because conf.py reads gudhi version from it
+ add_custom_target(sphinx
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc
+ COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}"
+ ${SPHINX_PATH} -b html ${CMAKE_CURRENT_SOURCE_DIR}/doc ${CMAKE_CURRENT_BINARY_DIR}/sphinx
+ DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/gudhi.so"
+ COMMENT "${GUDHI_SPHINX_MESSAGE}" VERBATIM)
+
+ add_test(NAME sphinx_py_test
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}"
+ ${SPHINX_PATH} -b doctest ${CMAKE_CURRENT_SOURCE_DIR}/doc ${CMAKE_CURRENT_BINARY_DIR}/doctest)
+
+ # Set missing or not modules
+ set(GUDHI_MODULES ${GUDHI_MODULES} "python-documentation" CACHE INTERNAL "GUDHI_MODULES")
+ else(NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
+ message("++ Python documentation module will not be compiled because it requires a Eigen3 and CGAL version >= 4.11.0")
+ set(GUDHI_MISSING_MODULES ${GUDHI_MISSING_MODULES} "python-documentation" CACHE INTERNAL "GUDHI_MISSING_MODULES")
+ endif(NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
+ else(OT_FOUND)
+ message("++ Python documentation module will not be compiled because POT was not found")
+ set(GUDHI_MISSING_MODULES ${GUDHI_MISSING_MODULES} "python-documentation" CACHE INTERNAL "GUDHI_MISSING_MODULES")
+ endif(OT_FOUND)
+ else(SKLEARN_FOUND)
+ message("++ Python documentation module will not be compiled because scikit-learn was not found")
set(GUDHI_MISSING_MODULES ${GUDHI_MISSING_MODULES} "python-documentation" CACHE INTERNAL "GUDHI_MISSING_MODULES")
- endif(NOT CGAL_WITH_EIGEN3_VERSION VERSION_LESS 4.11.0)
+ endif(SKLEARN_FOUND)
else(SCIPY_FOUND)
message("++ Python documentation module will not be compiled because scipy was not found")
set(GUDHI_MISSING_MODULES ${GUDHI_MISSING_MODULES} "python-documentation" CACHE INTERNAL "GUDHI_MISSING_MODULES")
diff --git a/src/python/doc/conf.py b/src/python/doc/conf.py
index e4c718c3..64d9cba1 100755
--- a/src/python/doc/conf.py
+++ b/src/python/doc/conf.py
@@ -39,6 +39,7 @@ extensions = [
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
+ 'sphinx.ext.napoleon',
'sphinxcontrib.bibtex',
]
diff --git a/src/python/doc/index.rst b/src/python/doc/index.rst
index e379bc23..1ef08096 100644
--- a/src/python/doc/index.rst
+++ b/src/python/doc/index.rst
@@ -23,7 +23,7 @@ Alpha complex
.. include:: alpha_complex_sum.inc
Rips complex
--------------
+------------
.. include:: rips_complex_sum.inc
@@ -73,6 +73,16 @@ Bottleneck distance
.. include:: bottleneck_distance_sum.inc
+Wasserstein distance
+====================
+
+.. include:: wasserstein_distance_sum.inc
+
+Persistence representations
+===========================
+
+.. include:: representations_sum.inc
+
Persistence graphical tools
===========================
diff --git a/src/python/doc/installation.rst b/src/python/doc/installation.rst
index 77d9e8b3..7699a5bb 100644
--- a/src/python/doc/installation.rst
+++ b/src/python/doc/installation.rst
@@ -8,7 +8,7 @@ Installation
Conda
*****
The easiest way to install the Python version of GUDHI is using
-`conda <https://gudhi.inria.fr/licensing/>`_.
+`conda <https://gudhi.inria.fr/conda/>`_.
Compiling
*********
@@ -215,12 +215,20 @@ The following examples require the `Matplotlib <http://matplotlib.org>`_:
* :download:`euclidean_strong_witness_complex_diagram_persistence_from_off_file_example.py <../example/euclidean_strong_witness_complex_diagram_persistence_from_off_file_example.py>`
* :download:`euclidean_witness_complex_diagram_persistence_from_off_file_example.py <../example/euclidean_witness_complex_diagram_persistence_from_off_file_example.py>`
+Python Optimal Transport
+========================
+
+The :doc:`Wasserstein distance </wasserstein_distance_user>`
+module requires `POT <https://pot.readthedocs.io/>`_, a library that provides
+several solvers for optimization problems related to Optimal Transport.
+
SciPy
=====
-The :doc:`persistence graphical tools </persistence_graphical_tools_user>`
-module requires `SciPy <http://scipy.org>`_, a Python-based ecosystem of
-open-source software for mathematics, science, and engineering.
+The :doc:`persistence graphical tools </persistence_graphical_tools_user>` and
+:doc:`Wasserstein distance </wasserstein_distance_user>` modules require `SciPy
+<http://scipy.org>`_, a Python-based ecosystem of open-source software for
+mathematics, science, and engineering.
Threading Building Blocks
=========================
diff --git a/src/python/doc/representations.rst b/src/python/doc/representations.rst
new file mode 100644
index 00000000..a137a035
--- /dev/null
+++ b/src/python/doc/representations.rst
@@ -0,0 +1,48 @@
+:orphan:
+
+.. To get rid of WARNING: document isn't included in any toctree
+
+======================
+Representations manual
+======================
+
+.. include:: representations_sum.inc
+
+This module, originally named sklearn_tda, aims at bridging the gap between persistence diagrams and machine learning tools, in particular scikit-learn. It provides tools, using the scikit-learn standard interface, to compute distances and kernels on diagrams, and to convert diagrams into vectors.
+
+A diagram is represented as a numpy array of shape (n,2), as can be obtained from `SimplexTree.persistence_intervals_in_dimension` for instance. Points at infinity are represented as a numpy array of shape (n,1), storing only the birth time.
+
+A small example is provided
+
+.. only:: builder_html
+
+ * :download:`diagram_vectorizations_distances_kernels.py <../example/diagram_vectorizations_distances_kernels.py>`
+
+
+Preprocessing
+-------------
+.. automodule:: gudhi.representations.preprocessing
+ :members:
+ :special-members:
+ :show-inheritance:
+
+Vector methods
+--------------
+.. automodule:: gudhi.representations.vector_methods
+ :members:
+ :special-members:
+ :show-inheritance:
+
+Kernel methods
+--------------
+.. automodule:: gudhi.representations.kernel_methods
+ :members:
+ :special-members:
+ :show-inheritance:
+
+Metrics
+-------
+.. automodule:: gudhi.representations.metrics
+ :members:
+ :special-members:
+ :show-inheritance:
diff --git a/src/python/doc/representations_sum.inc b/src/python/doc/representations_sum.inc
new file mode 100644
index 00000000..7b167a17
--- /dev/null
+++ b/src/python/doc/representations_sum.inc
@@ -0,0 +1,14 @@
+.. table::
+ :widths: 30 50 20
+
+ +------------------------------------------------------------------+----------------------------------------------------------------+-----------------------------------------------+
+ | .. figure:: | Vectorizations, distances and kernels that work on persistence | :Author: Mathieu Carrière |
+ | ../../doc/Persistence_representations/average_landscape.png | diagrams, compatible with scikit-learn. | |
+ | | | :Introduced in: GUDHI 3.1.0 |
+ | | | |
+ | | | :Copyright: MIT |
+ | | | |
+ | | | :Requires: scikit-learn |
+ +------------------------------------------------------------------+----------------------------------------------------------------+-----------------------------------------------+
+ | * :doc:`representations` |
+ +------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------+
diff --git a/src/python/doc/wasserstein_distance_sum.inc b/src/python/doc/wasserstein_distance_sum.inc
new file mode 100644
index 00000000..ffd4d312
--- /dev/null
+++ b/src/python/doc/wasserstein_distance_sum.inc
@@ -0,0 +1,14 @@
+.. table::
+ :widths: 30 50 20
+
+ +-----------------------------------------------------------------+----------------------------------------------------------------------+------------------------------------------------------------------+
+ | .. figure:: | The p-Wasserstein distance measures the similarity between two | :Author: Theo Lacombe |
+ | ../../doc/Bottleneck_distance/perturb_pd.png | persistence diagrams. It's the minimum value c that can be achieved | |
+ | :figclass: align-center | by a perfect matching between the points of the two diagrams (+ all | :Introduced in: GUDHI 3.1.0 |
+ | | diagonal points), where the value of a matching is defined as the | |
+ | Wasserstein distance is the p-th root of the sum of the | p-th root of the sum of all edge lengths to the power p. Edge lengths| :Copyright: MIT |
+ | edge lengths to the power p. | are measured in norm q, for :math:`1 \leq q \leq \infty`. | |
+ | | | :Requires: Python Optimal Transport (POT) :math:`\geq` 0.5.1 |
+ +-----------------------------------------------------------------+----------------------------------------------------------------------+------------------------------------------------------------------+
+ | * :doc:`wasserstein_distance_user` | |
+ +-----------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+
diff --git a/src/python/doc/wasserstein_distance_user.rst b/src/python/doc/wasserstein_distance_user.rst
new file mode 100644
index 00000000..a049cfb5
--- /dev/null
+++ b/src/python/doc/wasserstein_distance_user.rst
@@ -0,0 +1,40 @@
+:orphan:
+
+.. To get rid of WARNING: document isn't included in any toctree
+
+Wasserstein distance user manual
+================================
+Definition
+----------
+
+.. include:: wasserstein_distance_sum.inc
+
+This implementation is based on ideas from "Large Scale Computation of Means and Cluster for Persistence Diagrams via Optimal Transport".
+
+Function
+--------
+.. autofunction:: gudhi.wasserstein.wasserstein_distance
+
+
+Basic example
+-------------
+
+This example computes the 1-Wasserstein distance from 2 persistence diagrams with euclidean ground metric.
+Note that persistence diagrams must be submitted as (n x 2) numpy arrays and must not contain inf values.
+
+.. testcode::
+
+ import gudhi.wasserstein
+ import numpy as np
+
+ diag1 = np.array([[2.7, 3.7],[9.6, 14.],[34.2, 34.974]])
+ diag2 = np.array([[2.8, 4.45],[9.5, 14.1]])
+
+ message = "Wasserstein distance value = " + '%.2f' % gudhi.wasserstein.wasserstein_distance(diag1, diag2, q=2., p=1.)
+ print(message)
+
+The output is:
+
+.. testoutput::
+
+ Wasserstein distance value = 1.45
diff --git a/src/python/example/diagram_vectorizations_distances_kernels.py b/src/python/example/diagram_vectorizations_distances_kernels.py
new file mode 100755
index 00000000..a77bbfdd
--- /dev/null
+++ b/src/python/example/diagram_vectorizations_distances_kernels.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.kernel_approximation import RBFSampler
+from sklearn.preprocessing import MinMaxScaler
+
+from gudhi.representations import DiagramSelector, Clamping, Landscape, Silhouette, BettiCurve, ComplexPolynomial,\
+ TopologicalVector, DiagramScaler, BirthPersistenceTransform,\
+ PersistenceImage, PersistenceWeightedGaussianKernel, Entropy, \
+ PersistenceScaleSpaceKernel, SlicedWassersteinDistance,\
+ SlicedWassersteinKernel, BottleneckDistance, PersistenceFisherKernel
+
+D = np.array([[0.,4.],[1.,2.],[3.,8.],[6.,8.], [0., np.inf], [5., np.inf]])
+diags = [D]
+
+diags = DiagramSelector(use=True, point_type="finite").fit_transform(diags)
+diags = DiagramScaler(use=True, scalers=[([0,1], MinMaxScaler())]).fit_transform(diags)
+diags = DiagramScaler(use=True, scalers=[([1], Clamping(limit=.9))]).fit_transform(diags)
+
+D = diags[0]
+plt.scatter(D[:,0],D[:,1])
+plt.plot([0.,1.],[0.,1.])
+plt.title("Test Persistence Diagram for vector methods")
+plt.show()
+
+LS = Landscape(resolution=1000)
+L = LS.fit_transform(diags)
+plt.plot(L[0][:1000])
+plt.plot(L[0][1000:2000])
+plt.plot(L[0][2000:3000])
+plt.title("Landscape")
+plt.show()
+
+def pow(n):
+ return lambda x: np.power(x[1]-x[0],n)
+
+SH = Silhouette(resolution=1000, weight=pow(2))
+sh = SH.fit_transform(diags)
+plt.plot(sh[0])
+plt.title("Silhouette")
+plt.show()
+
+BC = BettiCurve(resolution=1000)
+bc = BC.fit_transform(diags)
+plt.plot(bc[0])
+plt.title("Betti Curve")
+plt.show()
+
+CP = ComplexPolynomial(threshold=-1, polynomial_type="T")
+cp = CP.fit_transform(diags)
+print("Complex polynomial is " + str(cp[0,:]))
+
+TV = TopologicalVector(threshold=-1)
+tv = TV.fit_transform(diags)
+print("Topological vector is " + str(tv[0,:]))
+
+PI = PersistenceImage(bandwidth=.1, weight=lambda x: x[1], im_range=[0,1,0,1], resolution=[100,100])
+pi = PI.fit_transform(diags)
+plt.imshow(np.flip(np.reshape(pi[0], [100,100]), 0))
+plt.title("Persistence Image")
+plt.show()
+
+ET = Entropy(mode="scalar")
+et = ET.fit_transform(diags)
+print("Entropy statistic is " + str(et[0,:]))
+
+ET = Entropy(mode="vector", normalized=False)
+et = ET.fit_transform(diags)
+plt.plot(et[0])
+plt.title("Entropy function")
+plt.show()
+
+D = np.array([[1.,5.],[3.,6.],[2.,7.]])
+diags2 = [D]
+
+diags2 = DiagramScaler(use=True, scalers=[([0,1], MinMaxScaler())]).fit_transform(diags2)
+
+D = diags[0]
+plt.scatter(D[:,0],D[:,1])
+D = diags2[0]
+plt.scatter(D[:,0],D[:,1])
+plt.plot([0.,1.],[0.,1.])
+plt.title("Test Persistence Diagrams for kernel methods")
+plt.show()
+
+def arctan(C,p):
+ return lambda x: C*np.arctan(np.power(x[1], p))
+
+PWG = PersistenceWeightedGaussianKernel(bandwidth=1., kernel_approx=None, weight=arctan(1.,1.))
+X = PWG.fit(diags)
+Y = PWG.transform(diags2)
+print("PWG kernel is " + str(Y[0][0]))
+
+PWG = PersistenceWeightedGaussianKernel(kernel_approx=RBFSampler(gamma=1./2, n_components=100000).fit(np.ones([1,2])), weight=arctan(1.,1.))
+X = PWG.fit(diags)
+Y = PWG.transform(diags2)
+print("Approximate PWG kernel is " + str(Y[0][0]))
+
+PSS = PersistenceScaleSpaceKernel(bandwidth=1.)
+X = PSS.fit(diags)
+Y = PSS.transform(diags2)
+print("PSS kernel is " + str(Y[0][0]))
+
+PSS = PersistenceScaleSpaceKernel(kernel_approx=RBFSampler(gamma=1./2, n_components=100000).fit(np.ones([1,2])))
+X = PSS.fit(diags)
+Y = PSS.transform(diags2)
+print("Approximate PSS kernel is " + str(Y[0][0]))
+
+sW = SlicedWassersteinDistance(num_directions=100)
+X = sW.fit(diags)
+Y = sW.transform(diags2)
+print("SW distance is " + str(Y[0][0]))
+
+SW = SlicedWassersteinKernel(num_directions=100, bandwidth=1.)
+X = SW.fit(diags)
+Y = SW.transform(diags2)
+print("SW kernel is " + str(Y[0][0]))
+
+W = BottleneckDistance(epsilon=.001)
+X = W.fit(diags)
+Y = W.transform(diags2)
+print("Bottleneck distance is " + str(Y[0][0]))
+
+PF = PersistenceFisherKernel(bandwidth_fisher=1., bandwidth=1.)
+X = PF.fit(diags)
+Y = PF.transform(diags2)
+print("PF kernel is " + str(Y[0][0]))
+
+PF = PersistenceFisherKernel(bandwidth_fisher=1., bandwidth=1., kernel_approx=RBFSampler(gamma=1./2, n_components=100000).fit(np.ones([1,2])))
+X = PF.fit(diags)
+Y = PF.transform(diags2)
+print("Approximate PF kernel is " + str(Y[0][0]))
diff --git a/src/python/gudhi/__init__.py.in b/src/python/gudhi/__init__.py.in
index 28bab0e1..0c462b02 100644
--- a/src/python/gudhi/__init__.py.in
+++ b/src/python/gudhi/__init__.py.in
@@ -1,14 +1,13 @@
from importlib import import_module
-"""This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "GUDHI Editorial Board"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -21,13 +20,16 @@ __debug_info__ = @GUDHI_PYTHON_DEBUG_INFO@
from sys import exc_info
from importlib import import_module
-__all__ = [@GUDHI_PYTHON_MODULES@]
+__all__ = [@GUDHI_PYTHON_MODULES@ @GUDHI_PYTHON_MODULES_EXTRA@]
__available_modules = ''
__missing_modules = ''
-# try to import * from gudhi.__module_name
-for __module_name in __all__:
+# Try to import * from gudhi.__module_name for default modules.
+# Extra modules require an explicit import by the user (mostly because of
+# unusual dependencies, but also to avoid cluttering namespace gudhi and
+# speed up the basic import)
+for __module_name in [@GUDHI_PYTHON_MODULES@]:
try:
__module = import_module('gudhi.' + __module_name)
try:
diff --git a/src/python/gudhi/alpha_complex.pyx b/src/python/gudhi/alpha_complex.pyx
index 6d6309db..8f2c98d5 100644
--- a/src/python/gudhi/alpha_complex.pyx
+++ b/src/python/gudhi/alpha_complex.pyx
@@ -9,15 +9,14 @@ import os
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -68,7 +67,7 @@ cdef class AlphaComplex:
# The real cython constructor
def __cinit__(self, points=None, off_file=''):
- if off_file is not '':
+ if off_file:
if os.path.isfile(off_file):
self.thisptr = new Alpha_complex_interface(str.encode(off_file), True)
else:
diff --git a/src/python/gudhi/bottleneck.pyx b/src/python/gudhi/bottleneck.pyx
index 4b378cbc..c2361024 100644
--- a/src/python/gudhi/bottleneck.pyx
+++ b/src/python/gudhi/bottleneck.pyx
@@ -3,15 +3,14 @@ from libcpp.vector cimport vector
from libcpp.utility cimport pair
import os
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
diff --git a/src/python/gudhi/cubical_complex.pyx b/src/python/gudhi/cubical_complex.pyx
index 0dc133d1..011c407c 100644
--- a/src/python/gudhi/cubical_complex.pyx
+++ b/src/python/gudhi/cubical_complex.pyx
@@ -7,15 +7,14 @@ import os
from numpy import array as np_array
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -66,9 +65,9 @@ cdef class CubicalComplex:
# The real cython constructor
def __cinit__(self, dimensions=None, top_dimensional_cells=None,
perseus_file=''):
- if (dimensions is not None) and (top_dimensional_cells is not None) and (perseus_file is ''):
+ if (dimensions is not None) and (top_dimensional_cells is not None) and (perseus_file == ''):
self.thisptr = new Bitmap_cubical_complex_base_interface(dimensions, top_dimensional_cells)
- elif (dimensions is None) and (top_dimensional_cells is None) and (perseus_file is not ''):
+ elif (dimensions is None) and (top_dimensional_cells is None) and (perseus_file != ''):
if os.path.isfile(perseus_file):
self.thisptr = new Bitmap_cubical_complex_base_interface(str.encode(perseus_file))
else:
diff --git a/src/python/gudhi/euclidean_strong_witness_complex.pyx b/src/python/gudhi/euclidean_strong_witness_complex.pyx
index 5d6e4fb9..e3f451f0 100644
--- a/src/python/gudhi/euclidean_strong_witness_complex.pyx
+++ b/src/python/gudhi/euclidean_strong_witness_complex.pyx
@@ -6,15 +6,14 @@ from libc.stdint cimport intptr_t
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -71,7 +70,7 @@ cdef class EuclideanStrongWitnessComplex:
"""
stree = SimplexTree()
cdef intptr_t stree_int_ptr=stree.thisptr
- if limit_dimension is not -1:
+ if limit_dimension != -1:
self.thisptr.create_simplex_tree(<Simplex_tree_interface_full_featured*>stree_int_ptr,
max_alpha_square, limit_dimension)
else:
diff --git a/src/python/gudhi/euclidean_witness_complex.pyx b/src/python/gudhi/euclidean_witness_complex.pyx
index 2531919b..84a8ea1a 100644
--- a/src/python/gudhi/euclidean_witness_complex.pyx
+++ b/src/python/gudhi/euclidean_witness_complex.pyx
@@ -6,15 +6,14 @@ from libc.stdint cimport intptr_t
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -71,7 +70,7 @@ cdef class EuclideanWitnessComplex:
"""
stree = SimplexTree()
cdef intptr_t stree_int_ptr=stree.thisptr
- if limit_dimension is not -1:
+ if limit_dimension != -1:
self.thisptr.create_simplex_tree(<Simplex_tree_interface_full_featured*>stree_int_ptr,
max_alpha_square, limit_dimension)
else:
diff --git a/src/python/gudhi/nerve_gic.pyx b/src/python/gudhi/nerve_gic.pyx
index 2b230b8c..acb78564 100644
--- a/src/python/gudhi/nerve_gic.pyx
+++ b/src/python/gudhi/nerve_gic.pyx
@@ -9,15 +9,14 @@ from libc.stdint cimport intptr_t
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2018 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2018 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2018 Inria"
diff --git a/src/python/gudhi/off_reader.pyx b/src/python/gudhi/off_reader.pyx
index 9efd97ff..225e981c 100644
--- a/src/python/gudhi/off_reader.pyx
+++ b/src/python/gudhi/off_reader.pyx
@@ -3,15 +3,14 @@ from libcpp.vector cimport vector
from libcpp.string cimport string
import os
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -29,7 +28,7 @@ def read_off(off_file=''):
:returns: The point set.
:rtype: vector[vector[double]]
"""
- if off_file is not '':
+ if off_file:
if os.path.isfile(off_file):
return read_points_from_OFF_file(str.encode(off_file))
else:
diff --git a/src/python/gudhi/periodic_cubical_complex.pyx b/src/python/gudhi/periodic_cubical_complex.pyx
index 724fadd4..c89055db 100644
--- a/src/python/gudhi/periodic_cubical_complex.pyx
+++ b/src/python/gudhi/periodic_cubical_complex.pyx
@@ -7,15 +7,14 @@ import os
from numpy import array as np_array
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -68,9 +67,9 @@ cdef class PeriodicCubicalComplex:
# The real cython constructor
def __cinit__(self, dimensions=None, top_dimensional_cells=None,
periodic_dimensions=None, perseus_file=''):
- if (dimensions is not None) and (top_dimensional_cells is not None) and (periodic_dimensions is not None) and (perseus_file is ''):
+ if (dimensions is not None) and (top_dimensional_cells is not None) and (periodic_dimensions is not None) and (perseus_file == ''):
self.thisptr = new Periodic_cubical_complex_base_interface(dimensions, top_dimensional_cells, periodic_dimensions)
- elif (dimensions is None) and (top_dimensional_cells is None) and (periodic_dimensions is None) and (perseus_file is not ''):
+ elif (dimensions is None) and (top_dimensional_cells is None) and (periodic_dimensions is None) and (perseus_file != ''):
if os.path.isfile(perseus_file):
self.thisptr = new Periodic_cubical_complex_base_interface(str.encode(perseus_file))
else:
diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py
index a8e2051b..23725ca7 100644
--- a/src/python/gudhi/persistence_graphical_tools.py
+++ b/src/python/gudhi/persistence_graphical_tools.py
@@ -5,15 +5,14 @@ import numpy as np
from gudhi.reader_utils import read_persistence_intervals_in_dimension
from gudhi.reader_utils import read_persistence_intervals_grouped_by_dimension
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau, Bertrand Michel
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau, Bertrand Michel
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau, Bertrand Michel"
__copyright__ = "Copyright (C) 2016 Inria"
diff --git a/src/python/gudhi/reader_utils.pyx b/src/python/gudhi/reader_utils.pyx
index 147fae71..6994c4f9 100644
--- a/src/python/gudhi/reader_utils.pyx
+++ b/src/python/gudhi/reader_utils.pyx
@@ -7,15 +7,14 @@ from libcpp.pair cimport pair
from os import path
from numpy import array as np_array
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2017 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2017 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2017 Inria"
@@ -37,7 +36,7 @@ def read_lower_triangular_matrix_from_csv_file(csv_file='', separator=';'):
:returns: The lower triangular matrix.
:rtype: vector[vector[double]]
"""
- if csv_file is not '':
+ if csv_file:
if path.isfile(csv_file):
return read_matrix_from_csv_file(str.encode(csv_file), ord(separator[0]))
print("file " + csv_file + " not set or not found.")
@@ -56,7 +55,7 @@ def read_persistence_intervals_grouped_by_dimension(persistence_file=''):
:returns: The persistence pairs grouped by dimension.
:rtype: map[int, vector[pair[double, double]]]
"""
- if persistence_file is not '':
+ if persistence_file:
if path.isfile(persistence_file):
return read_pers_intervals_grouped_by_dimension(str.encode(persistence_file))
print("file " + persistence_file + " not set or not found.")
@@ -79,7 +78,7 @@ def read_persistence_intervals_in_dimension(persistence_file='', only_this_dim=-
:returns: The persistence intervals.
:rtype: numpy array of dimension 2
"""
- if persistence_file is not '':
+ if persistence_file:
if path.isfile(persistence_file):
return np_array(read_pers_intervals_in_dimension(str.encode(
persistence_file), only_this_dim))
diff --git a/src/python/gudhi/representations/__init__.py b/src/python/gudhi/representations/__init__.py
new file mode 100644
index 00000000..f020248d
--- /dev/null
+++ b/src/python/gudhi/representations/__init__.py
@@ -0,0 +1,6 @@
+from .kernel_methods import *
+from .metrics import *
+from .preprocessing import *
+from .vector_methods import *
+
+__all__ = ["kernel_methods", "metrics", "preprocessing", "vector_methods"]
diff --git a/src/python/gudhi/representations/kernel_methods.py b/src/python/gudhi/representations/kernel_methods.py
new file mode 100644
index 00000000..c855d2be
--- /dev/null
+++ b/src/python/gudhi/representations/kernel_methods.py
@@ -0,0 +1,206 @@
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Mathieu Carrière
+#
+# Copyright (C) 2018-2019 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
+
+import numpy as np
+from sklearn.base import BaseEstimator, TransformerMixin
+from sklearn.metrics import pairwise_distances
+from .metrics import SlicedWassersteinDistance, PersistenceFisherDistance
+
+#############################################
+# Kernel methods ############################
+#############################################
+
+class SlicedWassersteinKernel(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing the sliced Wasserstein kernel matrix from a list of persistence diagrams. The sliced Wasserstein kernel is computed by exponentiating the corresponding sliced Wasserstein distance with a Gaussian kernel. See http://proceedings.mlr.press/v70/carriere17a.html for more details.
+ """
+ def __init__(self, num_directions=10, bandwidth=1.0):
+ """
+ Constructor for the SlicedWassersteinKernel class.
+
+ Parameters:
+ bandwidth (double): bandwidth of the Gaussian kernel applied to the sliced Wasserstein distance (default 1.).
+ num_directions (int): number of lines evenly sampled from [-pi/2,pi/2] in order to approximate and speed up the kernel computation (default 10).
+ """
+ self.bandwidth = bandwidth
+ self.sw_ = SlicedWassersteinDistance(num_directions=num_directions)
+
+ def fit(self, X, y=None):
+ """
+ Fit the SlicedWassersteinKernel class on a list of persistence diagrams: an instance of the SlicedWassersteinDistance class is fitted on the diagrams and then stored.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.sw_.fit(X, y)
+ return self
+
+ def transform(self, X):
+ """
+ Compute all sliced Wasserstein kernel values between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array of shape (number of diagrams in **diagrams**) x (number of diagrams in X): matrix of pairwise sliced Wasserstein kernel values.
+ """
+ return np.exp(-self.sw_.transform(X)/self.bandwidth)
+
+class PersistenceWeightedGaussianKernel(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing the persistence weighted Gaussian kernel matrix from a list of persistence diagrams. The persistence weighted Gaussian kernel is computed by convolving the persistence diagram points with weighted Gaussian kernels. See http://proceedings.mlr.press/v48/kusano16.html for more details.
+ """
+ def __init__(self, bandwidth=1., weight=lambda x: 1, kernel_approx=None):
+ """
+ Constructor for the PersistenceWeightedGaussianKernel class.
+
+ Parameters:
+ bandwidth (double): bandwidth of the Gaussian kernel with which persistence diagrams will be convolved (default 1.)
+ weight (function): weight function for the persistence diagram points (default constant function, ie lambda x: 1). This function must be defined on 2D points, ie lists or numpy arrays of the form [p_x,p_y].
+ kernel_approx (class): kernel approximation class used to speed up computation (default None). Common kernel approximations classes can be found in the scikit-learn library (such as RBFSampler for instance).
+ """
+ self.bandwidth, self.weight = bandwidth, weight
+ self.kernel_approx = kernel_approx
+
+ def fit(self, X, y=None):
+ """
+ Fit the PersistenceWeightedGaussianKernel class on a list of persistence diagrams: persistence diagrams are stored in a numpy array called **diagrams** and the kernel approximation class (if not None) is applied on them.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.diagrams_ = list(X)
+ self.ws_ = [ np.array([self.weight(self.diagrams_[i][j,:]) for j in range(self.diagrams_[i].shape[0])]) for i in range(len(self.diagrams_)) ]
+ if self.kernel_approx is not None:
+ self.approx_ = np.concatenate([np.sum(np.multiply(self.ws_[i][:,np.newaxis], self.kernel_approx.transform(self.diagrams_[i])), axis=0)[np.newaxis,:] for i in range(len(self.diagrams_))])
+ return self
+
+ def transform(self, X):
+ """
+ Compute all persistence weighted Gaussian kernel values between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array of shape (number of diagrams in **diagrams**) x (number of diagrams in X): matrix of pairwise persistence weighted Gaussian kernel values.
+ """
+ Xp = list(X)
+ Xfit = np.zeros((len(Xp), len(self.diagrams_)))
+ if len(self.diagrams_) == len(Xp) and np.all([np.array_equal(self.diagrams_[i], Xp[i]) for i in range(len(Xp))]):
+ if self.kernel_approx is not None:
+ Xfit = (1./(np.sqrt(2*np.pi)*self.bandwidth)) * np.matmul(self.approx_, self.approx_.T)
+ else:
+ for i in range(len(self.diagrams_)):
+ for j in range(i+1, len(self.diagrams_)):
+ W = np.matmul(self.ws_[i][:,np.newaxis], self.ws_[j][np.newaxis,:])
+ E = (1./(np.sqrt(2*np.pi)*self.bandwidth)) * np.exp(-np.square(pairwise_distances(self.diagrams_[i], self.diagrams_[j]))/(2*np.square(self.bandwidth)))
+ Xfit[i,j] = np.sum(np.multiply(W, E))
+ Xfit[j,i] = Xfit[i,j]
+ else:
+ ws = [ np.array([self.weight(Xp[i][j,:]) for j in range(Xp[i].shape[0])]) for i in range(len(Xp)) ]
+ if self.kernel_approx is not None:
+ approx = np.concatenate([np.sum(np.multiply(ws[i][:,np.newaxis], self.kernel_approx.transform(Xp[i])), axis=0)[np.newaxis,:] for i in range(len(Xp))])
+ Xfit = (1./(np.sqrt(2*np.pi)*self.bandwidth)) * np.matmul(approx, self.approx_.T)
+ else:
+ for i in range(len(Xp)):
+ for j in range(len(self.diagrams_)):
+ W = np.matmul(ws[i][:,np.newaxis], self.ws_[j][np.newaxis,:])
+ E = (1./(np.sqrt(2*np.pi)*self.bandwidth)) * np.exp(-np.square(pairwise_distances(Xp[i], self.diagrams_[j]))/(2*np.square(self.bandwidth)))
+ Xfit[i,j] = np.sum(np.multiply(W, E))
+
+ return Xfit
+
+class PersistenceScaleSpaceKernel(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing the persistence scale space kernel matrix from a list of persistence diagrams. The persistence scale space kernel is computed by adding the symmetric to the diagonal of each point in each persistence diagram, with negative weight, and then convolving the points with a Gaussian kernel. See https://www.cv-foundation.org/openaccess/content_cvpr_2015/papers/Reininghaus_A_Stable_Multi-Scale_2015_CVPR_paper.pdf for more details.
+ """
+ def __init__(self, bandwidth=1., kernel_approx=None):
+ """
+ Constructor for the PersistenceScaleSpaceKernel class.
+
+ Parameters:
+ bandwidth (double): bandwidth of the Gaussian kernel with which persistence diagrams will be convolved (default 1.)
+ kernel_approx (class): kernel approximation class used to speed up computation (default None). Common kernel approximations classes can be found in the scikit-learn library (such as RBFSampler for instance).
+ """
+ self.pwg_ = PersistenceWeightedGaussianKernel(bandwidth=bandwidth, weight=lambda x: 1 if x[1] >= x[0] else -1, kernel_approx=kernel_approx)
+
+ def fit(self, X, y=None):
+ """
+ Fit the PersistenceScaleSpaceKernel class on a list of persistence diagrams: symmetric to the diagonal of all points are computed and an instance of the PersistenceWeightedGaussianKernel class is fitted on the diagrams and then stored.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.diagrams_ = list(X)
+ for i in range(len(self.diagrams_)):
+ op_D = self.diagrams_[i][:,[1,0]]
+ self.diagrams_[i] = np.concatenate([self.diagrams_[i], op_D], axis=0)
+ self.pwg_.fit(X)
+ return self
+
+ def transform(self, X):
+ """
+ Compute all persistence scale space kernel values between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array of shape (number of diagrams in **diagrams**) x (number of diagrams in X): matrix of pairwise persistence scale space kernel values.
+ """
+ Xp = list(X)
+ for i in range(len(Xp)):
+ op_X = np.matmul(Xp[i], np.array([[0.,1.], [1.,0.]]))
+ Xp[i] = np.concatenate([Xp[i], op_X], axis=0)
+ return self.pwg_.transform(Xp)
+
+class PersistenceFisherKernel(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing the persistence Fisher kernel matrix from a list of persistence diagrams. The persistence Fisher kernel is computed by exponentiating the corresponding persistence Fisher distance with a Gaussian kernel. See papers.nips.cc/paper/8205-persistence-fisher-kernel-a-riemannian-manifold-kernel-for-persistence-diagrams for more details.
+ """
+ def __init__(self, bandwidth_fisher=1., bandwidth=1., kernel_approx=None):
+ """
+ Constructor for the PersistenceFisherKernel class.
+
+ Parameters:
+ bandwidth (double): bandwidth of the Gaussian kernel applied to the persistence Fisher distance (default 1.).
+ bandwidth_fisher (double): bandwidth of the Gaussian kernel used to turn persistence diagrams into probability distributions by PersistenceFisherDistance class (default 1.).
+ kernel_approx (class): kernel approximation class used to speed up computation (default None). Common kernel approximations classes can be found in the scikit-learn library (such as RBFSampler for instance).
+ """
+ self.bandwidth = bandwidth
+ self.pf_ = PersistenceFisherDistance(bandwidth=bandwidth_fisher, kernel_approx=kernel_approx)
+
+ def fit(self, X, y=None):
+ """
+ Fit the PersistenceFisherKernel class on a list of persistence diagrams: an instance of the PersistenceFisherDistance class is fitted on the diagrams and then stored.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.pf_.fit(X, y)
+ return self
+
+ def transform(self, X):
+ """
+ Compute all persistence Fisher kernel values between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array of shape (number of diagrams in **diagrams**) x (number of diagrams in X): matrix of pairwise persistence Fisher kernel values.
+ """
+ return np.exp(-self.pf_.transform(X)/self.bandwidth)
+
diff --git a/src/python/gudhi/representations/metrics.py b/src/python/gudhi/representations/metrics.py
new file mode 100644
index 00000000..c512cb82
--- /dev/null
+++ b/src/python/gudhi/representations/metrics.py
@@ -0,0 +1,243 @@
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Mathieu Carrière
+#
+# Copyright (C) 2018-2019 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
+
+import numpy as np
+from sklearn.base import BaseEstimator, TransformerMixin
+from sklearn.metrics import pairwise_distances
+try:
+ from .. import bottleneck_distance
+ USE_GUDHI = True
+except ImportError:
+ USE_GUDHI = False
+ print("Gudhi built without CGAL: BottleneckDistance will return a null matrix")
+
+#############################################
+# Metrics ###################################
+#############################################
+
+class SlicedWassersteinDistance(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing the sliced Wasserstein distance matrix from a list of persistence diagrams. The Sliced Wasserstein distance is computed by projecting the persistence diagrams onto lines, comparing the projections with the 1-norm, and finally integrating over all possible lines. See http://proceedings.mlr.press/v70/carriere17a.html for more details.
+ """
+ def __init__(self, num_directions=10):
+ """
+ Constructor for the SlicedWassersteinDistance class.
+
+ Parameters:
+ num_directions (int): number of lines evenly sampled from [-pi/2,pi/2] in order to approximate and speed up the distance computation (default 10).
+ """
+ self.num_directions = num_directions
+ thetas = np.linspace(-np.pi/2, np.pi/2, num=self.num_directions+1)[np.newaxis,:-1]
+ self.lines_ = np.concatenate([np.cos(thetas), np.sin(thetas)], axis=0)
+
+ def fit(self, X, y=None):
+ """
+ Fit the SlicedWassersteinDistance class on a list of persistence diagrams: persistence diagrams are projected onto the different lines. The diagrams themselves and their projections are then stored in numpy arrays, called **diagrams_** and **approx_diag_**.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.diagrams_ = X
+ self.approx_ = [np.matmul(X[i], self.lines_) for i in range(len(X))]
+ diag_proj = (1./2) * np.ones((2,2))
+ self.approx_diag_ = [np.matmul(np.matmul(X[i], diag_proj), self.lines_) for i in range(len(X))]
+ return self
+
+ def transform(self, X):
+ """
+ Compute all sliced Wasserstein distances between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array of shape (number of diagrams in **diagrams**) x (number of diagrams in X): matrix of pairwise sliced Wasserstein distances.
+ """
+ Xfit = np.zeros((len(X), len(self.approx_)))
+ if len(self.diagrams_) == len(X) and np.all([np.array_equal(self.diagrams_[i], X[i]) for i in range(len(X))]):
+ for i in range(len(self.approx_)):
+ for j in range(i+1, len(self.approx_)):
+ A = np.sort(np.concatenate([self.approx_[i], self.approx_diag_[j]], axis=0), axis=0)
+ B = np.sort(np.concatenate([self.approx_[j], self.approx_diag_[i]], axis=0), axis=0)
+ L1 = np.sum(np.abs(A-B), axis=0)
+ Xfit[i,j] = np.mean(L1)
+ Xfit[j,i] = Xfit[i,j]
+ else:
+ diag_proj = (1./2) * np.ones((2,2))
+ approx = [np.matmul(X[i], self.lines_) for i in range(len(X))]
+ approx_diag = [np.matmul(np.matmul(X[i], diag_proj), self.lines_) for i in range(len(X))]
+ for i in range(len(approx)):
+ for j in range(len(self.approx_)):
+ A = np.sort(np.concatenate([approx[i], self.approx_diag_[j]], axis=0), axis=0)
+ B = np.sort(np.concatenate([self.approx_[j], approx_diag[i]], axis=0), axis=0)
+ L1 = np.sum(np.abs(A-B), axis=0)
+ Xfit[i,j] = np.mean(L1)
+
+ return Xfit
+
+class BottleneckDistance(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing the bottleneck distance matrix from a list of persistence diagrams.
+ """
+ def __init__(self, epsilon=1e-3):
+ """
+ Constructor for the BottleneckDistance class.
+
+ Parameters:
+ epsilon (double): approximation quality (default 1e-4).
+ """
+ self.epsilon = epsilon
+
+ def fit(self, X, y=None):
+ """
+ Fit the BottleneckDistance class on a list of persistence diagrams: persistence diagrams are stored in a numpy array called **diagrams**.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.diagrams_ = X
+ return self
+
+ def transform(self, X):
+ """
+ Compute all bottleneck distances between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array of shape (number of diagrams in **diagrams**) x (number of diagrams in X): matrix of pairwise bottleneck distances.
+ """
+ num_diag1 = len(X)
+
+ if len(self.diagrams_) == len(X) and np.all([np.array_equal(self.diagrams_[i], X[i]) for i in range(len(X))]):
+ matrix = np.zeros((num_diag1, num_diag1))
+
+ if USE_GUDHI:
+ for i in range(num_diag1):
+ for j in range(i+1, num_diag1):
+ matrix[i,j] = bottleneck_distance(X[i], X[j], self.epsilon)
+ matrix[j,i] = matrix[i,j]
+ else:
+ print("Gudhi required---returning null matrix")
+
+ else:
+ num_diag2 = len(self.diagrams_)
+ matrix = np.zeros((num_diag1, num_diag2))
+
+ if USE_GUDHI:
+ for i in range(num_diag1):
+ for j in range(num_diag2):
+ matrix[i,j] = bottleneck_distance(X[i], self.diagrams_[j], self.epsilon)
+ else:
+ print("Gudhi required---returning null matrix")
+
+ Xfit = matrix
+
+ return Xfit
+
+class PersistenceFisherDistance(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing the persistence Fisher distance matrix from a list of persistence diagrams. The persistence Fisher distance is obtained by computing the original Fisher distance between the probability distributions associated to the persistence diagrams given by convolving them with a Gaussian kernel. See http://papers.nips.cc/paper/8205-persistence-fisher-kernel-a-riemannian-manifold-kernel-for-persistence-diagrams for more details.
+ """
+ def __init__(self, bandwidth=1., kernel_approx=None):
+ """
+ Constructor for the PersistenceFisherDistance class.
+
+ Parameters:
+ bandwidth (double): bandwidth of the Gaussian kernel used to turn persistence diagrams into probability distributions (default 1.).
+ kernel_approx (class): kernel approximation class used to speed up computation (default None). Common kernel approximations classes can be found in the scikit-learn library (such as RBFSampler for instance).
+ """
+ self.bandwidth, self.kernel_approx = bandwidth, kernel_approx
+
+ def fit(self, X, y=None):
+ """
+ Fit the PersistenceFisherDistance class on a list of persistence diagrams: persistence diagrams are stored in a numpy array called **diagrams** and the kernel approximation class (if not None) is applied on them.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.diagrams_ = X
+ projection = (1./2) * np.ones((2,2))
+ self.diagonal_projections_ = [np.matmul(X[i], projection) for i in range(len(X))]
+ if self.kernel_approx is not None:
+ self.approx_ = [self.kernel_approx.transform(X[i]) for i in range(len(X))]
+ self.approx_diagonal_ = [self.kernel_approx.transform(self.diagonal_projections_[i]) for i in range(len(X))]
+ return self
+
+ def transform(self, X):
+ """
+ Compute all persistence Fisher distances between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array of shape (number of diagrams in **diagrams**) x (number of diagrams in X): matrix of pairwise persistence Fisher distances.
+ """
+ Xfit = np.zeros((len(X), len(self.diagrams_)))
+ if len(self.diagrams_) == len(X) and np.all([np.array_equal(self.diagrams_[i], X[i]) for i in range(len(X))]):
+ for i in range(len(self.diagrams_)):
+ for j in range(i+1, len(self.diagrams_)):
+ if self.kernel_approx is not None:
+ Z = np.concatenate([self.approx_[i], self.approx_diagonal_[i], self.approx_[j], self.approx_diagonal_[j]], axis=0)
+ U, V = np.sum(np.concatenate([self.approx_[i], self.approx_diagonal_[j]], axis=0), axis=0), np.sum(np.concatenate([self.approx_[j], self.approx_diagonal_[i]], axis=0), axis=0)
+ vectori, vectorj = np.abs(np.matmul(Z, U.T)), np.abs(np.matmul(Z, V.T))
+ vectori_sum, vectorj_sum = np.sum(vectori), np.sum(vectorj)
+ if vectori_sum != 0:
+ vectori = vectori/vectori_sum
+ if vectorj_sum != 0:
+ vectorj = vectorj/vectorj_sum
+ Xfit[i,j] = np.arccos( min(np.dot(np.sqrt(vectori), np.sqrt(vectorj)), 1.) )
+ Xfit[j,i] = Xfit[i,j]
+ else:
+ Z = np.concatenate([self.diagrams_[i], self.diagonal_projections_[i], self.diagrams_[j], self.diagonal_projections_[j]], axis=0)
+ U, V = np.concatenate([self.diagrams_[i], self.diagonal_projections_[j]], axis=0), np.concatenate([self.diagrams_[j], self.diagonal_projections_[i]], axis=0)
+ vectori = np.sum(np.exp(-np.square(pairwise_distances(Z,U))/(2 * np.square(self.bandwidth)))/(self.bandwidth * np.sqrt(2*np.pi)), axis=1)
+ vectorj = np.sum(np.exp(-np.square(pairwise_distances(Z,V))/(2 * np.square(self.bandwidth)))/(self.bandwidth * np.sqrt(2*np.pi)), axis=1)
+ vectori_sum, vectorj_sum = np.sum(vectori), np.sum(vectorj)
+ if vectori_sum != 0:
+ vectori = vectori/vectori_sum
+ if vectorj_sum != 0:
+ vectorj = vectorj/vectorj_sum
+ Xfit[i,j] = np.arccos( min(np.dot(np.sqrt(vectori), np.sqrt(vectorj)), 1.) )
+ Xfit[j,i] = Xfit[i,j]
+ else:
+ projection = (1./2) * np.ones((2,2))
+ diagonal_projections = [np.matmul(X[i], projection) for i in range(len(X))]
+ if self.kernel_approx is not None:
+ approx = [self.kernel_approx.transform(X[i]) for i in range(len(X))]
+ approx_diagonal = [self.kernel_approx.transform(diagonal_projections[i]) for i in range(len(X))]
+ for i in range(len(X)):
+ for j in range(len(self.diagrams_)):
+ if self.kernel_approx is not None:
+ Z = np.concatenate([approx[i], approx_diagonal[i], self.approx_[j], self.approx_diagonal_[j]], axis=0)
+ U, V = np.sum(np.concatenate([approx[i], self.approx_diagonal_[j]], axis=0), axis=0), np.sum(np.concatenate([self.approx_[j], approx_diagonal[i]], axis=0), axis=0)
+ vectori, vectorj = np.abs(np.matmul(Z, U.T)), np.abs(np.matmul(Z, V.T))
+ vectori_sum, vectorj_sum = np.sum(vectori), np.sum(vectorj)
+ if vectori_sum != 0:
+ vectori = vectori/vectori_sum
+ if vectorj_sum != 0:
+ vectorj = vectorj/vectorj_sum
+ Xfit[i,j] = np.arccos( min(np.dot(np.sqrt(vectori), np.sqrt(vectorj)), 1.) )
+ else:
+ Z = np.concatenate([X[i], diagonal_projections[i], self.diagrams_[j], self.diagonal_projections_[j]], axis=0)
+ U, V = np.concatenate([X[i], self.diagonal_projections_[j]], axis=0), np.concatenate([self.diagrams_[j], diagonal_projections[i]], axis=0)
+ vectori = np.sum(np.exp(-np.square(pairwise_distances(Z,U))/(2 * np.square(self.bandwidth)))/(self.bandwidth * np.sqrt(2*np.pi)), axis=1)
+ vectorj = np.sum(np.exp(-np.square(pairwise_distances(Z,V))/(2 * np.square(self.bandwidth)))/(self.bandwidth * np.sqrt(2*np.pi)), axis=1)
+ vectori_sum, vectorj_sum = np.sum(vectori), np.sum(vectorj)
+ if vectori_sum != 0:
+ vectori = vectori/vectori_sum
+ if vectorj_sum != 0:
+ vectorj = vectorj/vectorj_sum
+ Xfit[i,j] = np.arccos( min(np.dot(np.sqrt(vectori), np.sqrt(vectorj)), 1.) )
+ return Xfit
diff --git a/src/python/gudhi/representations/preprocessing.py b/src/python/gudhi/representations/preprocessing.py
new file mode 100644
index 00000000..83227ca1
--- /dev/null
+++ b/src/python/gudhi/representations/preprocessing.py
@@ -0,0 +1,305 @@
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Mathieu Carrière
+#
+# Copyright (C) 2018-2019 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
+
+import numpy as np
+from sklearn.base import BaseEstimator, TransformerMixin
+from sklearn.preprocessing import StandardScaler
+
+#############################################
+# Preprocessing #############################
+#############################################
+
+class BirthPersistenceTransform(BaseEstimator, TransformerMixin):
+ """
+ This is a class for the affine transformation (x,y) -> (x,y-x) to be applied on persistence diagrams.
+ """
+ def __init__(self):
+ """
+ Constructor for BirthPersistenceTransform class.
+ """
+ return None
+
+ def fit(self, X, y=None):
+ """
+ Fit the BirthPersistenceTransform class on a list of persistence diagrams (this function actually does nothing but is useful when BirthPersistenceTransform is included in a scikit-learn Pipeline).
+
+ Parameters:
+ X (n x 2 numpy array): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ return self
+
+ def transform(self, X):
+ """
+ Apply the BirthPersistenceTransform function on the persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy array): input persistence diagrams.
+
+ Returns:
+ list of n x 2 numpy array: transformed persistence diagrams.
+ """
+ Xfit = []
+ for diag in X:
+ #new_diag = np.empty(diag.shape)
+ #np.copyto(new_diag, diag)
+ new_diag = np.copy(diag)
+ new_diag[:,1] = new_diag[:,1] - new_diag[:,0]
+ Xfit.append(new_diag)
+ return Xfit
+
+class Clamping(BaseEstimator, TransformerMixin):
+ """
+ This is a class for clamping values. It can be used as a parameter for the DiagramScaler class, for instance if you want to clamp abscissae or ordinates of persistence diagrams.
+ """
+ def __init__(self, limit=np.inf):
+ """
+ Constructor for the Clamping class.
+
+ Parameters:
+ limit (double): clamping value (default np.inf).
+ """
+ self.limit = limit
+
+ def fit(self, X, y=None):
+ """
+ Fit the Clamping class on a list of values (this function actually does nothing but is useful when Clamping is included in a scikit-learn Pipeline).
+
+ Parameters:
+ X (numpy array of size n): input values.
+ y (n x 1 array): value labels (unused).
+ """
+ return self
+
+ def transform(self, X):
+ """
+ Clamp list of values.
+
+ Parameters:
+ X (numpy array of size n): input list of values.
+
+ Returns:
+ numpy array of size n: output list of values.
+ """
+ Xfit = np.minimum(X, self.limit)
+ #Xfit = np.where(X >= self.limit, self.limit * np.ones(X.shape), X)
+ return Xfit
+
+class DiagramScaler(BaseEstimator, TransformerMixin):
+ """
+ This is a class for preprocessing persistence diagrams with a given list of scalers, such as those included in scikit-learn.
+ """
+ def __init__(self, use=False, scalers=[]):
+ """
+ Constructor for the DiagramScaler class.
+
+ Parameters:
+ use (bool): whether to use the class or not (default False).
+ scalers (list of classes): list of scalers to be fit on the persistence diagrams (default []). Each element of the list is a tuple with two elements: the first one is a list of coordinates, and the second one is a scaler (i.e. a class with fit() and transform() methods) that is going to be applied to these coordinates. Common scalers can be found in the scikit-learn library (such as MinMaxScaler for instance).
+ """
+ self.scalers = scalers
+ self.use = use
+
+ def fit(self, X, y=None):
+ """
+ Fit the DiagramScaler class on a list of persistence diagrams: persistence diagrams are concatenated in a big numpy array, and scalers are fit (by calling their fit() method) on their corresponding coordinates in this big array.
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ if self.use:
+ if len(X) == 1:
+ P = X[0]
+ else:
+ P = np.concatenate(X,0)
+ for (indices, scaler) in self.scalers:
+ scaler.fit(np.reshape(P[:,indices], [-1, 1]))
+ return self
+
+ def transform(self, X):
+ """
+ Apply the DiagramScaler function on the persistence diagrams. The fitted scalers are applied (by calling their transform() method) to their corresponding coordinates in each persistence diagram individually.
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+
+ Returns:
+ list of n x 2 or n x 1 numpy arrays: transformed persistence diagrams.
+ """
+ Xfit = [np.copy(d) for d in X]
+ if self.use:
+ for i in range(len(Xfit)):
+ if Xfit[i].shape[0] > 0:
+ for (indices, scaler) in self.scalers:
+ for I in indices:
+ Xfit[i][:,I] = np.squeeze(scaler.transform(np.reshape(Xfit[i][:,I], [-1,1])))
+ return Xfit
+
+class Padding(BaseEstimator, TransformerMixin):
+ """
+ This is a class for padding a list of persistence diagrams with dummy points, so that all persistence diagrams end up with the same number of points.
+ """
+ def __init__(self, use=False):
+ """
+ Constructor for the Padding class.
+
+ Parameters:
+ use (bool): whether to use the class or not (default False).
+ """
+ self.use = use
+
+ def fit(self, X, y=None):
+ """
+ Fit the Padding class on a list of persistence diagrams (this function actually does nothing but is useful when Padding is included in a scikit-learn Pipeline).
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ self.max_pts = max([len(diag) for diag in X])
+ return self
+
+ def transform(self, X):
+ """
+ Add dummy points to each persistence diagram so that they all have the same cardinality. All points are given an additional coordinate indicating if the point was added after padding (0) or already present before (1).
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+
+ Returns:
+ list of n x 3 or n x 2 numpy arrays: padded persistence diagrams.
+ """
+ if self.use:
+ Xfit, num_diag = [], len(X)
+ for diag in X:
+ diag_pad = np.pad(diag, ((0,max(0, self.max_pts - diag.shape[0])), (0,1)), "constant", constant_values=((0,0),(0,0)))
+ diag_pad[:diag.shape[0],2] = np.ones(diag.shape[0])
+ Xfit.append(diag_pad)
+ else:
+ Xfit = X
+ return Xfit
+
+class ProminentPoints(BaseEstimator, TransformerMixin):
+ """
+ This is a class for removing points that are close or far from the diagonal in persistence diagrams. If persistence diagrams are n x 2 numpy arrays (i.e. persistence diagrams with ordinary features), points are ordered and thresholded by distance-to-diagonal. If persistence diagrams are n x 1 numpy arrays (i.e. persistence diagrams with essential features), points are not ordered and thresholded by first coordinate.
+ """
+ def __init__(self, use=False, num_pts=10, threshold=-1, location="upper"):
+ """
+ Constructor for the ProminentPoints class.
+
+ Parameters:
+ use (bool): whether to use the class or not (default False).
+ location (string): either "upper" or "lower" (default "upper"). Whether to keep the points that are far away ("upper") or close ("lower") to the diagonal.
+ num_pts (int): cardinality threshold (default 10). If location == "upper", keep the top **num_pts** points that are the farthest away from the diagonal. If location == "lower", keep the top **num_pts** points that are the closest to the diagonal.
+ threshold (double): distance-to-diagonal threshold (default -1). If location == "upper", keep the points that are at least at a distance **threshold** from the diagonal. If location == "lower", keep the points that are at most at a distance **threshold** from the diagonal.
+ """
+ self.num_pts = num_pts
+ self.threshold = threshold
+ self.use = use
+ self.location = location
+
+ def fit(self, X, y=None):
+ """
+ Fit the ProminentPoints class on a list of persistence diagrams (this function actually does nothing but is useful when ProminentPoints is included in a scikit-learn Pipeline).
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ return self
+
+ def transform(self, X):
+ """
+ If location == "upper", first select the top **num_pts** points that are the farthest away from the diagonal, then select and return from these points the ones that are at least at distance **threshold** from the diagonal for each persistence diagram individually. If location == "lower", first select the top **num_pts** points that are the closest to the diagonal, then select and return from these points the ones that are at most at distance **threshold** from the diagonal for each persistence diagram individually.
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+
+ Returns:
+ list of n x 2 or n x 1 numpy arrays: thresholded persistence diagrams.
+ """
+ if self.use:
+ Xfit, num_diag = [], len(X)
+ for i in range(num_diag):
+ diag = X[i]
+ if diag.shape[1] >= 2:
+ if diag.shape[0] > 0:
+ pers = np.abs(diag[:,1] - diag[:,0])
+ idx_thresh = pers >= self.threshold
+ thresh_diag, thresh_pers = diag[idx_thresh], pers[idx_thresh]
+ sort_index = np.flip(np.argsort(thresh_pers, axis=None), 0)
+ if self.location == "upper":
+ new_diag = thresh_diag[sort_index[:min(self.num_pts, thresh_diag.shape[0])],:]
+ if self.location == "lower":
+ new_diag = np.concatenate( [ thresh_diag[sort_index[min(self.num_pts, thresh_diag.shape[0]):],:], diag[~idx_thresh] ], axis=0)
+ else:
+ new_diag = diag
+
+ else:
+ if diag.shape[0] > 0:
+ birth = diag[:,:1]
+ idx_thresh = birth >= self.threshold
+ thresh_diag, thresh_birth = diag[idx_thresh], birth[idx_thresh]
+ if self.location == "upper":
+ new_diag = thresh_diag[:min(self.num_pts, thresh_diag.shape[0]),:]
+ if self.location == "lower":
+ new_diag = np.concatenate( [ thresh_diag[min(self.num_pts, thresh_diag.shape[0]):,:], diag[~idx_thresh] ], axis=0)
+ else:
+ new_diag = diag
+
+ Xfit.append(new_diag)
+ else:
+ Xfit = X
+ return Xfit
+
+class DiagramSelector(BaseEstimator, TransformerMixin):
+ """
+ This is a class for extracting finite or essential points in persistence diagrams.
+ """
+ def __init__(self, use=False, limit=np.inf, point_type="finite"):
+ """
+ Constructor for the DiagramSelector class.
+
+ Parameters:
+ use (bool): whether to use the class or not (default False).
+ limit (double): second coordinate value that is the criterion for being an essential point (default numpy.inf).
+ point_type (string): either "finite" or "essential". The type of the points that are going to be extracted.
+ """
+ self.use, self.limit, self.point_type = use, limit, point_type
+
+ def fit(self, X, y=None):
+ """
+ Fit the DiagramSelector class on a list of persistence diagrams (this function actually does nothing but is useful when DiagramSelector is included in a scikit-learn Pipeline).
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ return self
+
+ def transform(self, X):
+ """
+ Extract and return the finite or essential points of each persistence diagram individually.
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+
+ Returns:
+ list of n x 2 or n x 1 numpy arrays: extracted persistence diagrams.
+ """
+ if self.use:
+ Xfit, num_diag = [], len(X)
+ if self.point_type == "finite":
+ Xfit = [ diag[diag[:,1] < self.limit] if diag.shape[0] != 0 else diag for diag in X]
+ else:
+ Xfit = [ diag[diag[:,1] >= self.limit, 0:1] if diag.shape[0] != 0 else diag for diag in X]
+ else:
+ Xfit = X
+ return Xfit
diff --git a/src/python/gudhi/representations/vector_methods.py b/src/python/gudhi/representations/vector_methods.py
new file mode 100644
index 00000000..bf32f18e
--- /dev/null
+++ b/src/python/gudhi/representations/vector_methods.py
@@ -0,0 +1,485 @@
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Mathieu Carrière
+#
+# Copyright (C) 2018-2019 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
+
+import numpy as np
+from sklearn.base import BaseEstimator, TransformerMixin
+from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler
+from sklearn.neighbors import DistanceMetric
+
+from .preprocessing import DiagramScaler, BirthPersistenceTransform
+
+#############################################
+# Finite Vectorization methods ##############
+#############################################
+
+class PersistenceImage(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing persistence images from a list of persistence diagrams. A persistence image is a 2D function computed from a persistence diagram by convolving the diagram points with a weighted Gaussian kernel. The plane is then discretized into an image with pixels, which is flattened and returned as a vector. See http://jmlr.org/papers/v18/16-337.html for more details.
+ """
+ def __init__(self, bandwidth=1., weight=lambda x: 1, resolution=[20,20], im_range=[np.nan, np.nan, np.nan, np.nan]):
+ """
+ Constructor for the PersistenceImage class.
+
+ Parameters:
+ bandwidth (double): bandwidth of the Gaussian kernel (default 1.).
+ weight (function): weight function for the persistence diagram points (default constant function, ie lambda x: 1). This function must be defined on 2D points, ie lists or numpy arrays of the form [p_x,p_y].
+ resolution ([int,int]): size (in pixels) of the persistence image (default [20,20]).
+ im_range ([double,double,double,double]): minimum and maximum of each axis of the persistence image, of the form [x_min, x_max, y_min, y_max] (default [numpy.nan, numpy.nan, numpy.nan, numpyp.nan]). If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method.
+ """
+ self.bandwidth, self.weight = bandwidth, weight
+ self.resolution, self.im_range = resolution, im_range
+
+ def fit(self, X, y=None):
+ """
+ Fit the PersistenceImage class on a list of persistence diagrams: if any of the values in **im_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ if np.isnan(np.array(self.im_range)).any():
+ new_X = BirthPersistenceTransform().fit_transform(X)
+ pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(new_X,y)
+ [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]]
+ self.im_range = np.where(np.isnan(np.array(self.im_range)), np.array([mx, Mx, my, My]), np.array(self.im_range))
+ return self
+
+ def transform(self, X):
+ """
+ Compute the persistence image for each persistence diagram individually and store the results in a single numpy array.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array with shape (number of diagrams) x (number of pixels = **resolution[0]** x **resolution[1]**): output persistence images.
+ """
+ num_diag, Xfit = len(X), []
+ new_X = BirthPersistenceTransform().fit_transform(X)
+
+ for i in range(num_diag):
+
+ diagram, num_pts_in_diag = new_X[i], X[i].shape[0]
+
+ w = np.empty(num_pts_in_diag)
+ for j in range(num_pts_in_diag):
+ w[j] = self.weight(diagram[j,:])
+
+ x_values, y_values = np.linspace(self.im_range[0], self.im_range[1], self.resolution[0]), np.linspace(self.im_range[2], self.im_range[3], self.resolution[1])
+ Xs, Ys = np.tile((diagram[:,0][:,np.newaxis,np.newaxis]-x_values[np.newaxis,np.newaxis,:]),[1,self.resolution[1],1]), np.tile(diagram[:,1][:,np.newaxis,np.newaxis]-y_values[np.newaxis,:,np.newaxis],[1,1,self.resolution[0]])
+ image = np.tensordot(w, np.exp((-np.square(Xs)-np.square(Ys))/(2*np.square(self.bandwidth)))/(np.square(self.bandwidth)*2*np.pi), 1)
+
+ Xfit.append(image.flatten()[np.newaxis,:])
+
+ Xfit = np.concatenate(Xfit,0)
+
+ return Xfit
+
+class Landscape(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing persistence landscapes from a list of persistence diagrams. A persistence landscape is a collection of 1D piecewise-linear functions computed from the rank function associated to the persistence diagram. These piecewise-linear functions are then sampled uniformly on a given range and the corresponding vectors of samples are concatenated and returned. See http://jmlr.org/papers/v16/bubenik15a.html for more details.
+ """
+ def __init__(self, num_landscapes=5, resolution=100, sample_range=[np.nan, np.nan]):
+ """
+ Constructor for the Landscape class.
+
+ Parameters:
+ num_landscapes (int): number of piecewise-linear functions to output (default 5).
+ resolution (int): number of sample for all piecewise-linear functions (default 100).
+ sample_range ([double, double]): minimum and maximum of all piecewise-linear function domains, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn uniformly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method.
+ """
+ self.num_landscapes, self.resolution, self.sample_range = num_landscapes, resolution, sample_range
+
+ def fit(self, X, y=None):
+ """
+ Fit the Landscape class on a list of persistence diagrams: if any of the values in **sample_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ if np.isnan(np.array(self.sample_range)).any():
+ pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y)
+ [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]]
+ self.sample_range = np.where(np.isnan(np.array(self.sample_range)), np.array([mx, My]), np.array(self.sample_range))
+ return self
+
+ def transform(self, X):
+ """
+ Compute the persistence landscape for each persistence diagram individually and concatenate the results.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array with shape (number of diagrams) x (number of samples = **num_landscapes** x **resolution**): output persistence landscapes.
+ """
+ num_diag, Xfit = len(X), []
+ x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution)
+ step_x = x_values[1] - x_values[0]
+
+ for i in range(num_diag):
+
+ diagram, num_pts_in_diag = X[i], X[i].shape[0]
+
+ ls = np.zeros([self.num_landscapes, self.resolution])
+
+ events = []
+ for j in range(self.resolution):
+ events.append([])
+
+ for j in range(num_pts_in_diag):
+ [px,py] = diagram[j,:2]
+ min_idx = np.minimum(np.maximum(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ mid_idx = np.minimum(np.maximum(np.ceil((0.5*(py+px) - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ max_idx = np.minimum(np.maximum(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+
+ if min_idx < self.resolution and max_idx > 0:
+
+ landscape_value = self.sample_range[0] + min_idx * step_x - px
+ for k in range(min_idx, mid_idx):
+ events[k].append(landscape_value)
+ landscape_value += step_x
+
+ landscape_value = py - self.sample_range[0] - mid_idx * step_x
+ for k in range(mid_idx, max_idx):
+ events[k].append(landscape_value)
+ landscape_value -= step_x
+
+ for j in range(self.resolution):
+ events[j].sort(reverse=True)
+ for k in range( min(self.num_landscapes, len(events[j])) ):
+ ls[k,j] = events[j][k]
+
+ Xfit.append(np.sqrt(2)*np.reshape(ls,[1,-1]))
+
+ Xfit = np.concatenate(Xfit,0)
+
+ return Xfit
+
+class Silhouette(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing persistence silhouettes from a list of persistence diagrams. A persistence silhouette is computed by taking a weighted average of the collection of 1D piecewise-linear functions given by the persistence landscapes, and then by uniformly sampling this average on a given range. Finally, the corresponding vector of samples is returned. See https://arxiv.org/abs/1312.0308 for more details.
+ """
+ def __init__(self, weight=lambda x: 1, resolution=100, sample_range=[np.nan, np.nan]):
+ """
+ Constructor for the Silhouette class.
+
+ Parameters:
+ weight (function): weight function for the persistence diagram points (default constant function, ie lambda x: 1). This function must be defined on 2D points, ie on lists or numpy arrays of the form [p_x,p_y].
+ resolution (int): number of samples for the weighted average (default 100).
+ sample_range ([double, double]): minimum and maximum for the weighted average domain, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn uniformly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method.
+ """
+ self.weight, self.resolution, self.sample_range = weight, resolution, sample_range
+
+ def fit(self, X, y=None):
+ """
+ Fit the Silhouette class on a list of persistence diagrams: if any of the values in **sample_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ if np.isnan(np.array(self.sample_range)).any():
+ pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y)
+ [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]]
+ self.sample_range = np.where(np.isnan(np.array(self.sample_range)), np.array([mx, My]), np.array(self.sample_range))
+ return self
+
+ def transform(self, X):
+ """
+ Compute the persistence silhouette for each persistence diagram individually and concatenate the results.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array with shape (number of diagrams) x (**resolution**): output persistence silhouettes.
+ """
+ num_diag, Xfit = len(X), []
+ x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution)
+ step_x = x_values[1] - x_values[0]
+
+ for i in range(num_diag):
+
+ diagram, num_pts_in_diag = X[i], X[i].shape[0]
+
+ sh, weights = np.zeros(self.resolution), np.zeros(num_pts_in_diag)
+ for j in range(num_pts_in_diag):
+ weights[j] = self.weight(diagram[j,:])
+ total_weight = np.sum(weights)
+
+ for j in range(num_pts_in_diag):
+
+ [px,py] = diagram[j,:2]
+ weight = weights[j] / total_weight
+ min_idx = np.minimum(np.maximum(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ mid_idx = np.minimum(np.maximum(np.ceil((0.5*(py+px) - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ max_idx = np.minimum(np.maximum(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+
+ if min_idx < self.resolution and max_idx > 0:
+
+ silhouette_value = self.sample_range[0] + min_idx * step_x - px
+ for k in range(min_idx, mid_idx):
+ sh[k] += weight * silhouette_value
+ silhouette_value += step_x
+
+ silhouette_value = py - self.sample_range[0] - mid_idx * step_x
+ for k in range(mid_idx, max_idx):
+ sh[k] += weight * silhouette_value
+ silhouette_value -= step_x
+
+ Xfit.append(np.reshape(np.sqrt(2) * sh, [1,-1]))
+
+ Xfit = np.concatenate(Xfit, 0)
+
+ return Xfit
+
+class BettiCurve(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing Betti curves from a list of persistence diagrams. A Betti curve is a 1D piecewise-constant function obtained from the rank function. It is sampled uniformly on a given range and the vector of samples is returned. See https://www.researchgate.net/publication/316604237_Time_Series_Classification_via_Topological_Data_Analysis for more details.
+ """
+ def __init__(self, resolution=100, sample_range=[np.nan, np.nan]):
+ """
+ Constructor for the BettiCurve class.
+
+ Parameters:
+ resolution (int): number of sample for the piecewise-constant function (default 100).
+ sample_range ([double, double]): minimum and maximum of the piecewise-constant function domain, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn uniformly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method.
+ """
+ self.resolution, self.sample_range = resolution, sample_range
+
+ def fit(self, X, y=None):
+ """
+ Fit the BettiCurve class on a list of persistence diagrams: if any of the values in **sample_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ if np.isnan(np.array(self.sample_range)).any():
+ pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y)
+ [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]]
+ self.sample_range = np.where(np.isnan(np.array(self.sample_range)), np.array([mx, My]), np.array(self.sample_range))
+ return self
+
+ def transform(self, X):
+ """
+ Compute the Betti curve for each persistence diagram individually and concatenate the results.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array with shape (number of diagrams) x (**resolution**): output Betti curves.
+ """
+ num_diag, Xfit = len(X), []
+ x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution)
+ step_x = x_values[1] - x_values[0]
+
+ for i in range(num_diag):
+
+ diagram, num_pts_in_diag = X[i], X[i].shape[0]
+
+ bc = np.zeros(self.resolution)
+ for j in range(num_pts_in_diag):
+ [px,py] = diagram[j,:2]
+ min_idx = np.minimum(np.maximum(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ max_idx = np.minimum(np.maximum(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ for k in range(min_idx, max_idx):
+ bc[k] += 1
+
+ Xfit.append(np.reshape(bc,[1,-1]))
+
+ Xfit = np.concatenate(Xfit, 0)
+
+ return Xfit
+
+class Entropy(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing persistence entropy. Persistence entropy is a statistic for persistence diagrams inspired from Shannon entropy. This statistic can also be used to compute a feature vector, called the entropy summary function. See https://arxiv.org/pdf/1803.08304.pdf for more details. Note that a previous implementation was contributed by Manuel Soriano-Trigueros.
+ """
+ def __init__(self, mode="scalar", normalized=True, resolution=100, sample_range=[np.nan, np.nan]):
+ """
+ Constructor for the Entropy class.
+
+ Parameters:
+ mode (string): what entropy to compute: either "scalar" for computing the entropy statistics, or "vector" for computing the entropy summary functions (default "scalar").
+ normalized (bool): whether to normalize the entropy summary function (default True). Used only if **mode** = "vector".
+ resolution (int): number of sample for the entropy summary function (default 100). Used only if **mode** = "vector".
+ sample_range ([double, double]): minimum and maximum of the entropy summary function domain, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn uniformly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method. Used only if **mode** = "vector".
+ """
+ self.mode, self.normalized, self.resolution, self.sample_range = mode, normalized, resolution, sample_range
+
+ def fit(self, X, y=None):
+ """
+ Fit the Entropy class on a list of persistence diagrams.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ if np.isnan(np.array(self.sample_range)).any():
+ pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y)
+ [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]]
+ self.sample_range = np.where(np.isnan(np.array(self.sample_range)), np.array([mx, My]), np.array(self.sample_range))
+ return self
+
+ def transform(self, X):
+ """
+ Compute the entropy for each persistence diagram individually and concatenate the results.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array with shape (number of diagrams) x (1 if **mode** = "scalar" else **resolution**): output entropy.
+ """
+ num_diag, Xfit = len(X), []
+ x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution)
+ step_x = x_values[1] - x_values[0]
+ new_X = BirthPersistenceTransform().fit_transform(X)
+
+ for i in range(num_diag):
+
+ orig_diagram, diagram, num_pts_in_diag = X[i], new_X[i], X[i].shape[0]
+ new_diagram = DiagramScaler(use=True, scalers=[([1], MaxAbsScaler())]).fit_transform([diagram])[0]
+
+ if self.mode == "scalar":
+ ent = - np.sum( np.multiply(new_diagram[:,1], np.log(new_diagram[:,1])) )
+ Xfit.append(np.array([[ent]]))
+
+ else:
+ ent = np.zeros(self.resolution)
+ for j in range(num_pts_in_diag):
+ [px,py] = orig_diagram[j,:2]
+ min_idx = np.minimum(np.maximum(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ max_idx = np.minimum(np.maximum(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)
+ for k in range(min_idx, max_idx):
+ ent[k] += (-1) * new_diagram[j,1] * np.log(new_diagram[j,1])
+ if self.normalized:
+ ent = ent / np.linalg.norm(ent, ord=1)
+ Xfit.append(np.reshape(ent,[1,-1]))
+
+ Xfit = np.concatenate(Xfit, 0)
+
+ return Xfit
+
+class TopologicalVector(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing topological vectors from a list of persistence diagrams. The topological vector associated to a persistence diagram is the sorted vector of a slight modification of the pairwise distances between the persistence diagram points. See https://diglib.eg.org/handle/10.1111/cgf12692 for more details.
+ """
+ def __init__(self, threshold=10):
+ """
+ Constructor for the TopologicalVector class.
+
+ Parameters:
+ threshold (int): number of distances to keep (default 10). This is the dimension of the topological vector. If -1, this threshold is computed from the list of persistence diagrams by considering the one with the largest number of points and using the dimension of its corresponding topological vector as threshold.
+ """
+ self.threshold = threshold
+
+ def fit(self, X, y=None):
+ """
+ Fit the TopologicalVector class on a list of persistence diagrams (this function actually does nothing but is useful when TopologicalVector is included in a scikit-learn Pipeline).
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ return self
+
+ def transform(self, X):
+ """
+ Compute the topological vector for each persistence diagram individually and concatenate the results.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array with shape (number of diagrams) x (**threshold**): output topological vectors.
+ """
+ if self.threshold == -1:
+ thresh = np.array([X[i].shape[0] for i in range(len(X))]).max()
+ else:
+ thresh = self.threshold
+
+ num_diag = len(X)
+ Xfit = np.zeros([num_diag, thresh])
+
+ for i in range(num_diag):
+
+ diagram, num_pts_in_diag = X[i], X[i].shape[0]
+ pers = 0.5 * (diagram[:,1]-diagram[:,0])
+ min_pers = np.minimum(pers,np.transpose(pers))
+ distances = DistanceMetric.get_metric("chebyshev").pairwise(diagram)
+ vect = np.flip(np.sort(np.triu(np.minimum(distances, min_pers)), axis=None), 0)
+ dim = min(len(vect), thresh)
+ Xfit[i, :dim] = vect[:dim]
+
+ return Xfit
+
+class ComplexPolynomial(BaseEstimator, TransformerMixin):
+ """
+ This is a class for computing complex polynomials from a list of persistence diagrams. The persistence diagram points are seen as the roots of some complex polynomial, whose coefficients are returned in a complex vector. See https://link.springer.com/chapter/10.1007%2F978-3-319-23231-7_27 for more details.
+ """
+ def __init__(self, polynomial_type="R", threshold=10):
+ """
+ Constructor for the ComplexPolynomial class.
+
+ Parameters:
+ polynomial_type (char): either "R", "S" or "T" (default "R"). Type of complex polynomial that is going to be computed (explained in https://link.springer.com/chapter/10.1007%2F978-3-319-23231-7_27).
+ threshold (int): number of coefficients (default 10). This is the dimension of the complex vector of coefficients, i.e. the number of coefficients corresponding to the largest degree terms of the polynomial. If -1, this threshold is computed from the list of persistence diagrams by considering the one with the largest number of points and using the dimension of its corresponding complex vector of coefficients as threshold.
+ """
+ self.threshold, self.polynomial_type = threshold, polynomial_type
+
+ def fit(self, X, y=None):
+ """
+ Fit the ComplexPolynomial class on a list of persistence diagrams (this function actually does nothing but is useful when ComplexPolynomial is included in a scikit-learn Pipeline).
+
+ Parameters:
+ X (list of n x 2 or n x 1 numpy arrays): input persistence diagrams.
+ y (n x 1 array): persistence diagram labels (unused).
+ """
+ return self
+
+ def transform(self, X):
+ """
+ Compute the complex vector of coefficients for each persistence diagram individually and concatenate the results.
+
+ Parameters:
+ X (list of n x 2 numpy arrays): input persistence diagrams.
+
+ Returns:
+ numpy array with shape (number of diagrams) x (**threshold**): output complex vectors of coefficients.
+ """
+ if self.threshold == -1:
+ thresh = np.array([X[i].shape[0] for i in range(len(X))]).max()
+ else:
+ thresh = self.threshold
+
+ Xfit = np.zeros([len(X), thresh]) + 1j * np.zeros([len(X), thresh])
+ for d in range(len(X)):
+ D, N = X[d], X[d].shape[0]
+ if self.polynomial_type == "R":
+ roots = D[:,0] + 1j * D[:,1]
+ elif self.polynomial_type == "S":
+ alpha = np.linalg.norm(D, axis=1)
+ alpha = np.where(alpha==0, np.ones(N), alpha)
+ roots = np.multiply( np.multiply( (D[:,0]+1j*D[:,1]), (D[:,1]-D[:,0]) ), 1./(np.sqrt(2)*alpha) )
+ elif self.polynomial_type == "T":
+ alpha = np.linalg.norm(D, axis=1)
+ roots = np.multiply( (D[:,1]-D[:,0])/2, np.cos(alpha) - np.sin(alpha) + 1j * (np.cos(alpha) + np.sin(alpha)) )
+ coeff = [0] * (N+1)
+ coeff[N] = 1
+ for i in range(1, N+1):
+ for j in range(N-i-1, N):
+ coeff[j] += ((-1) * roots[i-1] * coeff[j+1])
+ coeff = np.array(coeff[::-1])[1:]
+ Xfit[d, :min(thresh, coeff.shape[0])] = coeff[:min(thresh, coeff.shape[0])]
+ return Xfit
diff --git a/src/python/gudhi/rips_complex.pyx b/src/python/gudhi/rips_complex.pyx
index f2cd6a8d..cbbbab0d 100644
--- a/src/python/gudhi/rips_complex.pyx
+++ b/src/python/gudhi/rips_complex.pyx
@@ -8,15 +8,14 @@ from libc.stdint cimport intptr_t
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
diff --git a/src/python/gudhi/simplex_tree.pyx b/src/python/gudhi/simplex_tree.pyx
index 9f490271..4a3cd9bc 100644
--- a/src/python/gudhi/simplex_tree.pyx
+++ b/src/python/gudhi/simplex_tree.pyx
@@ -2,15 +2,14 @@ from libc.stdint cimport intptr_t
from numpy import array as np_array
cimport simplex_tree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -75,13 +74,22 @@ cdef class SimplexTree:
return self.get_ptr().simplex_filtration(simplex)
def assign_filtration(self, simplex, filtration):
- """This function assigns the simplicial complex filtration value for a
+ """This function assigns a new filtration value to a
given N-simplex.
:param simplex: The N-simplex, represented by a list of vertex.
:type simplex: list of int.
- :param filtration: The simplicial complex filtration value.
+ :param filtration: The new filtration value.
:type filtration: float
+
+ .. note::
+ Beware that after this operation, the structure may not be a valid
+ filtration anymore, a simplex could have a lower filtration value
+ than one of its faces. Callers are responsible for fixing this
+ (with more :meth:`assign_filtration` or
+ :meth:`make_filtration_non_decreasing` for instance) before calling
+ any function that relies on the filtration property, like
+ :meth:`initialize_filtration`.
"""
self.get_ptr().assign_simplex_filtration(simplex, filtration)
@@ -362,7 +370,7 @@ cdef class SimplexTree:
value than its faces by increasing the filtration values.
:returns: True if any filtration value was modified,
- False if the filtration was already non-decreasing.
+ False if the filtration was already non-decreasing.
:rtype: bool
diff --git a/src/python/gudhi/strong_witness_complex.pyx b/src/python/gudhi/strong_witness_complex.pyx
index e757abea..66d49b49 100644
--- a/src/python/gudhi/strong_witness_complex.pyx
+++ b/src/python/gudhi/strong_witness_complex.pyx
@@ -6,15 +6,14 @@ from libc.stdint cimport intptr_t
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -69,7 +68,7 @@ cdef class StrongWitnessComplex:
"""
stree = SimplexTree()
cdef intptr_t stree_int_ptr=stree.thisptr
- if limit_dimension is not -1:
+ if limit_dimension != -1:
self.thisptr.create_simplex_tree(<Simplex_tree_interface_full_featured*>stree_int_ptr,
max_alpha_square, limit_dimension)
else:
diff --git a/src/python/gudhi/subsampling.pyx b/src/python/gudhi/subsampling.pyx
index 1135c1fb..e0cd1348 100644
--- a/src/python/gudhi/subsampling.pyx
+++ b/src/python/gudhi/subsampling.pyx
@@ -4,15 +4,14 @@ from libcpp.string cimport string
from libcpp cimport bool
import os
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -44,15 +43,15 @@ def choose_n_farthest_points(points=None, off_file='', nb_points=0, starting_poi
:param nb_points: Number of points of the subsample.
:type nb_points: unsigned.
:param starting_point: The iteration starts with the landmark `starting \
- point`,which is the index of the poit to start with. If not set, this \
- index is choosen randomly.
+ point`,which is the index of the point to start with. If not set, this \
+ index is chosen randomly.
:type starting_point: unsigned.
:returns: The subsample point set.
:rtype: vector[vector[double]]
"""
- if off_file is not '':
+ if off_file:
if os.path.isfile(off_file):
- if starting_point is '':
+ if starting_point == '':
return subsampling_n_farthest_points_from_file(str.encode(off_file),
nb_points)
else:
@@ -65,7 +64,7 @@ def choose_n_farthest_points(points=None, off_file='', nb_points=0, starting_poi
if points is None:
# Empty points
points=[]
- if starting_point is '':
+ if starting_point == '':
return subsampling_n_farthest_points(points, nb_points)
else:
return subsampling_n_farthest_points(points, nb_points,
@@ -87,7 +86,7 @@ def pick_n_random_points(points=None, off_file='', nb_points=0):
:returns: The subsample point set.
:rtype: vector[vector[double]]
"""
- if off_file is not '':
+ if off_file:
if os.path.isfile(off_file):
return subsampling_n_random_points_from_file(str.encode(off_file),
nb_points)
@@ -117,7 +116,7 @@ def sparsify_point_set(points=None, off_file='', min_squared_dist=0.0):
:returns: The subsample point set.
:rtype: vector[vector[double]]
"""
- if off_file is not '':
+ if off_file:
if os.path.isfile(off_file):
return subsampling_sparsify_points_from_file(str.encode(off_file),
min_squared_dist)
diff --git a/src/python/gudhi/tangential_complex.pyx b/src/python/gudhi/tangential_complex.pyx
index 3a945fe2..b7678f4d 100644
--- a/src/python/gudhi/tangential_complex.pyx
+++ b/src/python/gudhi/tangential_complex.pyx
@@ -9,15 +9,14 @@ import os
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -65,7 +64,7 @@ cdef class TangentialComplex:
# The real cython constructor
def __cinit__(self, intrisic_dim, points=None, off_file=''):
- if off_file is not '':
+ if off_file:
if os.path.isfile(off_file):
self.thisptr = new Tangential_complex_interface(intrisic_dim, str.encode(off_file), True)
else:
diff --git a/src/python/gudhi/wasserstein.py b/src/python/gudhi/wasserstein.py
new file mode 100644
index 00000000..d8a3104c
--- /dev/null
+++ b/src/python/gudhi/wasserstein.py
@@ -0,0 +1,98 @@
+import numpy as np
+import scipy.spatial.distance as sc
+try:
+ import ot
+except ImportError:
+ print("POT (Python Optimal Transport) package is not installed. Try to run $ conda install -c conda-forge pot ; or $ pip install POT")
+
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Theo Lacombe
+#
+# Copyright (C) 2019 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
+
+def _proj_on_diag(X):
+ '''
+ :param X: (n x 2) array encoding the points of a persistent diagram.
+ :returns: (n x 2) array encoding the (respective orthogonal) projections of the points onto the diagonal
+ '''
+ Z = (X[:,0] + X[:,1]) / 2.
+ return np.array([Z , Z]).T
+
+
+def _build_dist_matrix(X, Y, p=2., q=2.):
+ '''
+ :param X: (n x 2) numpy.array encoding the (points of the) first diagram.
+ :param Y: (m x 2) numpy.array encoding the second diagram.
+ :param q: Ground metric (i.e. norm l_q).
+ :param p: exponent for the Wasserstein metric.
+ :returns: (n+1) x (m+1) np.array encoding the cost matrix C.
+ For 1 <= i <= n, 1 <= j <= m, C[i,j] encodes the distance between X[i] and Y[j], while C[i, m+1] (resp. C[n+1, j]) encodes the distance (to the p) between X[i] (resp Y[j]) and its orthogonal proj onto the diagonal.
+ note also that C[n+1, m+1] = 0 (it costs nothing to move from the diagonal to the diagonal).
+ '''
+ Xdiag = _proj_on_diag(X)
+ Ydiag = _proj_on_diag(Y)
+ if np.isinf(q):
+ C = sc.cdist(X,Y, metric='chebyshev')**p
+ Cxd = np.linalg.norm(X - Xdiag, ord=q, axis=1)**p
+ Cdy = np.linalg.norm(Y - Ydiag, ord=q, axis=1)**p
+ else:
+ C = sc.cdist(X,Y, metric='minkowski', p=q)**p
+ Cxd = np.linalg.norm(X - Xdiag, ord=q, axis=1)**p
+ Cdy = np.linalg.norm(Y - Ydiag, ord=q, axis=1)**p
+ Cf = np.hstack((C, Cxd[:,None]))
+ Cdy = np.append(Cdy, 0)
+
+ Cf = np.vstack((Cf, Cdy[None,:]))
+
+ return Cf
+
+
+def _perstot(X, p, q):
+ '''
+ :param X: (n x 2) numpy.array (points of a given diagram).
+ :param q: Ground metric on the (upper-half) plane (i.e. norm l_q in R^2); Default value is 2 (Euclidean norm).
+ :param p: exponent for Wasserstein; Default value is 2.
+ :returns: float, the total persistence of the diagram (that is, its distance to the empty diagram).
+ '''
+ Xdiag = _proj_on_diag(X)
+ return (np.sum(np.linalg.norm(X - Xdiag, ord=q, axis=1)**p))**(1./p)
+
+
+def wasserstein_distance(X, Y, p=2., q=2.):
+ '''
+ :param X: (n x 2) numpy.array encoding the (finite points of the) first diagram. Must not contain essential points (i.e. with infinite coordinate).
+ :param Y: (m x 2) numpy.array encoding the second diagram.
+ :param q: Ground metric on the (upper-half) plane (i.e. norm l_q in R^2); Default value is 2 (euclidean norm).
+ :param p: exponent for Wasserstein; Default value is 2.
+ :returns: the p-Wasserstein distance (1 <= p < infinity) with respect to the q-norm as ground metric.
+ :rtype: float
+ '''
+ n = len(X)
+ m = len(Y)
+
+ # handle empty diagrams
+ if X.size == 0:
+ if Y.size == 0:
+ return 0.
+ else:
+ return _perstot(Y, p, q)
+ elif Y.size == 0:
+ return _perstot(X, p, q)
+
+ M = _build_dist_matrix(X, Y, p=p, q=q)
+ a = np.full(n+1, 1. / (n + m) ) # weight vector of the input diagram. Uniform here.
+ a[-1] = a[-1] * m # normalized so that we have a probability measure, required by POT
+ b = np.full(m+1, 1. / (n + m) ) # weight vector of the input diagram. Uniform here.
+ b[-1] = b[-1] * n # so that we have a probability measure, required by POT
+
+ # Comptuation of the otcost using the ot.emd2 library.
+ # Note: it is the squared Wasserstein distance.
+ # The default numItermax=100000 is not sufficient for some examples with 5000 points, what is a good value?
+ ot_cost = (n+m) * ot.emd2(a, b, M, numItermax=2000000)
+
+ return ot_cost ** (1./p)
+
diff --git a/src/python/gudhi/witness_complex.pyx b/src/python/gudhi/witness_complex.pyx
index baa70b7a..153fc615 100644
--- a/src/python/gudhi/witness_complex.pyx
+++ b/src/python/gudhi/witness_complex.pyx
@@ -6,15 +6,14 @@ from libc.stdint cimport intptr_t
from gudhi.simplex_tree cimport *
from gudhi.simplex_tree import SimplexTree
-""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
- See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
- Author(s): Vincent Rouvreau
-
- Copyright (C) 2016 Inria
-
- Modification(s):
- - YYYY/MM Author: Description of the modification
-"""
+# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+# See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+# Author(s): Vincent Rouvreau
+#
+# Copyright (C) 2016 Inria
+#
+# Modification(s):
+# - YYYY/MM Author: Description of the modification
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
@@ -69,7 +68,7 @@ cdef class WitnessComplex:
"""
stree = SimplexTree()
cdef intptr_t stree_int_ptr=stree.thisptr
- if limit_dimension is not -1:
+ if limit_dimension != -1:
self.thisptr.create_simplex_tree(<Simplex_tree_interface_full_featured*>stree_int_ptr,
max_alpha_square, limit_dimension)
else:
diff --git a/src/python/include/Alpha_complex_interface.h b/src/python/include/Alpha_complex_interface.h
index b3553d32..96353cc4 100644
--- a/src/python/include/Alpha_complex_interface.h
+++ b/src/python/include/Alpha_complex_interface.h
@@ -15,6 +15,8 @@
#include <gudhi/Alpha_complex.h>
#include <CGAL/Epick_d.h>
+#include <boost/range/adaptor/transformed.hpp>
+
#include "Simplex_tree_interface.h"
#include <iostream>
@@ -31,7 +33,10 @@ class Alpha_complex_interface {
public:
Alpha_complex_interface(const std::vector<std::vector<double>>& points) {
- alpha_complex_ = new Alpha_complex<Dynamic_kernel>(points);
+ auto mkpt = [](std::vector<double> const& vec){
+ return Point_d(vec.size(), vec.begin(), vec.end());
+ };
+ alpha_complex_ = new Alpha_complex<Dynamic_kernel>(boost::adaptors::transform(points, mkpt));
}
Alpha_complex_interface(const std::string& off_file_name, bool from_file = true) {
@@ -45,9 +50,9 @@ class Alpha_complex_interface {
std::vector<double> get_point(int vh) {
std::vector<double> vd;
try {
- Point_d ph = alpha_complex_->get_point(vh);
+ Point_d const& ph = alpha_complex_->get_point(vh);
for (auto coord = ph.cartesian_begin(); coord < ph.cartesian_end(); coord++)
- vd.push_back(*coord);
+ vd.push_back(CGAL::to_double(*coord));
} catch (std::out_of_range const&) {
// std::out_of_range is thrown in case not found. Other exceptions must be re-thrown
}
diff --git a/src/python/test/test_representations.py b/src/python/test/test_representations.py
new file mode 100755
index 00000000..4ff65f98
--- /dev/null
+++ b/src/python/test/test_representations.py
@@ -0,0 +1,11 @@
+import os
+import sys
+import matplotlib.pyplot as plt
+# Disable graphics for testing purposes
+plt.show = lambda:None
+here = os.path.dirname(os.path.realpath(__file__))
+sys.path.append(here + "/../example")
+import diagram_vectorizations_distances_kernels
+# pytest is unhappy if there are 0 tests
+def test_nothing():
+ return None
diff --git a/src/python/test/test_wasserstein_distance.py b/src/python/test/test_wasserstein_distance.py
new file mode 100755
index 00000000..a6bf9901
--- /dev/null
+++ b/src/python/test/test_wasserstein_distance.py
@@ -0,0 +1,48 @@
+from gudhi.wasserstein import wasserstein_distance
+import numpy as np
+
+""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
+ See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
+ Author(s): Theo Lacombe
+
+ Copyright (C) 2019 Inria
+
+ Modification(s):
+ - YYYY/MM Author: Description of the modification
+"""
+
+__author__ = "Theo Lacombe"
+__copyright__ = "Copyright (C) 2019 Inria"
+__license__ = "MIT"
+
+
+def test_basic_wasserstein():
+ diag1 = np.array([[2.7, 3.7], [9.6, 14.0], [34.2, 34.974]])
+ diag2 = np.array([[2.8, 4.45], [9.5, 14.1]])
+ diag3 = np.array([[0, 2], [4, 6]])
+ diag4 = np.array([[0, 3], [4, 8]])
+ emptydiag = np.array([[]])
+
+ assert wasserstein_distance(emptydiag, emptydiag, q=2., p=1.) == 0.
+ assert wasserstein_distance(emptydiag, emptydiag, q=np.inf, p=1.) == 0.
+ assert wasserstein_distance(emptydiag, emptydiag, q=np.inf, p=2.) == 0.
+ assert wasserstein_distance(emptydiag, emptydiag, q=2., p=2.) == 0.
+
+ assert wasserstein_distance(diag3, emptydiag, q=np.inf, p=1.) == 2.
+ assert wasserstein_distance(diag3, emptydiag, q=1., p=1.) == 4.
+
+ assert wasserstein_distance(diag4, emptydiag, q=1., p=2.) == 5. # thank you Pythagorician triplets
+ assert wasserstein_distance(diag4, emptydiag, q=np.inf, p=2.) == 2.5
+ assert wasserstein_distance(diag4, emptydiag, q=2., p=2.) == 3.5355339059327378
+
+ assert wasserstein_distance(diag1, diag2, q=2., p=1.) == 1.4453593023967701
+ assert wasserstein_distance(diag1, diag2, q=2.35, p=1.74) == 0.9772734057168739
+
+ assert wasserstein_distance(diag1, emptydiag, q=2.35, p=1.7863) == 3.141592214572228
+
+ assert wasserstein_distance(diag3, diag4, q=1., p=1.) == 3.
+ assert wasserstein_distance(diag3, diag4, q=np.inf, p=1.) == 3. # no diag matching here
+ assert wasserstein_distance(diag3, diag4, q=np.inf, p=2.) == np.sqrt(5)
+ assert wasserstein_distance(diag3, diag4, q=1., p=2.) == np.sqrt(5)
+ assert wasserstein_distance(diag3, diag4, q=4.5, p=2.) == np.sqrt(5)
+