summaryrefslogtreecommitdiff
path: root/src/Collapse
diff options
context:
space:
mode:
Diffstat (limited to 'src/Collapse')
-rw-r--r--src/Collapse/doc/dominated_edge.pngbin0 -> 349766 bytes
-rw-r--r--src/Collapse/doc/intro_edge_collapse.h101
-rw-r--r--src/Collapse/example/CMakeLists.txt23
-rw-r--r--src/Collapse/example/edge_collapse_basic_example.cpp36
-rw-r--r--src/Collapse/example/edge_collapse_conserve_persistence.cpp159
-rw-r--r--src/Collapse/example/edge_collapse_example_basic.txt5
-rw-r--r--src/Collapse/include/gudhi/Flag_complex_edge_collapser.h378
-rw-r--r--src/Collapse/test/CMakeLists.txt9
-rw-r--r--src/Collapse/test/collapse_unit_test.cpp198
-rw-r--r--src/Collapse/utilities/CMakeLists.txt33
-rw-r--r--src/Collapse/utilities/collapse.md63
-rw-r--r--src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp152
-rw-r--r--src/Collapse/utilities/point_cloud_edge_collapse_rips_persistence.cpp181
13 files changed, 1338 insertions, 0 deletions
diff --git a/src/Collapse/doc/dominated_edge.png b/src/Collapse/doc/dominated_edge.png
new file mode 100644
index 00000000..5900a55a
--- /dev/null
+++ b/src/Collapse/doc/dominated_edge.png
Binary files differ
diff --git a/src/Collapse/doc/intro_edge_collapse.h b/src/Collapse/doc/intro_edge_collapse.h
new file mode 100644
index 00000000..81edd79f
--- /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) 2020 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
+ *
+ * @{
+ *
+ * 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.
+ *
+ * \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$.
+ *
+ * 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 calls `Gudhi::collapse::flag_complex_collapse_edges()` from a proximity graph represented as a list of
+ * `Filtered_edge`.
+ * Then it collapses edges and displays a new list of `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..ba0e75e3
--- /dev/null
+++ b/src/Collapse/example/CMakeLists.txt
@@ -0,0 +1,23 @@
+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>)
+
+# Point cloud
+add_executable ( Edge_collapse_conserve_persistence edge_collapse_conserve_persistence.cpp )
+
+if (TBB_FOUND)
+ target_link_libraries(Edge_collapse_conserve_persistence ${TBB_LIBRARIES})
+endif()
+
+add_test(NAME Edge_collapse_conserve_persistence_1 COMMAND $<TARGET_FILE:Edge_collapse_conserve_persistence>
+ "${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off" "0.2")
+
+add_test(NAME Edge_collapse_conserve_persistence_2 COMMAND $<TARGET_FILE:Edge_collapse_conserve_persistence>
+ "${CMAKE_SOURCE_DIR}/data/points/tore3D_300.off" "1.8")
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..1b3dc1b5
--- /dev/null
+++ b/src/Collapse/example/edge_collapse_basic_example.cpp
@@ -0,0 +1,36 @@
+#include <gudhi/Flag_complex_edge_collapser.h>
+
+#include <iostream>
+#include <vector>
+#include <tuple>
+
+int main() {
+ // Type definitions
+ using Filtration_value = float;
+ using Vertex_handle = short;
+ using Filtered_edge = std::tuple<Vertex_handle, Vertex_handle, Filtration_value>;
+ using Filtered_edge_list = std::vector<Filtered_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.}};
+
+ auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(graph);
+
+ for (auto filtered_edge_from_collapse : remaining_edges) {
+ std::cout << "fn[" << std::get<0>(filtered_edge_from_collapse) << ", " << std::get<1>(filtered_edge_from_collapse)
+ << "] = " << std::get<2>(filtered_edge_from_collapse) << std::endl;
+ }
+
+ return 0;
+}
diff --git a/src/Collapse/example/edge_collapse_conserve_persistence.cpp b/src/Collapse/example/edge_collapse_conserve_persistence.cpp
new file mode 100644
index 00000000..b2c55e7a
--- /dev/null
+++ b/src/Collapse/example/edge_collapse_conserve_persistence.cpp
@@ -0,0 +1,159 @@
+/* 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
+ */
+
+#include <gudhi/Flag_complex_edge_collapser.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/range/adaptor/transformed.hpp>
+
+#include<utility> // for std::pair
+#include<vector>
+#include<tuple>
+
+// 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 Proximity_graph = Gudhi::Proximity_graph<Simplex_tree>;
+
+using Field_Zp = Gudhi::persistent_cohomology::Field_Zp;
+using Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp>;
+
+using Persistence_interval = std::tuple<int, Filtration_value, Filtration_value>;
+/*
+ * Compare two intervals by dimension, then by length.
+ */
+struct cmp_intervals_by_length {
+ explicit cmp_intervals_by_length(Simplex_tree * sc)
+ : sc_(sc) { }
+
+ template<typename Persistent_interval>
+ bool operator()(const Persistent_interval & p1, const Persistent_interval & p2) {
+ return (sc_->filtration(get < 1 > (p1)) - sc_->filtration(get < 0 > (p1))
+ > sc_->filtration(get < 1 > (p2)) - sc_->filtration(get < 0 > (p2)));
+ }
+ Simplex_tree* sc_;
+};
+
+std::vector<Persistence_interval> get_persistence_intervals(Simplex_tree& st, int ambient_dim) {
+ std::vector<Persistence_interval> persistence_intervals;
+ st.expansion(ambient_dim);
+
+ // Sort the simplices in the order of the filtration
+ st.initialize_filtration();
+ // Compute the persistence diagram of the complex
+ Persistent_cohomology pcoh(st);
+ // initializes the coefficient field for homology - must be a prime number
+ int p = 11;
+ pcoh.init_coefficients(p);
+
+ // Default min_interval_length = 0.
+ pcoh.compute_persistent_cohomology();
+ // Custom sort and output persistence
+ cmp_intervals_by_length cmp(&st);
+ auto persistent_pairs = pcoh.get_persistent_pairs();
+ std::sort(std::begin(persistent_pairs), std::end(persistent_pairs), cmp);
+ for (auto pair : persistent_pairs) {
+ persistence_intervals.emplace_back(st.dimension(get<0>(pair)),
+ st.filtration(get<0>(pair)),
+ st.filtration(get<1>(pair)));
+ }
+ return persistence_intervals;
+}
+
+int main(int argc, char* argv[]) {
+ if (argc != 3) {
+ std::cerr << "This program requires an OFF file and minimal threshold value as parameter\n";
+ std::cerr << "For instance: ./Edge_collapse_conserve_persistence ../../data/points/tore3D_300.off 1.\n";
+ exit(-1); // ----- >>
+ }
+
+ std::string off_file_points {argv[1]};
+ double threshold {atof(argv[2])};
+
+ 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); // ----- >>
+ }
+
+ 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);
+ }
+
+ int ambient_dim = point_vector[0].size();
+
+ // ***** Simplex tree from a flag complex built after collapse *****
+ auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(
+ boost::adaptors::transform(edges(proximity_graph), [&](auto&&edge){
+ return std::make_tuple(static_cast<Vertex_handle>(source(edge, proximity_graph)),
+ static_cast<Vertex_handle>(target(edge, proximity_graph)),
+ get(Gudhi::edge_filtration_t(), proximity_graph, edge));
+ })
+ );
+
+ Simplex_tree stree_from_collapse;
+ for (Vertex_handle vertex = 0; static_cast<std::size_t>(vertex) < point_vector.size(); vertex++) {
+ // insert the vertex with a 0. filtration value just like a Rips
+ stree_from_collapse.insert_simplex({vertex}, 0.);
+ }
+ for (auto remaining_edge : remaining_edges) {
+ stree_from_collapse.insert_simplex({std::get<0>(remaining_edge), std::get<1>(remaining_edge)},
+ std::get<2>(remaining_edge));
+ }
+
+ std::vector<Persistence_interval> persistence_intervals_from_collapse = get_persistence_intervals(stree_from_collapse, ambient_dim);
+
+ // ***** Simplex tree from the complete flag complex *****
+ Simplex_tree stree_wo_collapse;
+ stree_wo_collapse.insert_graph(proximity_graph);
+
+ std::vector<Persistence_interval> persistence_intervals_wo_collapse = get_persistence_intervals(stree_wo_collapse, ambient_dim);
+
+ // ***** Comparison *****
+ if (persistence_intervals_wo_collapse.size() != persistence_intervals_from_collapse.size()) {
+ std::cerr << "Number of persistence pairs with collapse is " << persistence_intervals_from_collapse.size() << std::endl;
+ std::cerr << "Number of persistence pairs without collapse is " << persistence_intervals_wo_collapse.size() << std::endl;
+ exit(-1);
+ }
+
+ int return_value = 0;
+ auto ppwoc_ptr = persistence_intervals_wo_collapse.begin();
+ for (auto ppfc: persistence_intervals_from_collapse) {
+ if (ppfc != *ppwoc_ptr) {
+ return_value++;
+ std::cerr << "Without collapse: "
+ << std::get<0>(*ppwoc_ptr) << " " << std::get<1>(*ppwoc_ptr) << " " << std::get<2>(*ppwoc_ptr)
+ << " - With collapse: "
+ << std::get<0>(ppfc) << " " << std::get<1>(ppfc) << " " << std::get<2>(ppfc) << std::endl;
+ }
+ ppwoc_ptr++;
+ }
+ return return_value;
+}
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_edge_collapser.h b/src/Collapse/include/gudhi/Flag_complex_edge_collapser.h
new file mode 100644
index 00000000..b6b7f7c1
--- /dev/null
+++ b/src/Collapse/include/gudhi/Flag_complex_edge_collapser.h
@@ -0,0 +1,378 @@
+/* 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) 2020 Inria
+ *
+ * Modification(s):
+ * - 2020/03 Vincent Rouvreau: integration to the gudhi library
+ * - YYYY/MM Author: Description of the modification
+ */
+
+#ifndef FLAG_COMPLEX_EDGE_COLLAPSER_H_
+#define FLAG_COMPLEX_EDGE_COLLAPSER_H_
+
+#include <gudhi/Debug_utils.h>
+
+#include <boost/functional/hash.hpp>
+#include <boost/iterator/iterator_facade.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
+#include <type_traits> // for std::decay
+
+namespace Gudhi {
+
+namespace collapse {
+
+/** \private
+ *
+ * \brief Flag complex sparse matrix data structure.
+ *
+ * \details
+ * This class stores a <a target="_blank" href="https://en.wikipedia.org/wiki/Clique_complex">Flag complex</a>
+ * in an <a target="_blank" href="https://eigen.tuxfamily.org/dox/group__TutorialSparse.html">Eigen sparse matrix</a>.
+ *
+ * \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_edge_collapser {
+ public:
+ /** \brief Re-define Vertex as Vertex_handle type to ease the interface with `Gudhi::Proximity_graph`. */
+ using Vertex_handle = Vertex;
+ /** \brief Re-define Filtration as Filtration_value type to ease the interface with `Gudhi::Proximity_graph`. */
+ using Filtration_value = Filtration;
+
+ private:
+ // internal numbering of vertices and edges
+ using IVertex = std::size_t;
+ using Edge_index = std::size_t;
+ using IEdge = std::pair<IVertex, IVertex>;
+
+ // The sparse matrix data type
+ // (Eigen::SparseMatrix<Edge_index, Eigen::RowMajor> has slow insertions)
+ using Sparse_vector = Eigen::SparseVector<Edge_index>;
+ using Sparse_row_matrix = std::vector<Sparse_vector>;
+
+ // Range of neighbors of a vertex
+ template<bool closed>
+ struct Neighbours {
+ class iterator : public boost::iterator_facade<iterator,
+ IVertex, /* value_type */
+ std::input_iterator_tag, // or boost::single_pass_traversal_tag
+ IVertex /* reference */ >
+ {
+ public:
+ iterator():ptr(nullptr){}
+ iterator(Neighbours const*p):ptr(p){find_valid();}
+ private:
+ friend class boost::iterator_core_access;
+ Neighbours const*ptr;
+ void increment(){
+ ++ptr->it;
+ find_valid();
+ }
+ void find_valid(){
+ auto& it = ptr->it;
+ do {
+ if(!it) { ptr=nullptr; break; }
+ if(IVertex(it.index()) == ptr->u) {
+ if(closed) break;
+ else continue;
+ }
+ Edge_index e = it.value();
+ if(e <= ptr->ec->current_backward || ptr->ec->critical_edge_indicator_[e]) break;
+ } while(++it, true);
+ }
+ bool equal(iterator const& other) const { return ptr == other.ptr; }
+ IVertex dereference() const { return ptr->it.index(); }
+ };
+ typedef iterator const_iterator;
+ mutable typename Sparse_vector::InnerIterator it;
+ Flag_complex_edge_collapser const*ec;
+ IVertex u;
+ iterator begin() const { return this; }
+ iterator end() const { return {}; }
+ explicit Neighbours(Flag_complex_edge_collapser const*p,IVertex u):it(p->sparse_row_adjacency_matrix_[u]),ec(p),u(u){}
+ };
+
+ // A range of row indices
+ using IVertex_vector = std::vector<IVertex>;
+
+ public:
+ /** \brief Filtered_edge is a type to store an edge with its filtration value. */
+ using Filtered_edge = std::tuple<Vertex_handle, Vertex_handle, Filtration_value>;
+
+ private:
+ // Map from row index to its vertex handle
+ std::vector<Vertex_handle> row_to_vertex_;
+
+ // Index of the current edge in the backwards walk. Edges <= current_backward are part of the temporary graph,
+ // while edges > current_backward are removed unless critical_edge_indicator_.
+ Edge_index current_backward = -1;
+
+ // Map from IEdge to its index
+ std::unordered_map<IEdge, Edge_index, boost::hash<IEdge>> iedge_to_index_map_;
+
+ // Boolean vector to indicate if the edge is critical.
+ std::vector<bool> critical_edge_indicator_;
+
+ // Map from vertex handle to its row index
+ std::unordered_map<Vertex_handle, IVertex> vertex_to_row_;
+
+ // Stores the Sparse matrix of Filtration values representing the original graph.
+ // The matrix rows and columns are indexed by IVertex.
+ Sparse_row_matrix sparse_row_adjacency_matrix_;
+
+ // The input, a vector of filtered edges.
+ std::vector<Filtered_edge> f_edge_vector_;
+
+ // Edge is the actual edge (u,v), with Vertex_handle u and v, not IVertex.
+ bool edge_is_dominated(Vertex_handle u, Vertex_handle v) const
+ {
+ const IVertex rw_u = vertex_to_row_.at(u);
+ const IVertex rw_v = vertex_to_row_.at(v);
+#ifdef DEBUG_TRACES
+ std::cout << "The edge {" << u << ", " << v << "} is going for domination check." << std::endl;
+#endif // DEBUG_TRACES
+ auto common_neighbours = open_common_neighbours_row_index(rw_u, rw_v);
+#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() == 1)
+ return true;
+ else
+ for (auto rw_c : common_neighbours) {
+ auto neighbours_c = neighbours_row_index<true>(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;
+ }
+
+ // Returns the edges connecting u and v (extremities of crit) to their common neighbors (not themselves)
+ std::set<Edge_index> three_clique_indices(Edge_index crit) {
+ std::set<Edge_index> edge_indices;
+
+ Vertex_handle u = std::get<0>(f_edge_vector_[crit]);
+ Vertex_handle v = std::get<1>(f_edge_vector_[crit]);
+
+#ifdef DEBUG_TRACES
+ std::cout << "The current critical edge to re-check criticality with filt value is : f {" << u << "," << v
+ << "} = " << std::get<2>(f_edge_vector_[crit]) << std::endl;
+#endif // DEBUG_TRACES
+ auto rw_u = vertex_to_row_[u];
+ auto rw_v = vertex_to_row_[v];
+
+ IVertex_vector common_neighbours = open_common_neighbours_row_index(rw_u, rw_v);
+
+ for (auto rw_c : common_neighbours) {
+ IEdge e_with_new_nbhr_v = std::minmax(rw_u, rw_c);
+ IEdge e_with_new_nbhr_u = std::minmax(rw_v, rw_c);
+ edge_indices.emplace(iedge_to_index_map_[e_with_new_nbhr_v]);
+ edge_indices.emplace(iedge_to_index_map_[e_with_new_nbhr_u]);
+ }
+ return edge_indices;
+ }
+
+ // Detect and set all edges that are becoming critical
+ template<typename FilteredEdgeOutput>
+ void set_edge_critical(Edge_index indx, Filtration_value filt, FilteredEdgeOutput filtered_edge_output) {
+#ifdef DEBUG_TRACES
+ std::cout << "The curent index with filtration value " << indx << ", " << filt << " is primary critical" <<
+ std::endl;
+#endif // DEBUG_TRACES
+ std::set<Edge_index> effected_indices = three_clique_indices(indx);
+ // Cannot use boost::adaptors::reverse in such dynamic cases apparently
+ for (auto it = effected_indices.rbegin(); it != effected_indices.rend(); ++it) {
+ current_backward = *it;
+ Vertex_handle u = std::get<0>(f_edge_vector_[current_backward]);
+ Vertex_handle v = std::get<1>(f_edge_vector_[current_backward]);
+ // If current_backward is not critical so it should be processed, otherwise it stays in the graph
+ if (!critical_edge_indicator_[current_backward]) {
+ if (!edge_is_dominated(u, v)) {
+#ifdef DEBUG_TRACES
+ std::cout << "The curent index became critical " << current_backward << std::endl;
+#endif // DEBUG_TRACES
+ critical_edge_indicator_[current_backward] = true;
+ filtered_edge_output(u, v, filt);
+ std::set<Edge_index> inner_effected_indcs = three_clique_indices(current_backward);
+ for (auto inr_idx : inner_effected_indcs) {
+ if(inr_idx < current_backward) // && !critical_edge_indicator_[inr_idx]
+ effected_indices.emplace(inr_idx);
+ }
+#ifdef DEBUG_TRACES
+ std::cout << "The following edge is critical with filt value: {" << u << "," << v << "}; "
+ << filt << std::endl;
+#endif // DEBUG_TRACES
+ }
+ }
+ }
+ // Clear the implicit "removed from graph" data structure
+ current_backward = -1;
+ }
+
+ // Returns list of neighbors of a particular vertex.
+ template<bool closed>
+ auto neighbours_row_index(IVertex rw_u) const
+ {
+ return Neighbours<closed>(this, rw_u);
+ }
+
+ // Returns the list of open neighbours of the edge :{u,v}.
+ IVertex_vector open_common_neighbours_row_index(IVertex rw_u, IVertex rw_v) const
+ {
+ auto non_zero_indices_u = neighbours_row_index<false>(rw_u);
+ auto non_zero_indices_v = neighbours_row_index<false>(rw_v);
+ IVertex_vector common;
+ std::set_intersection(non_zero_indices_u.begin(), non_zero_indices_u.end(), non_zero_indices_v.begin(),
+ non_zero_indices_v.end(), std::back_inserter(common));
+
+ return common;
+ }
+
+ // Insert a vertex in the data structure
+ IVertex insert_vertex(Vertex_handle vertex) {
+ auto n = row_to_vertex_.size();
+ auto result = vertex_to_row_.emplace(vertex, n);
+ // If it was not already inserted - Value won't be updated by emplace if it is already present
+ if (result.second) {
+ // Expand the matrix. The size of rows is irrelevant.
+ sparse_row_adjacency_matrix_.emplace_back((std::numeric_limits<Eigen::Index>::max)());
+ // Initializing the diagonal element of the adjency matrix corresponding to rw_b.
+ sparse_row_adjacency_matrix_[n].insert(n) = -1; // not an edge
+ // Must be done after reading its size()
+ row_to_vertex_.push_back(vertex);
+ }
+ return result.first->second;
+ }
+
+ // Insert an edge in the data structure
+ // @exception std::invalid_argument In debug mode, if u == v
+ IEdge insert_new_edge(Vertex_handle u, Vertex_handle v, Edge_index idx)
+ {
+ GUDHI_CHECK((u != v), std::invalid_argument("Flag_complex_edge_collapser::insert_new_edge with u == v"));
+ // The edge must not be added before, it should be a new edge.
+ IVertex rw_u = insert_vertex(u);
+ IVertex rw_v = insert_vertex(v);
+#ifdef DEBUG_TRACES
+ std::cout << "Inserting the edge " << u <<", " << v << std::endl;
+#endif // DEBUG_TRACES
+ sparse_row_adjacency_matrix_[rw_u].insert(rw_v) = idx;
+ sparse_row_adjacency_matrix_[rw_v].insert(rw_u) = idx;
+ return std::minmax(rw_u, rw_v);
+ }
+
+ public:
+ /** \brief Flag_complex_edge_collapser constructor from a range of filtered edges.
+ *
+ * @param[in] edges Range of Filtered edges range.There is no need the range to be sorted, as it will be performed in
+ * `Flag_complex_edge_collapser::process_edges`.
+ *
+ * \tparam FilteredEdgeRange must be a range for which std::begin and std::end return iterators on a
+ * `Flag_complex_edge_collapser::Filtered_edge`.
+ */
+ template<typename FilteredEdgeRange>
+ Flag_complex_edge_collapser(const FilteredEdgeRange& edges)
+ : f_edge_vector_(std::begin(edges), std::end(edges)) { }
+
+ /** \brief Performs edge collapse in a increasing sequence of the filtration value.
+ *
+ * \tparam filtered_edge_output is a functor that is called on the output edges, in non-decreasing order of
+ * filtration, as filtered_edge_output(u, v, f) where u and v are Vertex_handle representing the extremities of the
+ * edge, and f is its new Filtration_value.
+ */
+ template<typename FilteredEdgeOutput>
+ void process_edges(FilteredEdgeOutput filtered_edge_output) {
+ // Sort edges
+ auto sort_by_filtration = [](const Filtered_edge& edge_a, const Filtered_edge& edge_b) -> bool
+ {
+ return (std::get<2>(edge_a) < std::get<2>(edge_b));
+ };
+
+#ifdef GUDHI_USE_TBB
+ tbb::parallel_sort(f_edge_vector_.begin(), f_edge_vector_.end(), sort_by_filtration);
+#else
+ std::sort(f_edge_vector_.begin(), f_edge_vector_.end(), sort_by_filtration);
+#endif
+
+ for (Edge_index endIdx = 0; endIdx < f_edge_vector_.size(); endIdx++) {
+ Filtered_edge fec = f_edge_vector_[endIdx];
+ Vertex_handle u = std::get<0>(fec);
+ Vertex_handle v = std::get<1>(fec);
+ Filtration_value filt = std::get<2>(fec);
+
+ // Inserts the edge in the sparse matrix to update the graph (G_i)
+ IEdge ie = insert_new_edge(u, v, endIdx);
+
+ iedge_to_index_map_.emplace(ie, endIdx);
+ critical_edge_indicator_.push_back(false);
+
+ if (!edge_is_dominated(u, v)) {
+ critical_edge_indicator_[endIdx] = true;
+ filtered_edge_output(u, v, filt);
+ if (endIdx > 1)
+ set_edge_critical(endIdx, filt, filtered_edge_output);
+ }
+ }
+ }
+
+};
+
+/** \brief Implicitly constructs a flag complex from edges as an input, collapses edges while preserving the persistent
+ * homology and returns the remaining edges as a range.
+ *
+ * \param[in] edges Range of Filtered edges.There is no need the range to be sorted, as it will be performed.
+ *
+ * \tparam FilteredEdgeRange furnishes `std::begin` and `std::end` methods and returns an iterator on a
+ * FilteredEdge of type `std::tuple<Vertex_handle, Vertex_handle, Filtration_value>` where `Vertex_handle` is the type
+ * of a vertex index and `Filtration_value` is the type of an edge filtration value.
+ *
+ * \return Remaining edges after collapse as a range of
+ * `std::tuple<Vertex_handle, Vertex_handle, Filtration_value>`.
+ *
+ * \ingroup edge_collapse
+ *
+ */
+template<class FilteredEdgeRange> auto flag_complex_collapse_edges(const FilteredEdgeRange& edges) {
+ auto first_edge_itr = std::begin(edges);
+ using Vertex_handle = std::decay_t<decltype(std::get<0>(*first_edge_itr))>;
+ using Filtration_value = std::decay_t<decltype(std::get<2>(*first_edge_itr))>;
+ using Edge_collapser = Flag_complex_edge_collapser<Vertex_handle, Filtration_value>;
+ std::vector<typename Edge_collapser::Filtered_edge> remaining_edges;
+ if (first_edge_itr != std::end(edges)) {
+ Edge_collapser edge_collapser(edges);
+ edge_collapser.process_edges(
+ [&remaining_edges](Vertex_handle u, Vertex_handle v, Filtration_value filtration) {
+ // insert the edge
+ remaining_edges.emplace_back(u, v, filtration);
+ });
+ }
+ return remaining_edges;
+}
+
+} // namespace collapse
+
+} // namespace Gudhi
+
+#endif // FLAG_COMPLEX_EDGE_COLLAPSER_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..b8876246
--- /dev/null
+++ b/src/Collapse/test/collapse_unit_test.cpp
@@ -0,0 +1,198 @@
+/* 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 <boost/range/adaptor/transformed.hpp>
+
+#include <gudhi/Flag_complex_edge_collapser.h>
+#include <gudhi/distance_functions.h>
+#include <gudhi/graph_simplicial_complex.h>
+
+#include <iostream>
+#include <tuple>
+#include <vector>
+#include <array>
+#include <cmath>
+
+struct Simplicial_complex {
+ using Vertex_handle = short;
+ using Filtration_value = float;
+};
+
+using Vertex_handle = Simplicial_complex::Vertex_handle;
+using Filtration_value = Simplicial_complex::Filtration_value;
+using Filtered_edge = std::tuple<Vertex_handle, Vertex_handle, Filtration_value>;
+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) {
+ std::cout << "f[" << std::get<0>(filtered_edge) << ", " << std::get<1>(filtered_edge) << "] = "
+ << std::get<2>(filtered_edge) << std::endl;
+ }
+
+ std::cout << "COLLAPSE - keep edges: " << std::endl;
+ auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(filtered_edges);
+
+ std::cout << "AFTER COLLAPSE - Total number of edges: " << remaining_edges.size() << std::endl;
+ BOOST_CHECK(remaining_edges.size() <= filtered_edges.size());
+ for (auto filtered_edge_from_collapse : remaining_edges) {
+ std::cout << "f[" << std::get<0>(filtered_edge_from_collapse) << ", " << std::get<1>(filtered_edge_from_collapse)
+ << "] = " << std::get<2>(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) {
+ std::cout << "f[" << std::get<0>(removed_filtered_edge) << ", " << std::get<1>(removed_filtered_edge) << "] = "
+ << std::get<2>(removed_filtered_edge) << std::endl;
+ // Check each removed edge from collapse is in the input
+ BOOST_CHECK(!find_edge_in_list(removed_filtered_edge, remaining_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.emplace_back(0, 2, 2.);
+ edges.emplace_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.emplace_back(2, 4, 3.);
+ edges.emplace_back(4, 5, 3.);
+ edges.emplace_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.emplace_back(2, 5, 4.);
+ edges.emplace_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.emplace_back(1, 5, 5.);
+ edges.emplace_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 = Gudhi::Proximity_graph<Simplicial_complex>;
+ Proximity_graph proximity_graph = Gudhi::compute_proximity_graph<Simplicial_complex>(point_cloud,
+ threshold,
+ Gudhi::Euclidean_distance());
+
+ auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(
+ boost::adaptors::transform(edges(proximity_graph), [&](auto&&edge){
+ return std::make_tuple(static_cast<Vertex_handle>(source(edge, proximity_graph)),
+ static_cast<Vertex_handle>(target(edge, proximity_graph)),
+ get(Gudhi::edge_filtration_t(), proximity_graph, edge));
+ })
+ );
+
+ BOOST_CHECK(remaining_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 : remaining_edges) {
+ if (std::get<2>(filtered_edge) == 1.)
+ filtration_is_edge_length_nb++;
+ if (std::fabs(std::get<2>(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);
+}
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..1f41bb1f
--- /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 Rips graph defined on a set of input points, using Euclidean distance, and collapses 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.
+* `-i [ --edge-collapse-iterations ]` (default = 1) Number of iterations edge collapse is performed.
+
+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..11ee5871
--- /dev/null
+++ b/src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp
@@ -0,0 +1,152 @@
+/* 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_edge_collapser.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>
+#include <boost/range/adaptor/transformed.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 Filtered_edge = std::tuple<Vertex_handle, Vertex_handle, Filtration_value>;
+using Proximity_graph = Gudhi::Proximity_graph<Simplex_tree>;
+
+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& csv_matrix_file, std::string& filediag,
+ Filtration_value& threshold, int& dim_max, int& p, int& edge_collapse_iter_nb,
+ 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;
+ int edge_collapse_iter_nb;
+ Filtration_value min_persistence;
+
+ program_options(argc, argv, csv_matrix_file, filediag, threshold, dim_max, p, edge_collapse_iter_nb,
+ min_persistence);
+
+ Distance_matrix 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];
+ });
+
+ auto edges_from_graph = boost::adaptors::transform(edges(proximity_graph), [&](auto&&edge){
+ return std::make_tuple(source(edge, proximity_graph),
+ target(edge, proximity_graph),
+ get(Gudhi::edge_filtration_t(), proximity_graph, edge));
+ });
+ std::vector<Filtered_edge> edges_list(edges_from_graph.begin(), edges_from_graph.end());
+ std::vector<Filtered_edge> remaining_edges;
+ for (int iter = 0; iter < edge_collapse_iter_nb; iter++) {
+ auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(edges_list);
+ edges_list = std::move(remaining_edges);
+ remaining_edges.clear();
+ }
+
+ Simplex_tree stree;
+ for (Vertex_handle vertex = 0; static_cast<std::size_t>(vertex) < distances.size(); vertex++) {
+ // insert the vertex with a 0. filtration value just like a Rips
+ stree.insert_simplex({vertex}, 0.);
+ }
+ for (auto filtered_edge : edges_list) {
+ stree.insert_simplex({std::get<0>(filtered_edge), std::get<1>(filtered_edge)}, std::get<2>(filtered_edge));
+ }
+
+ 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, int& edge_collapse_iter_nb,
+ 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.")(
+ "edge-collapse-iterations,i", po::value<int>(&edge_collapse_iter_nb)->default_value(1),
+ "Number of iterations edge collapse is performed.")(
+ "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..0eea742c
--- /dev/null
+++ b/src/Collapse/utilities/point_cloud_edge_collapse_rips_persistence.cpp
@@ -0,0 +1,181 @@
+/* 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_edge_collapser.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 <boost/range/adaptor/transformed.hpp>
+
+#include<utility> // for std::pair
+#include<vector>
+#include<tuple>
+
+// 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 Filtered_edge = std::tuple<Vertex_handle, Vertex_handle, Filtration_value>;
+using Proximity_graph = Gudhi::Proximity_graph<Simplex_tree>;
+
+using Field_Zp = Gudhi::persistent_cohomology::Field_Zp;
+using Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp>;
+
+void program_options(int argc, char* argv[], std::string& off_file_points, std::string& filediag,
+ Filtration_value& threshold, int& dim_max, int& p, int& edge_collapse_iter_nb,
+ 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;
+ int edge_collapse_iter_nb;
+ double min_persistence;
+
+ program_options(argc, argv, off_file_points, filediag, threshold, dim_max, p, edge_collapse_iter_nb, 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;
+
+ 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>(point_vector,
+ threshold,
+ Gudhi::Euclidean_distance());
+
+ if (num_edges(proximity_graph) <= 0) {
+ std::cerr << "Total number of egdes are zero." << std::endl;
+ exit(-1);
+ }
+
+ auto edges_from_graph = boost::adaptors::transform(edges(proximity_graph), [&](auto&&edge){
+ return std::make_tuple(source(edge, proximity_graph),
+ target(edge, proximity_graph),
+ get(Gudhi::edge_filtration_t(), proximity_graph, edge));
+ });
+ std::vector<Filtered_edge> edges_list(edges_from_graph.begin(), edges_from_graph.end());
+
+ std::vector<Filtered_edge> remaining_edges;
+ for (int iter = 0; iter < edge_collapse_iter_nb; iter++) {
+ auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(edges_list);
+ edges_list = std::move(remaining_edges);
+ remaining_edges.clear();
+ }
+
+ Simplex_tree stree;
+ for (Vertex_handle vertex = 0; static_cast<std::size_t>(vertex) < point_vector.size(); vertex++) {
+ // insert the vertex with a 0. filtration value just like a Rips
+ stree.insert_simplex({vertex}, 0.);
+ }
+
+ for (auto filtered_edge : edges_list) {
+ stree.insert_simplex({std::get<0>(filtered_edge), std::get<1>(filtered_edge)}, std::get<2>(filtered_edge));
+ }
+
+ 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, int& edge_collapse_iter_nb,
+ 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.")(
+ "edge-collapse-iterations,i", po::value<int>(&edge_collapse_iter_nb)->default_value(1),
+ "Number of iterations edge collapse is performed.")(
+ "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);
+ }
+}