diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/CMakeLists.txt | 1 | ||||
-rw-r--r-- | src/Collapse/doc/intro_edge_collapse.h | 101 | ||||
-rw-r--r-- | src/Collapse/example/CMakeLists.txt | 10 | ||||
-rw-r--r-- | src/Collapse/example/edge_collapse_basic_example.cpp | 45 | ||||
-rw-r--r-- | src/Collapse/example/edge_collapse_example_basic.txt | 5 | ||||
-rw-r--r-- | src/Collapse/include/gudhi/Flag_complex_sparse_matrix.h | 424 | ||||
-rw-r--r-- | src/Collapse/test/CMakeLists.txt | 9 | ||||
-rw-r--r-- | src/Collapse/test/collapse_unit_test.cpp | 191 | ||||
-rw-r--r-- | src/Collapse/utilities/CMakeLists.txt | 33 | ||||
-rw-r--r-- | src/Collapse/utilities/collapse.md | 63 | ||||
-rw-r--r-- | src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp | 177 | ||||
-rw-r--r-- | src/Collapse/utilities/point_cloud_edge_collapse_rips_persistence.cpp | 165 | ||||
-rw-r--r-- | src/common/doc/main_page.md | 30 |
13 files changed, 1254 insertions, 0 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 561aa049..9e4d78ac 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -26,6 +26,7 @@ add_gudhi_module(Bitmap_cubical_complex) add_gudhi_module(Bottleneck_distance) add_gudhi_module(Cech_complex) add_gudhi_module(Contraction) +add_gudhi_module(Collapse) add_gudhi_module(Hasse_complex) add_gudhi_module(Persistence_representations) add_gudhi_module(Persistent_cohomology) diff --git a/src/Collapse/doc/intro_edge_collapse.h b/src/Collapse/doc/intro_edge_collapse.h new file mode 100644 index 00000000..0691ccf6 --- /dev/null +++ b/src/Collapse/doc/intro_edge_collapse.h @@ -0,0 +1,101 @@ +/* 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): Siddharth Pritam + * + * Copyright (C) 2019 Inria + * + * Modification(s): + * - YYYY/MM Author: Description of the modification + */ + +#ifndef DOC_EDGE_COLLAPSE_INTRO_EDGE_COLLAPSE_H_ +#define DOC_EDGE_COLLAPSE_INTRO_EDGE_COLLAPSE_H_ + +namespace Gudhi { + +namespace collapse { + +/** \defgroup edge_collapse Edge collapse + * + * \author Siddharth Pritam + * + * @{ + * + * \section edge_collapse_definition Edge collapse definition + * + * An edge \f$e\f$ in a simplicial complex \f$K\f$ is called a <b>dominated edge</b> if the link of \f$e\f$ in + * \f$K\f$, \f$lk_K(e)\f$ is a simplicial cone, that is, there exists a vertex \f$v^{\prime} \notin e\f$ and a + * subcomplex \f$L\f$ in \f$K\f$, such that \f$lk_K(e) = v^{\prime}L\f$. We say that the vertex \f$v^{\prime}\f$ is + * {dominating} \f$e\f$ and \f$e\f$ is {dominated} by \f$v^{\prime}\f$. + * An <b> elementary egde collapse </b> is the removal of a dominated edge \f$e\f$ from \f$K\f$, + * which we denote with \f$K\f$ \f${\searrow\searrow}^1 \f$ \f$K\setminus e\f$. + * The symbol \f$\mathbf{K\setminus e}\f$ (deletion of \f$e\f$ from \f$K\f$) refers to the subcomplex of \f$K\f$ which + * has all simplices of \f$K\f$ except \f$e\f$ and the ones containing \f$e\f$. + * There is an <b>edge collapse</b> from a simplicial complex \f$K\f$ to its subcomplex \f$L\f$, + * if there exists a series of elementary edge collapses from \f$K\f$ to \f$L\f$, denoted as \f$K\f$ + * \f${\searrow\searrow}\f$ \f$L\f$. + * + * An edge collapse is a homotopy preserving operation, and it can be further expressed as sequence of the classical + * elementary simple collapse. + * A complex without any dominated edge is called a \f$1\f$- minimal complex and the core \f$K^1\f$ of simplicial + * complex is a minimal complex such that \f$K\f$ \f${\searrow\searrow}\f$ \f$K^1\f$. + * Computation of a core (not unique) involves computation of dominated edges and the dominated edges can be easily + * characterized as follows: + * + * -- For general simplicial complex: An edge \f$e \in K\f$ is dominated by another vertex \f$v^{\prime} \in K\f$, + * <i>if and only if</i> all the maximal simplices of \f$K\f$ that contain \f$e\f$ also contain \f$v^{\prime}\f$ + * + * -- For a flag complex: An edge \f$e \in K\f$ is dominated by another vertex \f$v^{\prime} \in K\f$, <i>if and only + * if</i> all the vertices in \f$K\f$ that has an edge with both vertices of \f$e\f$ also has an edge with + * \f$v^{\prime}\f$. + + * This module implements edge collapse of a filtered flag complex, in particular it reduces a filtration of + * Vietoris-Rips complex from its graph + * to another smaller flag filtration with same persistence. Where a filtration is a sequence of simplicial + * (here Rips) complexes connected with inclusions. The algorithm to compute the smaller induced filtration is + * described in Section 5 \cite edgecollapsesocg2020. + * Edge collapse can be successfully employed to reduce any given filtration of flag complexes to a smaller induced + * filtration which preserves the persistent homology of the original filtration and is a flag complex as well. + + * The general idea is that we consider edges in the filtered graph and sort them according to their filtration value + * giving them a total order. + * Each edge gets a unique index denoted as \f$i\f$ in this order. To reduce the filtration, we move forward with + * increasing filtration value + * in the graph and check if the current edge \f$e_i\f$ is dominated in the current graph \f$G_i := \{e_1, .. e_i\} \f$ + * or not. + * If the edge \f$e_i\f$ is dominated we remove it from the filtration and move forward to the next edge \f$e_{i+1}\f$. + * If \f$e_i\f$ is non-dominated then we keep it in the reduced filtration and then go backward in the current graph + * \f$G_i\f$ to look for new non-dominated edges that was dominated before but might become non-dominated at this + * point. + * If an edge \f$e_j, j < i \f$ during the backward search is found to be non-dominated, we include \f$e_j\f$ in to the + * reduced filtration and we set its new filtration value to be \f$i\f$ that is the index of \f$e_i\f$. + * The precise mechanism for this reduction has been described in Section 5 \cite edgecollapsesocg2020. + * Here we implement this mechanism for a filtration of Rips complex, + * After perfoming the reduction the filtration reduces to a flag-filtration with the same persistence as the original + * filtration. + * + * \subsection edgecollapseexample Basic edge collapse + * + * This example builds the `Flag_complex_sparse_matrix` from a proximity graph represented as a list of + * `Flag_complex_sparse_matrix::Filtered_edge`. + * Then it collapses edges and displays a new list of `Flag_complex_sparse_matrix::Filtered_edge` (with less edges) + * that will preserve the persistence homology computation. + * + * \include Collapse/edge_collapse_basic_example.cpp + * + * When launching the example: + * + * \code $> ./Edge_collapse_example_basic + * \endcode + * + * the program output is: + * + * \include Collapse/edge_collapse_example_basic.txt + */ +/** @} */ // end defgroup strong_collapse + +} // namespace collapse + +} // namespace Gudhi + +#endif // DOC_EDGE_COLLAPSE_INTRO_EDGE_COLLAPSE_H_ diff --git a/src/Collapse/example/CMakeLists.txt b/src/Collapse/example/CMakeLists.txt new file mode 100644 index 00000000..6cf3bf07 --- /dev/null +++ b/src/Collapse/example/CMakeLists.txt @@ -0,0 +1,10 @@ +project(Edge_collapse_examples) + +# Point cloud +add_executable ( Edge_collapse_example_basic edge_collapse_basic_example.cpp ) + +if (TBB_FOUND) + target_link_libraries(Edge_collapse_example_basic ${TBB_LIBRARIES}) +endif() + +add_test(NAME Edge_collapse_example_basic COMMAND $<TARGET_FILE:Edge_collapse_example_basic>) diff --git a/src/Collapse/example/edge_collapse_basic_example.cpp b/src/Collapse/example/edge_collapse_basic_example.cpp new file mode 100644 index 00000000..a154c6bb --- /dev/null +++ b/src/Collapse/example/edge_collapse_basic_example.cpp @@ -0,0 +1,45 @@ +#include <gudhi/Flag_complex_sparse_matrix.h> + +#include <iostream> +#include <vector> + +int main() { + // Type definitions + using Filtration_value = float; + using Vertex_handle = short; + using Flag_complex_sparse_matrix = Gudhi::collapse::Flag_complex_sparse_matrix<Vertex_handle, Filtration_value>; + using Filtered_edge = Flag_complex_sparse_matrix::Filtered_edge; + using Filtered_edge_list = std::vector<Filtered_edge>; + using Edge = Flag_complex_sparse_matrix::Edge; + + // 1 2 + // o---o + // |\ /| + // | x | + // |/ \| + // o---o + // 0 3 + Filtered_edge_list graph = {{{0, 1}, 1.}, + {{1, 2}, 1.}, + {{2, 3}, 1.}, + {{3, 0}, 1.}, + {{0, 2}, 2.}, + {{1, 3}, 2.}}; + + Flag_complex_sparse_matrix flag_complex_sparse_matrix(graph); + + Filtered_edge_list collapse_edges; + // Retrieve collapse edges from the output iterator + flag_complex_sparse_matrix.filtered_edge_collapse( + [&collapse_edges](std::pair<Vertex_handle, Vertex_handle> edge, Filtration_value filtration) { + collapse_edges.push_back({edge, filtration}); + }); + + for (Filtered_edge filtered_edge_from_collapse : collapse_edges) { + Edge edge_from_collapse = std::get<0>(filtered_edge_from_collapse); + std::cout << "fn[" << std::get<0>(edge_from_collapse) << ", " << std::get<1>(edge_from_collapse) << "] = " + << std::get<1>(filtered_edge_from_collapse) << std::endl; + } + + return 0; +} diff --git a/src/Collapse/example/edge_collapse_example_basic.txt b/src/Collapse/example/edge_collapse_example_basic.txt new file mode 100644 index 00000000..acecacaf --- /dev/null +++ b/src/Collapse/example/edge_collapse_example_basic.txt @@ -0,0 +1,5 @@ +fn[0, 1] = 1 +fn[1, 2] = 1 +fn[2, 3] = 1 +fn[3, 0] = 1 +fn[0, 2] = 2 diff --git a/src/Collapse/include/gudhi/Flag_complex_sparse_matrix.h b/src/Collapse/include/gudhi/Flag_complex_sparse_matrix.h new file mode 100644 index 00000000..a2f3a2a9 --- /dev/null +++ b/src/Collapse/include/gudhi/Flag_complex_sparse_matrix.h @@ -0,0 +1,424 @@ +/* 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): Siddharth Pritam + * + * Copyright (C) 2018 Inria + * + * Modification(s): + * - 2020/03 Vincent Rouvreau: integration to the gudhi library + * - YYYY/MM Author: Description of the modification + */ + +#ifndef FLAG_COMPLEX_SPARSE_MATRIX_H_ +#define FLAG_COMPLEX_SPARSE_MATRIX_H_ + +#include <gudhi/graph_simplicial_complex.h> + +#include <boost/functional/hash.hpp> +#include <boost/graph/adjacency_list.hpp> + +#include <Eigen/Sparse> + +#ifdef GUDHI_USE_TBB +#include <tbb/parallel_sort.h> +#endif + +#include <iostream> +#include <utility> // for std::pair +#include <vector> +#include <unordered_map> +#include <unordered_set> +#include <set> +#include <tuple> // for std::tie +#include <algorithm> // for std::includes +#include <iterator> // for std::inserter + +namespace Gudhi { + +namespace collapse { + +/** + * \class Flag_complex_sparse_matrix + * \brief Flag complex sparse matrix data structure. + * + * \ingroup collapse + * + * \details + * A class to store the vertices v/s MaxSimplices Sparse Matrix and to perform collapse operations using the N^2() + * Algorithm. + * + * \tparam Vertex type must be a signed integer type. It admits a total order <. + * \tparam Filtration type for the value of the filtration function. Must be comparable with <. + */ +template<typename Vertex, typename Filtration> +class Flag_complex_sparse_matrix { + public: + /** \brief Re-define Vertex as Vertex_handle type to ease the interface with compute_proximity_graph. */ + using Vertex_handle = Vertex; + /** \brief Re-define Filtration as Filtration_value type to ease the interface with compute_proximity_graph. */ + using Filtration_value = Filtration; + /** \brief This is an ordered pair, An edge is stored with convention of the first element being the smaller i.e + * {2,3} not {3,2}. However this is at the level of row indices on actual vertex lables. + */ + using Edge = std::pair<Vertex_handle, Vertex_handle>; + + private: + // Row_index type in the sparse matrix + using Row_index = std::size_t; + + // The sparse matrix data type + using Sparse_row_matrix = Eigen::SparseMatrix<Filtration_value, Eigen::RowMajor>; + + // A range of row indices + using Row_indices_vector = std::vector<Row_index>; + + public: + /** \brief A Filtered_edge is a std::pair<std::pair<`Vertex_handle`, `Vertex_handle`>, `Filtration_value`>. */ + using Filtered_edge = std::pair<Edge, Filtration_value>; + /** \brief Proximity_graph is a type that can be used to construct easily a Flag_complex_sparse_matrix. */ + using Proximity_graph = Gudhi::Proximity_graph<Flag_complex_sparse_matrix>; + + private: + // Map from row index to its vertex handle + std::unordered_map<Row_index, Vertex_handle> row_to_vertex_; + + // Vertices stored as an unordered_set + std::unordered_set<Vertex_handle> vertices_; + + // Unordered set of removed edges. (to enforce removal from the matrix) + std::unordered_set<Edge, boost::hash<Edge>> u_set_removed_edges_; + + // Unordered set of dominated edges. (to inforce removal from the matrix) + std::unordered_set<Edge, boost::hash<Edge>> u_set_dominated_edges_; + + // Map from edge to its index + std::unordered_map<Edge, Row_index, boost::hash<Edge>> edge_to_index_map_; + + // Boolean vector to indicate if the index is critical or not. + std::vector<bool> critical_edge_indicator_; + + // Map from vertex handle to its row index + std::unordered_map<Vertex_handle, Row_index> vertex_to_row_; + + // Stores the Sparse matrix of Filtration values representing the original graph. + // This is row-major version of the same sparse-matrix, to facilitate easy access + // to elements when traversing the matrix row-wise. + Sparse_row_matrix sparse_row_adjacency_matrix_; + + // Stores <I>true</I> for dominated rows and <I>false</I> otherwise. + // Initialised to a vector of length equal to the value of the variable <B>rows_</B> with all <I>false</I> values. + // Subsequent removal of dominated vertices is reflected by concerned entries changing to <I>true</I> + // in this vector. + std::vector<bool> domination_indicator_; + + // Vector of filtered edges, for edge-collapse, the indices of the edges are the row-indices. + std::vector<Filtered_edge> f_edge_vector_; + + + //! Stores the number of vertices in the original graph (which is also the number of rows in the Matrix). + Row_index rows_; + + // Edge e is the actual edge (u,v). Not the row ids in the matrixs + bool check_edge_domination(const Edge& edge) const + { + Vertex_handle u = std::get<0>(edge); + Vertex_handle v = std::get<1>(edge); + + const Row_index rw_u = vertex_to_row_.at(u); + const Row_index rw_v = vertex_to_row_.at(v); + auto rw_e = std::make_pair(rw_u, rw_v); +#ifdef DEBUG_TRACES + std::cout << "The edge {" << u << ", " << v << "} is going for domination check." << std::endl; +#endif // DEBUG_TRACES + auto common_neighbours = closed_common_neighbours_row_index(rw_e); +#ifdef DEBUG_TRACES + std::cout << "And its common neighbours are." << std::endl; + for (auto neighbour : common_neighbours) { + std::cout << row_to_vertex_[neighbour] << ", " ; + } + std::cout<< std::endl; +#endif // DEBUG_TRACES + if (common_neighbours.size() > 2) { + if (common_neighbours.size() == 3) + return true; + else + for (auto rw_c : common_neighbours) { + if (rw_c != rw_u and rw_c != rw_v) { + auto neighbours_c = closed_neighbours_row_index(rw_c); + // If neighbours_c contains the common neighbours. + if (std::includes(neighbours_c.begin(), neighbours_c.end(), common_neighbours.begin(), + common_neighbours.end())) + return true; + } + } + } + return false; + } + + std::set<Row_index> three_clique_indices(Row_index crit) { + std::set<Row_index> edge_indices; + + Edge edge = std::get<0>(f_edge_vector_[crit]); + Vertex_handle u = std::get<0>(edge); + Vertex_handle v = std::get<1>(edge); + +#ifdef DEBUG_TRACES + std::cout << "The current critical edge to re-check criticality with filt value is : f {" << u << "," << v + << "} = " << std::get<1>(f_edge_vector_[crit]) << std::endl; +#endif // DEBUG_TRACES + auto rw_u = vertex_to_row_[u]; + auto rw_v = vertex_to_row_[v]; + auto rw_critical_edge = std::make_pair(rw_u, rw_v); + + Row_indices_vector common_neighbours = closed_common_neighbours_row_index(rw_critical_edge); + + if (common_neighbours.size() > 2) { + for (auto rw_c : common_neighbours) { + if (rw_c != rw_u and rw_c != rw_v) { + auto e_with_new_nbhr_v = std::minmax(u, row_to_vertex_[rw_c]); + auto e_with_new_nbhr_u = std::minmax(v, row_to_vertex_[rw_c]); + edge_indices.emplace(edge_to_index_map_[e_with_new_nbhr_v]); + edge_indices.emplace(edge_to_index_map_[e_with_new_nbhr_u]); + } + } + } + return edge_indices; + } + + // Detect and set all indices that are becoming critical + template<typename FilteredEdgeInsertion> + void set_edge_critical(Row_index indx, Filtration_value filt, FilteredEdgeInsertion filtered_edge_insert) { +#ifdef DEBUG_TRACES + std::cout << "The curent index with filtration value " << indx << ", " << filt << " is primary critical" << + std::endl; +#endif // DEBUG_TRACES + std::set<Row_index> effected_indices = three_clique_indices(indx); + if (effected_indices.size() > 0) { + for (auto idx = indx - 1; idx > 0; idx--) { + Edge edge = std::get<0>(f_edge_vector_[idx]); + Vertex_handle u = std::get<0>(edge); + Vertex_handle v = std::get<1>(edge); + // If idx is not critical so it should be processed, otherwise it stays in the graph + if (not critical_edge_indicator_[idx]) { + // If idx is affected + if (effected_indices.find(idx) != effected_indices.end()) { + if (not check_edge_domination(edge)) { +#ifdef DEBUG_TRACES + std::cout << "The curent index became critical " << idx << std::endl; +#endif // DEBUG_TRACES + critical_edge_indicator_[idx] = true; + filtered_edge_insert({u, v}, filt); + std::set<Row_index> inner_effected_indcs = three_clique_indices(idx); + for (auto inr_idx = inner_effected_indcs.rbegin(); inr_idx != inner_effected_indcs.rend(); inr_idx++) { + if (*inr_idx < idx) effected_indices.emplace(*inr_idx); + } + inner_effected_indcs.clear(); +#ifdef DEBUG_TRACES + std::cout << "The following edge is critical with filt value: {" << u << "," << v << "}; " + << filt << std::endl; +#endif // DEBUG_TRACES + } else + u_set_dominated_edges_.emplace(std::minmax(vertex_to_row_[u], vertex_to_row_[v])); + } else + // Idx is not affected hence dominated. + u_set_dominated_edges_.emplace(std::minmax(vertex_to_row_[u], vertex_to_row_[v])); + } + } + } + effected_indices.clear(); + u_set_dominated_edges_.clear(); + } + + // Returns list of non-zero columns of a particular indx. + Row_indices_vector closed_neighbours_row_index(Row_index rw_u) const + { + Row_indices_vector non_zero_indices; +#ifdef DEBUG_TRACES + std::cout << "The neighbours of the vertex: " << row_to_vertex_[rw_u] << " are. " << std::endl; +#endif // DEBUG_TRACES + if (not domination_indicator_[rw_u]) { + // Iterate over the non-zero columns + for (typename Sparse_row_matrix::InnerIterator it(sparse_row_adjacency_matrix_, rw_u); it; ++it) { + Row_index rw_v = it.index(); + // If the vertex v is not dominated and the edge {u,v} is still in the matrix + if (not domination_indicator_[rw_v] and u_set_removed_edges_.find(std::minmax(rw_u, rw_v)) == u_set_removed_edges_.end() and + u_set_dominated_edges_.find(std::minmax(rw_u, rw_v)) == u_set_dominated_edges_.end()) { + // inner index, here it is equal to it.columns() + non_zero_indices.push_back(rw_v); +#ifdef DEBUG_TRACES + std::cout << row_to_vertex_[rw_v] << ", " ; +#endif // DEBUG_TRACES + } + } +#ifdef DEBUG_TRACES + std::cout << std::endl; +#endif // DEBUG_TRACES + } + return non_zero_indices; + } + + // Returns the list of closed neighbours of the edge :{u,v}. + Row_indices_vector closed_common_neighbours_row_index(const std::pair<Row_index, Row_index>& rw_edge) const + { + Row_indices_vector common; + Row_indices_vector non_zero_indices_u; + Row_indices_vector non_zero_indices_v; + Row_index rw_u = std::get<0>(rw_edge); + Row_index rw_v = std::get<1>(rw_edge); + + non_zero_indices_u = closed_neighbours_row_index(rw_u); + non_zero_indices_v = closed_neighbours_row_index(rw_v); + std::set_intersection(non_zero_indices_u.begin(), non_zero_indices_u.end(), non_zero_indices_v.begin(), + non_zero_indices_v.end(), std::inserter(common, common.begin())); + + return common; + } + + // Insert a vertex in the data structure + void insert_vertex(Vertex_handle vertex, Filtration_value filt_val) { + auto rw = vertex_to_row_.find(vertex); + if (rw == vertex_to_row_.end()) { + // Initializing the diagonal element of the adjency matrix corresponding to rw_b. + sparse_row_adjacency_matrix_.insert(rows_, rows_) = filt_val; + domination_indicator_.push_back(false); + vertex_to_row_.insert(std::make_pair(vertex, rows_)); + row_to_vertex_.insert(std::make_pair(rows_, vertex)); + rows_++; + } + } + + // Insert an edge in the data structure + void insert_new_edges(Vertex_handle u, Vertex_handle v, Filtration_value filt_val) + { + // The edge must not be added before, it should be a new edge. + insert_vertex(u, filt_val); + if (u != v) { + insert_vertex(v, filt_val); +#ifdef DEBUG_TRACES + std::cout << "Insertion of the edge begins " << u <<", " << v << std::endl; +#endif // DEBUG_TRACES + + auto rw_u = vertex_to_row_.find(u); + auto rw_v = vertex_to_row_.find(v); +#ifdef DEBUG_TRACES + std::cout << "Inserting the edge " << u <<", " << v << std::endl; +#endif // DEBUG_TRACES + sparse_row_adjacency_matrix_.insert(rw_u->second, rw_v->second) = filt_val; + sparse_row_adjacency_matrix_.insert(rw_v->second, rw_u->second) = filt_val; + } +#ifdef DEBUG_TRACES + else { + std::cout << "Already a member simplex, skipping..." << std::endl; + } +#endif // DEBUG_TRACES + } + + public: + /** \brief Flag_complex_sparse_matrix constructor from a range of filtered edges. + * + * @param[in] filtered_edge_range Range of filtered edges. Filtered edges must be in + * `Flag_complex_sparse_matrix::Filtered_edge`. + * + * There is no need the range to be sorted, as it will be performed in + * `Flag_complex_sparse_matrix::filtered_edge_collapse`. + */ + template<typename Filtered_edge_range> + Flag_complex_sparse_matrix(const Filtered_edge_range& filtered_edge_range) + : f_edge_vector_(filtered_edge_range.begin(), filtered_edge_range.end()), + rows_(0) { + for (Filtered_edge filtered_edge : filtered_edge_range) { + Vertex_handle u; + Vertex_handle v; + std::tie(u,v) = std::get<0>(filtered_edge); + vertices_.emplace(u); + vertices_.emplace(v); + } + } + + /** \brief Flag_complex_sparse_matrix constructor from a proximity graph, cf. `Gudhi::compute_proximity_graph`. + * + * @param[in] one_skeleton_graph The one skeleton graph. The graph must be in + * `Flag_complex_sparse_matrix::Proximity_graph`. + * + * The constructor is computing and filling a vector of `Flag_complex_sparse_matrix::Filtered_edge` + */ + Flag_complex_sparse_matrix(const Proximity_graph& one_skeleton_graph) + : rows_(0) { + // Insert all vertices_ + for (auto v_it = boost::vertices(one_skeleton_graph); v_it.first != v_it.second; ++v_it.first) { + vertices_.emplace(*(v_it.first)); + } + // Insert all edges + for (auto edge_it = boost::edges(one_skeleton_graph); + edge_it.first != edge_it.second; ++edge_it.first) { + auto edge = *(edge_it.first); + Vertex_handle u = source(edge, one_skeleton_graph); + Vertex_handle v = target(edge, one_skeleton_graph); + f_edge_vector_.push_back({{u, v}, boost::get(Gudhi::edge_filtration_t(), one_skeleton_graph, edge)}); + } + } + + /** \brief Performs edge collapse in a decreasing sequence of the filtration value. + * + * \tparam FilteredEdgeInsertion is an output iterator that furnishes + * `({Vertex_handle u, Vertex_handle v}, Filtration_value f)` that will fill the user defined data structure. + */ + template<typename FilteredEdgeInsertion> + void filtered_edge_collapse(FilteredEdgeInsertion filtered_edge_insert) { + Row_index endIdx = 0; + + u_set_removed_edges_.clear(); + u_set_dominated_edges_.clear(); + critical_edge_indicator_.clear(); + + // Sort edges + auto sort_by_filtration = [](const Filtered_edge& edge_a, const Filtered_edge& edge_b) -> bool + { + return (get<1>(edge_a) < get<1>(edge_b)); + }; + +#ifdef GUDHI_USE_TBB + tbb::parallel_sort(f_edge_vector_.begin(), f_edge_vector_.end(), sort_by_filtration); +#else + std::stable_sort(f_edge_vector_.begin(), f_edge_vector_.end(), sort_by_filtration); +#endif + + // Initializing sparse_row_adjacency_matrix_, This is a row-major sparse matrix. + sparse_row_adjacency_matrix_ = Sparse_row_matrix(vertices_.size(), vertices_.size()); + + while (endIdx < f_edge_vector_.size()) { + Filtered_edge fec = f_edge_vector_[endIdx]; + Edge edge = std::get<0>(fec); + Vertex_handle u = std::get<0>(edge); + Vertex_handle v = std::get<1>(edge); + Filtration_value filt = std::get<1>(fec); + + // Inserts the edge in the sparse matrix to update the graph (G_i) + insert_new_edges(u, v, filt); + + edge_to_index_map_.emplace(std::minmax(u, v), endIdx); + critical_edge_indicator_.push_back(false); + + if (not check_edge_domination(edge)) { + critical_edge_indicator_[endIdx] = true; + filtered_edge_insert({u, v}, filt); + if (endIdx > 1) + set_edge_critical(endIdx, filt, filtered_edge_insert); + } + endIdx++; + } + } + + /** \brief Returns the number of vertices in the data structure. + * + * @return the number of vertices (which is also the number of rows in the Matrix). + */ + std::size_t num_vertices() const { return vertices_.size(); } + +}; + +} // namespace collapse + +} // namespace Gudhi + +#endif // FLAG_COMPLEX_SPARSE_MATRIX_H_ diff --git a/src/Collapse/test/CMakeLists.txt b/src/Collapse/test/CMakeLists.txt new file mode 100644 index 00000000..c7eafb46 --- /dev/null +++ b/src/Collapse/test/CMakeLists.txt @@ -0,0 +1,9 @@ +project(Collapse_tests) + +include(GUDHI_boost_test) + +add_executable ( Collapse_test_unit collapse_unit_test.cpp ) +if (TBB_FOUND) + target_link_libraries(Collapse_test_unit ${TBB_LIBRARIES}) +endif() +gudhi_add_boost_test(Collapse_test_unit) diff --git a/src/Collapse/test/collapse_unit_test.cpp b/src/Collapse/test/collapse_unit_test.cpp new file mode 100644 index 00000000..1bec3810 --- /dev/null +++ b/src/Collapse/test/collapse_unit_test.cpp @@ -0,0 +1,191 @@ +/* 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) 2020 Inria + * + * Modification(s): + * - YYYY/MM Author: Description of the modification + */ + + +#define BOOST_TEST_DYN_LINK +#define BOOST_TEST_MODULE "collapse" +#include <boost/test/unit_test.hpp> +#include <boost/mpl/list.hpp> + +#include <gudhi/Flag_complex_sparse_matrix.h> +#include <gudhi/distance_functions.h> +#include <gudhi/graph_simplicial_complex.h> + +#include <iostream> +#include <tuple> +#include <vector> +#include <array> +#include <cmath> + +using Filtration_value = float; +using Vertex_handle = short; +using Flag_complex_sparse_matrix = Gudhi::collapse::Flag_complex_sparse_matrix<Vertex_handle, Filtration_value>; +using Filtered_edge = Flag_complex_sparse_matrix::Filtered_edge; +using Filtered_edge_list = std::vector<Filtered_edge>; + +template<typename Filtered_edge_range> +bool find_edge_in_list(const Filtered_edge& edge, const Filtered_edge_range& edge_list) { + for (auto edge_from_list : edge_list) { + if (edge_from_list == edge) + return true; + } + return false; +} + +template<typename Filtered_edge_range> +void trace_and_check_collapse(const Filtered_edge_range& filtered_edges, const Filtered_edge_list& removed_edges) { + std::cout << "BEFORE COLLAPSE - Total number of edges: " << filtered_edges.size() << std::endl; + BOOST_CHECK(filtered_edges.size() > 0); + for (auto filtered_edge : filtered_edges) { + auto edge = std::get<0>(filtered_edge); + std::cout << "f[" << std::get<0>(edge) << ", " << std::get<1>(edge) << "] = " << std::get<1>(filtered_edge) << std::endl; + } + + std::cout << "COLLAPSE - keep edges: " << std::endl; + Flag_complex_sparse_matrix flag_complex_sparse_matrix(filtered_edges); + Filtered_edge_list collapse_edges; + flag_complex_sparse_matrix.filtered_edge_collapse( + [&collapse_edges](std::pair<Vertex_handle, Vertex_handle> edge, Filtration_value filtration) { + std::cout << "f[" << std::get<0>(edge) << ", " << std::get<1>(edge) << "] = " << filtration << std::endl; + collapse_edges.push_back({edge, filtration}); + }); + std::cout << "AFTER COLLAPSE - Total number of edges: " << collapse_edges.size() << std::endl; + BOOST_CHECK(collapse_edges.size() <= filtered_edges.size()); + for (auto filtered_edge_from_collapse : collapse_edges) { + auto edge_from_collapse = std::get<0>(filtered_edge_from_collapse); + std::cout << "f[" << std::get<0>(edge_from_collapse) << ", " << std::get<1>(edge_from_collapse) << "] = " + << std::get<1>(filtered_edge_from_collapse) << std::endl; + // Check each edge from collapse is in the input + BOOST_CHECK(find_edge_in_list(filtered_edge_from_collapse, filtered_edges)); + } + + std::cout << "CHECK COLLAPSE - Total number of removed edges: " << removed_edges.size() << std::endl; + for (auto removed_filtered_edge : removed_edges) { + auto removed_edge = std::get<0>(removed_filtered_edge); + std::cout << "f[" << std::get<0>(removed_edge) << ", " << std::get<1>(removed_edge) << "] = " + << std::get<1>(removed_filtered_edge) << std::endl; + // Check each removed edge from collapse is in the input + BOOST_CHECK(!find_edge_in_list(removed_filtered_edge, collapse_edges)); + } + +} + +BOOST_AUTO_TEST_CASE(collapse) { + std::cout << "***** COLLAPSE *****" << std::endl; + // 1 2 + // o---o + // | | + // | | + // | | + // o---o + // 0 3 + Filtered_edge_list edges {{{0, 1}, 1.}, {{1, 2}, 1.}, {{2, 3}, 1.}, {{3, 0}, 1.}}; + trace_and_check_collapse(edges, {}); + + // 1 2 + // o---o + // |\ /| + // | x | + // |/ \| + // o---o + // 0 3 + edges.push_back({{0, 2}, 2.}); + edges.push_back({{1, 3}, 2.}); + trace_and_check_collapse(edges, {{{1, 3}, 2.}}); + + // 1 2 4 + // o---o---o + // |\ /| | + // | x | | + // |/ \| | + // o---o---o + // 0 3 5 + edges.push_back({{2, 4}, 3.}); + edges.push_back({{4, 5}, 3.}); + edges.push_back({{5, 3}, 3.}); + trace_and_check_collapse(edges, {{{1, 3}, 2.}}); + + // 1 2 4 + // o---o---o + // |\ /|\ /| + // | x | x | + // |/ \|/ \| + // o---o---o + // 0 3 5 + edges.push_back({{2, 5}, 4.}); + edges.push_back({{4, 3}, 4.}); + trace_and_check_collapse(edges, {{{1, 3}, 2.}, {{4, 3}, 4.}}); + + // 1 2 4 + // o---o---o + // |\ /|\ /| + // | x | x | + [0,4] and [1,5] + // |/ \|/ \| + // o---o---o + // 0 3 5 + edges.push_back({{1, 5}, 5.}); + edges.push_back({{0, 4}, 5.}); + trace_and_check_collapse(edges, {{{1, 3}, 2.}, {{4, 3}, 4.}, {{0, 4}, 5.}}); +} + +BOOST_AUTO_TEST_CASE(collapse_from_array) { + std::cout << "***** COLLAPSE FROM ARRAY *****" << std::endl; + // 1 2 + // o---o + // |\ /| + // | x | + // |/ \| + // o---o + // 0 3 + std::array<Filtered_edge, 6> f_edge_array = {{{{0, 1}, 1.}, {{1, 2}, 1.}, {{2, 3}, 1.}, {{3, 0}, 1.}, {{0, 2}, 2.}, {{1, 3}, 2.}}}; + trace_and_check_collapse(f_edge_array, {{{1, 3}, 2.}}); +} + + +BOOST_AUTO_TEST_CASE(collapse_from_proximity_graph) { + std::cout << "***** COLLAPSE FROM PROXIMITY GRAPH *****" << std::endl; + // 1 2 + // o---o + // |\ /| + // | x | + // |/ \| + // o---o + // 0 3 + std::vector<std::vector<Filtration_value>> point_cloud = {{0., 0.}, + {0., 1.}, + {1., 0.}, + {1., 1.} }; + + Filtration_value threshold = std::numeric_limits<Filtration_value>::infinity(); + using Proximity_graph = Flag_complex_sparse_matrix::Proximity_graph; + Proximity_graph proximity_graph = Gudhi::compute_proximity_graph<Flag_complex_sparse_matrix>(point_cloud, + threshold, + Gudhi::Euclidean_distance()); + Flag_complex_sparse_matrix flag_complex_sparse_matrix(proximity_graph); + Filtered_edge_list collapse_edges; + flag_complex_sparse_matrix.filtered_edge_collapse( + [&collapse_edges](std::pair<Vertex_handle, Vertex_handle> edge, Filtration_value filtration) { + std::cout << "f[" << std::get<0>(edge) << ", " << std::get<1>(edge) << "] = " << filtration << std::endl; + collapse_edges.push_back({edge, filtration}); + }); + BOOST_CHECK(collapse_edges.size() == 5); + + std::size_t filtration_is_edge_length_nb = 0; + std::size_t filtration_is_diagonal_length_nb = 0; + float epsilon = std::numeric_limits<Filtration_value>::epsilon(); + for (auto filtered_edge : collapse_edges) { + if (std::get<1>(filtered_edge) == 1.) + filtration_is_edge_length_nb++; + if (std::fabs(std::get<1>(filtered_edge) - std::sqrt(2.)) <= epsilon) + filtration_is_diagonal_length_nb++; + } + BOOST_CHECK(filtration_is_edge_length_nb == 4); + BOOST_CHECK(filtration_is_diagonal_length_nb == 1); +}
\ No newline at end of file diff --git a/src/Collapse/utilities/CMakeLists.txt b/src/Collapse/utilities/CMakeLists.txt new file mode 100644 index 00000000..c742144b --- /dev/null +++ b/src/Collapse/utilities/CMakeLists.txt @@ -0,0 +1,33 @@ +project(Collapse_utilities) + +# From a point cloud +add_executable ( point_cloud_edge_collapse_rips_persistence point_cloud_edge_collapse_rips_persistence.cpp ) +target_link_libraries(point_cloud_edge_collapse_rips_persistence Boost::program_options) + +if (TBB_FOUND) + target_link_libraries(point_cloud_edge_collapse_rips_persistence ${TBB_LIBRARIES}) +endif() +add_test(NAME Edge_collapse_utilities_point_cloud_rips_persistence COMMAND $<TARGET_FILE:point_cloud_edge_collapse_rips_persistence> + "${CMAKE_SOURCE_DIR}/data/points/tore3D_1307.off" "-r" "0.25" "-m" "0.5" "-d" "3" "-p" "3" "-o" "off_results.pers") + +install(TARGETS point_cloud_edge_collapse_rips_persistence DESTINATION bin) + +# From a distance matrix +add_executable ( distance_matrix_edge_collapse_rips_persistence distance_matrix_edge_collapse_rips_persistence.cpp ) +target_link_libraries(distance_matrix_edge_collapse_rips_persistence Boost::program_options) + +if (TBB_FOUND) + target_link_libraries(distance_matrix_edge_collapse_rips_persistence ${TBB_LIBRARIES}) +endif() +add_test(NAME Edge_collapse_utilities_distance_matrix_rips_persistence COMMAND $<TARGET_FILE:distance_matrix_edge_collapse_rips_persistence> + "${CMAKE_SOURCE_DIR}/data/distance_matrix/tore3D_1307_distance_matrix.csv" "-r" "0.25" "-m" "0.5" "-d" "3" "-p" "3" "-o" "csv_results.pers") + +install(TARGETS distance_matrix_edge_collapse_rips_persistence DESTINATION bin) + +if (DIFF_PATH) + add_test(Edge_collapse_utilities_diff_persistence ${DIFF_PATH} + "off_results.pers" "csv_results.pers") + set_tests_properties(Edge_collapse_utilities_diff_persistence PROPERTIES DEPENDS + "Edge_collapse_utilities_point_cloud_rips_persistence;Edge_collapse_utilities_distance_matrix_rips_persistence") + +endif() diff --git a/src/Collapse/utilities/collapse.md b/src/Collapse/utilities/collapse.md new file mode 100644 index 00000000..9ca5077a --- /dev/null +++ b/src/Collapse/utilities/collapse.md @@ -0,0 +1,63 @@ +--- +layout: page +title: "Collapse" +meta_title: "Edge collapse" +teaser: "" +permalink: /collapse/ +--- +{::comment} +Leave the lines above as it is required by the web site generator 'Jekyll' +{:/comment} + + +## point_cloud_edge_collapse_rips_persistence ## +This program computes the one-skeleton graph defined on a set of input points, using Euclidean distance, and collapse edges. +This program finally computes persistent homology with coefficient field *Z/pZ* of the Rips complex built on top of these collapse edges. +The output diagram contains one bar per line, written with the convention: + +`p dim birth death` + +where `dim` is the dimension of the homological feature, `birth` and `death` are respectively the birth and death of the feature, and `p` is the characteristic of the field *Z/pZ* used for homology coefficients (`p` must be a prime number). + +**Usage** + +`point_cloud_edge_collapse_rips_persistence [options] <OFF input file>` + +**Allowed options** + +* `-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. +* `-d [ --cpx-dimension ]` (default = 1) 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. +* `-m [ --min-persistence ]` (default = 0) Minimal lifetime of homology feature to be recorded. Enter a negative value to see zero length intervals. + +Beware: this program may use a lot of RAM and take a lot of time if `max-edge-length` is set to a large value. + +**Example 1 with Z/2Z coefficients** + +`point_cloud_edge_collapse_rips_persistence ../../data/points/tore3D_1307.off -r 0.25 -m 0.5 -d 3 -p 2` + +**Example 2 with Z/3Z coefficients** + +`point_cloud_edge_collapse_rips_persistence ../../data/points/tore3D_1307.off -r 0.25 -m 0.5 -d 3 -p 3` + + +## distance_matrix_edge_collapse_rips_persistence ## + +Same as `point_cloud_edge_collapse_rips_persistence` but taking a distance matrix as input. + +**Usage** + +`distance_matrix_edge_collapse_rips_persistence [options] <CSV input file>` + +where +`<CSV input file>` is the path to the file containing a distance matrix. Can be square or lower triangular matrix. Separator is ';'. +The code do not check if it is dealing with a distance matrix. It is the user responsibility to provide a valid input. +Please refer to data/distance_matrix/lower_triangular_distance_matrix.csv for an example of a file. + +**Example** + +`distance_matrix_edge_collapse_rips_persistence data/distance_matrix/full_square_distance_matrix.csv -r 15 -d 3 -p 3 -m 0` + + diff --git a/src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp b/src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp new file mode 100644 index 00000000..f4a460ab --- /dev/null +++ b/src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp @@ -0,0 +1,177 @@ +/* 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): Siddharth Pritam, Vincent Rouvreau + * + * Copyright (C) 2020 Inria + * + * Modification(s): + * - YYYY/MM Author: Description of the modification + */ + +#include <gudhi/Flag_complex_sparse_matrix.h> +#include <gudhi/Simplex_tree.h> +#include <gudhi/Persistent_cohomology.h> +#include <gudhi/reader_utils.h> +#include <gudhi/graph_simplicial_complex.h> + +#include <boost/program_options.hpp> + +using Simplex_tree = Gudhi::Simplex_tree<Gudhi::Simplex_tree_options_fast_persistence>; +using Filtration_value = Simplex_tree::Filtration_value; +using Vertex_handle = Simplex_tree::Vertex_handle; + +using Flag_complex_sparse_matrix = Gudhi::collapse::Flag_complex_sparse_matrix<Vertex_handle, Filtration_value>; +using Proximity_graph = Flag_complex_sparse_matrix::Proximity_graph; + +using Field_Zp = Gudhi::persistent_cohomology::Field_Zp; +using Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp>; +using Distance_matrix = std::vector<std::vector<Filtration_value>>; + +void program_options(int argc, char* const argv[], double& min_persistence, double& end_thresold, + int& dimension, int& dim_max, std::string& csv_matrix_file, std::string& filediag) { + namespace po = boost::program_options; + po::options_description visible("Allowed options", 100); + visible.add_options() + ("help,h", "produce help message") + ("min_persistence,m", po::value<double>(&min_persistence)->default_value(0.1), + "Minimum persistence interval length") + ("end_thresold,e", po::value<double>(&end_thresold)->default_value(1), + "Final threshold for rips complex.") + ("dimensions,D", po::value<int>(&dimension)->default_value(2), + "Dimension of the manifold.") + ("dim_max,k ", po::value<int>(&dim_max)->default_value(2), + "Maximum allowed dimension of the Rips complex.") + ("input_file_name,i", po::value<std::string>(&csv_matrix_file), + "The input file.") + ("filediag,o", po::value<std::string>(&filediag), + "The output file."); + + po::options_description all; + all.add(visible); + po::variables_map vm; + po::store(po::command_line_parser(argc, argv).options(all).run(), vm); + po::notify(vm); + if (vm.count("help")) { + std::cout << std::endl; + std::cout << "Computes rips complexes of different threshold values, to 'end_thresold' from a n random uniform " + "point_vector on a selected manifold, . \n"; + std::cout << "Strongly collapses all the rips complexes and output the results in out_file. \n"; + std::cout << "The experiments are repeted 'repete' num of times for each threshold value. \n"; + std::cout << "type -m for manifold options, 's' for uni sphere, 'b' for unit ball, 'f' for file. \n"; + std::cout << "type -i 'filename' for Input file option for exported point sample. \n"; + std::cout << std::endl << std::endl; + std::cout << "Usage: " << argv[0] << " [options]" << std::endl << std::endl; + std::cout << visible << std::endl; + std::abort(); + } +} + +void program_options(int argc, char* argv[], std::string& csv_matrix_file, std::string& filediag, + Filtration_value& threshold, int& dim_max, int& p, Filtration_value& min_persistence); + +int main(int argc, char* argv[]) { + std::string csv_matrix_file; + std::string filediag; + Filtration_value threshold; + int dim_max = 2; + int p; + Filtration_value min_persistence; + + program_options(argc, argv, csv_matrix_file, filediag, threshold, dim_max, p, min_persistence); + + Distance_matrix distances; + + distances = Gudhi::read_lower_triangular_matrix_from_csv_file<Filtration_value>(csv_matrix_file); + std::cout << "Read the distance matrix succesfully, of size: " << distances.size() << std::endl; + + Proximity_graph proximity_graph = Gudhi::compute_proximity_graph<Simplex_tree>(boost::irange((size_t)0, + distances.size()), + threshold, + [&distances](size_t i, size_t j) { + return distances[j][i]; + }); + + // Now we will perform filtered edge collapse to sparsify the edge list edge_t. + Flag_complex_sparse_matrix flag_complex(proximity_graph); + + Simplex_tree stree; + flag_complex.filtered_edge_collapse( + [&stree](std::vector<Vertex_handle> edge, Filtration_value filtration) { + // insert the 2 vertices with a 0. filtration value just like a Rips + stree.insert_simplex({edge[0]}, 0.); + stree.insert_simplex({edge[1]}, 0.); + // insert the edge + stree.insert_simplex(edge, filtration); + }); + + stree.expansion(dim_max); + + std::cout << "The complex contains " << stree.num_simplices() << " simplices after collapse. \n"; + std::cout << " and has dimension " << stree.dimension() << " \n"; + + // Sort the simplices in the order of the filtration + stree.initialize_filtration(); + // Compute the persistence diagram of the complex + Persistent_cohomology pcoh(stree); + // initializes the coefficient field for homology + pcoh.init_coefficients(3); + + pcoh.compute_persistent_cohomology(min_persistence); + if (filediag.empty()) { + pcoh.output_diagram(); + } else { + std::ofstream out(filediag); + pcoh.output_diagram(out); + out.close(); + } + return 0; +} + +void program_options(int argc, char* argv[], std::string& csv_matrix_file, std::string& filediag, + Filtration_value& threshold, int& dim_max, int& p, Filtration_value& min_persistence) { + namespace po = boost::program_options; + po::options_description hidden("Hidden options"); + hidden.add_options()( + "input-file", po::value<std::string>(&csv_matrix_file), + "Name of file containing a distance matrix. Can be square or lower triangular matrix. Separator is ';'."); + + po::options_description visible("Allowed options", 100); + 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.")( + "cpx-dimension,d", po::value<int>(&dim_max)->default_value(1), + "Maximal dimension of the Rips complex we want to compute.")( + "field-charac,p", po::value<int>(&p)->default_value(11), + "Characteristic p of the coefficient field Z/pZ for computing homology.")( + "min-persistence,m", po::value<Filtration_value>(&min_persistence), + "Minimal lifetime of homology feature to be recorded. Default is 0. Enter a negative value to see zero length " + "intervals"); + + po::positional_options_description pos; + pos.add("input-file", 1); + + po::options_description all; + all.add(visible).add(hidden); + + po::variables_map vm; + po::store(po::command_line_parser(argc, argv).options(all).positional(pos).run(), vm); + po::notify(vm); + + if (vm.count("help") || !vm.count("input-file")) { + std::cout << std::endl; + std::cout << "Compute the persistent homology with coefficient field Z/pZ \n"; + std::cout << "of a Rips complex after edge collapse defined on a set of distance matrix.\n \n"; + std::cout << "The output diagram contains one bar per line, written with the convention: \n"; + std::cout << " p dim b d \n"; + std::cout << "where dim is the dimension of the homological feature,\n"; + std::cout << "b and d are respectively the birth and death of the feature and \n"; + std::cout << "p is the characteristic of the field Z/pZ used for homology coefficients." << std::endl << std::endl; + + std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl << std::endl; + std::cout << visible << std::endl; + exit(-1); + } +} diff --git a/src/Collapse/utilities/point_cloud_edge_collapse_rips_persistence.cpp b/src/Collapse/utilities/point_cloud_edge_collapse_rips_persistence.cpp new file mode 100644 index 00000000..b9130d4c --- /dev/null +++ b/src/Collapse/utilities/point_cloud_edge_collapse_rips_persistence.cpp @@ -0,0 +1,165 @@ +/* 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): Siddharth Pritam, Vincent Rouvreau + * + * Copyright (C) 2020 Inria + * + * Modification(s): + * - YYYY/MM Author: Description of the modification + */ + +#include <gudhi/Flag_complex_sparse_matrix.h> +#include <gudhi/Simplex_tree.h> +#include <gudhi/Persistent_cohomology.h> +#include <gudhi/distance_functions.h> +#include <gudhi/Points_off_io.h> +#include <gudhi/graph_simplicial_complex.h> + +#include <boost/program_options.hpp> + +#include<utility> // for std::pair +#include<vector> + +// Types definition + +using Simplex_tree = Gudhi::Simplex_tree<>; +using Filtration_value = Simplex_tree::Filtration_value; +using Vertex_handle = Simplex_tree::Vertex_handle; +using Point = std::vector<Filtration_value>; +using Vector_of_points = std::vector<Point>; + +using Flag_complex_sparse_matrix = Gudhi::collapse::Flag_complex_sparse_matrix<Vertex_handle, Filtration_value>; +using Proximity_graph = Flag_complex_sparse_matrix::Proximity_graph; + +using Field_Zp = Gudhi::persistent_cohomology::Field_Zp; +using Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp>; +using Distance_matrix = std::vector<std::vector<Filtration_value>>; + +void program_options(int argc, char* argv[], std::string& off_file_points, std::string& filediag, + Filtration_value& threshold, int& dim_max, int& p, Filtration_value& min_persistence); + +int main(int argc, char* argv[]) { + std::string off_file_points; + std::string filediag; + double threshold; + int dim_max; + int p; + double min_persistence; + + program_options(argc, argv, off_file_points, filediag, threshold, dim_max, p, min_persistence); + + std::cout << "The current input values to run the program is: " << std::endl; + std::cout << "min_persistence, threshold, max_complex_dimension, off_file_points, filediag" + << std::endl; + std::cout << min_persistence << ", " << threshold << ", " << dim_max + << ", " << off_file_points << ", " << filediag << std::endl; + + Distance_matrix sparse_distances; + + Gudhi::Points_off_reader<Point> off_reader(off_file_points); + if (!off_reader.is_valid()) { + std::cerr << "Unable to read file " << off_file_points << "\n"; + exit(-1); // ----- >> + } + + Vector_of_points point_vector = off_reader.get_point_cloud(); + if (point_vector.size() <= 0) { + std::cerr << "Empty point cloud." << std::endl; + exit(-1); // ----- >> + } + + std::cout << "Successfully read " << point_vector.size() << " point_vector.\n"; + std::cout << "Ambient dimension is " << point_vector[0].size() << ".\n"; + + Proximity_graph proximity_graph = Gudhi::compute_proximity_graph<Simplex_tree>(off_reader.get_point_cloud(), + threshold, + Gudhi::Euclidean_distance()); + + if (num_edges(proximity_graph) <= 0) { + std::cerr << "Total number of egdes are zero." << std::endl; + exit(-1); + } + + Flag_complex_sparse_matrix mat_filt_edge_coll(proximity_graph); + + Simplex_tree stree; + mat_filt_edge_coll.filtered_edge_collapse( + [&stree](const std::vector<Vertex_handle>& edge, Filtration_value filtration) { + // insert the 2 vertices with a 0. filtration value just like a Rips + stree.insert_simplex({edge[0]}, 0.); + stree.insert_simplex({edge[1]}, 0.); + // insert the edge + stree.insert_simplex(edge, filtration); + }); + + stree.expansion(dim_max); + + std::cout << "The complex contains " << stree.num_simplices() << " simplices after collapse. \n"; + std::cout << " and has dimension " << stree.dimension() << " \n"; + + // Sort the simplices in the order of the filtration + stree.initialize_filtration(); + // Compute the persistence diagram of the complex + Persistent_cohomology pcoh(stree); + // initializes the coefficient field for homology + pcoh.init_coefficients(p); + + pcoh.compute_persistent_cohomology(min_persistence); + if (filediag.empty()) { + pcoh.output_diagram(); + } else { + std::ofstream out(filediag); + pcoh.output_diagram(out); + out.close(); + } + + return 0; +} + +void program_options(int argc, char* argv[], std::string& off_file_points, std::string& filediag, + Filtration_value& threshold, int& dim_max, int& p, 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), + "Name of an OFF file containing a point set.\n"); + + po::options_description visible("Allowed options", 100); + 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.")( + "cpx-dimension,d", po::value<int>(&dim_max)->default_value(1), + "Maximal dimension of the Rips complex we want to compute.")( + "field-charac,p", po::value<int>(&p)->default_value(11), + "Characteristic p of the coefficient field Z/pZ for computing homology.")( + "min-persistence,m", po::value<Filtration_value>(&min_persistence), + "Minimal lifetime of homology feature to be recorded. Default is 0. Enter a negative value to see zero length " + "intervals"); + + po::positional_options_description pos; + pos.add("input-file", 1); + + po::options_description all; + all.add(visible).add(hidden); + + po::variables_map vm; + po::store(po::command_line_parser(argc, argv).options(all).positional(pos).run(), vm); + po::notify(vm); + + if (vm.count("help") || !vm.count("input-file")) { + std::cout << std::endl; + std::cout << "Compute the persistent homology with coefficient field Z/pZ \n"; + std::cout << "of a Rips complex, after edge collapse, defined on a set of input points.\n \n"; + std::cout << "The output diagram contains one bar per line, written with the convention: \n"; + std::cout << " p dim b d \n"; + std::cout << "where dim is the dimension of the homological feature,\n"; + std::cout << "b and d are respectively the birth and death of the feature and \n"; + std::cout << "p is the characteristic of the field Z/pZ used for homology coefficients." << std::endl << std::endl; + + std::cout << "Usage: " << argv[0] << " [options] input-file" << std::endl << std::endl; + std::cout << visible << std::endl; + exit(-1); + } +}
\ No newline at end of file diff --git a/src/common/doc/main_page.md b/src/common/doc/main_page.md index 6ea10b88..cdea3d94 100644 --- a/src/common/doc/main_page.md +++ b/src/common/doc/main_page.md @@ -242,6 +242,36 @@ </tr> </table> +#### Strong collapse + +<table> + <tr> + <td width="35%" rowspan=2> + \image html "edge_collapse_representation.png" + </td> + <td width="50%"> + Edge collapse is able to reduce any flag filtration to a smaller flag filtration with the same persistence, using + only the 1-skeletons of a simplicial complex. + The reduction is exact and the persistence homology of the reduced sequence is identical to the persistence + homology of the input sequence. The resulting method is simple and extremely efficient. + + Computation of edge collapse and persistent homology of a filtered flag complex via edge collapse as described in + \cite edgecollapsesocg2020. + </td> + <td width="15%"> + <b>Author:</b> Siddharth Pritam<br> + <b>Introduced in:</b> GUDHI 2.4.0<br> + <b>Copyright:</b> MIT<br> + <b>Requires:</b> \ref eigen + </td> + </tr> + <tr> + <td colspan=2 height="25"> + <b>User manual:</b> \ref edge_collapse + </td> + </tr> +</table> + ### Cover Complexes <table> <tr> |