Loading...
Searching...
No Matches
Sliced_Wasserstein.h
1/* This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
2 * See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
3 * Author(s): Mathieu Carriere
4 *
5 * Copyright (C) 2018 Inria
6 *
7 * Modification(s):
8 * - 2026/04 Vincent Rouvreau: Use Gudhi::random
9 * - YYYY/MM Author: Description of the modification
10 */
11
12#ifndef SLICED_WASSERSTEIN_H_
13#define SLICED_WASSERSTEIN_H_
14
15// standard include
16#include <vector> // for std::vector<>
17#include <utility> // for std::pair<>, std::move
18#include <algorithm> // for std::sort, std::max, std::merge
19#include <cmath> // for std::abs, std::sqrt
20#include <stdexcept> // for std::invalid_argument
21
22// gudhi include
23#include <gudhi/read_persistence_from_file.h>
25#include <gudhi/Debug_utils.h>
26#include <gudhi/random.h>
27
28namespace Gudhi {
29namespace Persistence_representations {
30
66{
67 public:
77 Sliced_Wasserstein(const Persistence_diagram& diagram, double sigma = 1.0, int approx = 10)
78 : diagram_(diagram), approx_(approx), sigma_(sigma)
79 {
80 _build_rep();
81 }
82
89 double compute_scalar_product(const Sliced_Wasserstein& second) const
90 {
91 GUDHI_CHECK(this->sigma_ == second.sigma_,
92 std::invalid_argument("Error: different sigma values for representations"));
93 return std::exp(-_compute_sliced_wasserstein_distance(second) / (2 * this->sigma_ * this->sigma_));
94 }
95
102 double distance(const Sliced_Wasserstein& second) const
103 {
104 GUDHI_CHECK(this->sigma_ == second.sigma_,
105 std::invalid_argument("Error: different sigma values for representations"));
106 return std::sqrt(this->compute_scalar_product(*this) + second.compute_scalar_product(second) -
107 2 * this->compute_scalar_product(second));
108 }
109
110 private:
111 Persistence_diagram diagram_;
112 int approx_;
113 double sigma_;
114 std::vector<std::vector<double> > projections_, projections_diagonal_;
115
116 // **********************************
117 // Utils.
118 // **********************************
119
120 void _build_rep()
121 {
122 if (approx_ > 0) {
123 double step = pi / this->approx_;
124 int n = diagram_.size();
125
126 for (int i = 0; i < this->approx_; i++) {
127 std::vector<double> l, l_diag;
128 for (int j = 0; j < n; j++) {
129 double px = diagram_[j].first;
130 double py = diagram_[j].second;
131 double proj_diag = (px + py) / 2;
132
133 l.push_back(px * cos(-pi / 2 + i * step) + py * sin(-pi / 2 + i * step));
134 l_diag.push_back(proj_diag * cos(-pi / 2 + i * step) + proj_diag * sin(-pi / 2 + i * step));
135 }
136
137 std::sort(l.begin(), l.end());
138 std::sort(l_diag.begin(), l_diag.end());
139 projections_.push_back(std::move(l));
140 projections_diagonal_.push_back(std::move(l_diag));
141 }
142
143 diagram_.clear();
144 }
145 }
146
147 // Compute the angle formed by two points of a PD
148 double _compute_angle(const Persistence_diagram& diag, int i, int j) const
149 {
150 if (diag[i].second == diag[j].second)
151 return pi / 2;
152 else
153 return atan((diag[j].first - diag[i].first) / (diag[i].second - diag[j].second));
154 }
155
156 // Compute the integral of |cos()| between alpha and beta, valid only if alpha is in [-pi,pi] and beta-alpha is in
157 // [0,pi]
158 double _compute_int_cos(double alpha, double beta) const
159 {
160 double res = 0;
161 if (alpha >= 0 && alpha <= pi) {
162 if (cos(alpha) >= 0) {
163 if (pi / 2 <= beta) {
164 res = 2 - sin(alpha) - sin(beta);
165 } else {
166 res = sin(beta) - sin(alpha);
167 }
168 } else {
169 if (1.5 * pi <= beta) {
170 res = 2 + sin(alpha) + sin(beta);
171 } else {
172 res = sin(alpha) - sin(beta);
173 }
174 }
175 }
176 if (alpha >= -pi && alpha <= 0) {
177 if (cos(alpha) <= 0) {
178 if (-pi / 2 <= beta) {
179 res = 2 + sin(alpha) + sin(beta);
180 } else {
181 res = sin(alpha) - sin(beta);
182 }
183 } else {
184 if (pi / 2 <= beta) {
185 res = 2 - sin(alpha) - sin(beta);
186 } else {
187 res = sin(beta) - sin(alpha);
188 }
189 }
190 }
191 return res;
192 }
193
194 double _compute_int(double theta1,
195 double theta2,
196 int p,
197 int q,
198 const Persistence_diagram& diag1,
199 const Persistence_diagram& diag2) const
200 {
201 double norm = std::sqrt((diag1[p].first - diag2[q].first) * (diag1[p].first - diag2[q].first) +
202 (diag1[p].second - diag2[q].second) * (diag1[p].second - diag2[q].second));
203 double angle1;
204 if (diag1[p].first == diag2[q].first)
205 angle1 = theta1 - pi / 2;
206 else
207 angle1 = theta1 - atan((diag1[p].second - diag2[q].second) / (diag1[p].first - diag2[q].first));
208 double angle2 = angle1 + theta2 - theta1;
209 double integral = _compute_int_cos(angle1, angle2);
210 return norm * integral;
211 }
212
213 // Evaluation of the Sliced Wasserstein Distance between a pair of diagrams.
214 // TODO: decompose it in smaller methods if some modifications have to be done one day?
215 double _compute_sliced_wasserstein_distance(const Sliced_Wasserstein& second) const
216 {
217 GUDHI_CHECK(this->approx_ == second.approx_,
218 std::invalid_argument("Error: different approx values for representations"));
219
220 Persistence_diagram diagram1 = this->diagram_;
221 Persistence_diagram diagram2 = second.diagram_;
222 double sw = 0;
223
224 if (this->approx_ == -1) {
225 // Add projections onto diagonal.
226 int n1, n2;
227 n1 = diagram1.size();
228 n2 = diagram2.size();
229 double min_ordinate = std::numeric_limits<double>::max();
230 double min_abscissa = std::numeric_limits<double>::max();
231 double max_ordinate = std::numeric_limits<double>::lowest();
232 double max_abscissa = std::numeric_limits<double>::lowest();
233 for (int i = 0; i < n2; i++) {
234 min_ordinate = std::min(min_ordinate, diagram2[i].second);
235 min_abscissa = std::min(min_abscissa, diagram2[i].first);
236 max_ordinate = std::max(max_ordinate, diagram2[i].second);
237 max_abscissa = std::max(max_abscissa, diagram2[i].first);
238 diagram1.emplace_back((diagram2[i].first + diagram2[i].second) / 2,
239 (diagram2[i].first + diagram2[i].second) / 2);
240 }
241 for (int i = 0; i < n1; i++) {
242 min_ordinate = std::min(min_ordinate, diagram1[i].second);
243 min_abscissa = std::min(min_abscissa, diagram1[i].first);
244 max_ordinate = std::max(max_ordinate, diagram1[i].second);
245 max_abscissa = std::max(max_abscissa, diagram1[i].first);
246 diagram2.emplace_back((diagram1[i].first + diagram1[i].second) / 2,
247 (diagram1[i].first + diagram1[i].second) / 2);
248 }
249 int num_pts_dgm = diagram1.size();
250
251 // Slightly perturb the points so that the PDs are in generic positions.
252 double epsilon = 0.0001;
253 double thresh_y = (max_ordinate - min_ordinate) * epsilon;
254 double thresh_x = (max_abscissa - min_abscissa) * epsilon;
255 for (int i = 0; i < num_pts_dgm; i++) {
256 double u = Gudhi::random::get_uniform<double>(-1., 1.);
257 diagram1[i].first += u * thresh_x;
258 diagram1[i].second += u * thresh_y;
259 diagram2[i].first += u * thresh_x;
260 diagram2[i].second += u * thresh_y;
261 }
262
263 // Compute all angles in both PDs.
264 std::vector<std::pair<double, std::pair<int, int> > > angles1, angles2;
265 for (int i = 0; i < num_pts_dgm; i++) {
266 for (int j = i + 1; j < num_pts_dgm; j++) {
267 double theta1 = _compute_angle(diagram1, i, j);
268 double theta2 = _compute_angle(diagram2, i, j);
269 angles1.emplace_back(theta1, std::pair<int, int>(i, j));
270 angles2.emplace_back(theta2, std::pair<int, int>(i, j));
271 }
272 }
273
274 // Sort angles.
275 std::sort(angles1.begin(),
276 angles1.end(),
277 [](const std::pair<double, std::pair<int, int> >& p1,
278 const std::pair<double, std::pair<int, int> >& p2) { return (p1.first < p2.first); });
279 std::sort(angles2.begin(),
280 angles2.end(),
281 [](const std::pair<double, std::pair<int, int> >& p1,
282 const std::pair<double, std::pair<int, int> >& p2) { return (p1.first < p2.first); });
283
284 // Initialize orders of the points of both PDs (given by ordinates when theta = -pi/2).
285 std::vector<int> orderp1, orderp2;
286 for (int i = 0; i < num_pts_dgm; i++) {
287 orderp1.push_back(i);
288 orderp2.push_back(i);
289 }
290 std::sort(orderp1.begin(), orderp1.end(), [&](int i, int j) {
291 if (diagram1[i].second != diagram1[j].second)
292 return (diagram1[i].second < diagram1[j].second);
293 else
294 return (diagram1[i].first > diagram1[j].first);
295 });
296 std::sort(orderp2.begin(), orderp2.end(), [&](int i, int j) {
297 if (diagram2[i].second != diagram2[j].second)
298 return (diagram2[i].second < diagram2[j].second);
299 else
300 return (diagram2[i].first > diagram2[j].first);
301 });
302
303 // Find the inverses of the orders.
304 std::vector<int> order1(num_pts_dgm);
305 std::vector<int> order2(num_pts_dgm);
306 for (int i = 0; i < num_pts_dgm; i++) {
307 order1[orderp1[i]] = i;
308 order2[orderp2[i]] = i;
309 }
310
311 // Record all inversions of points in the orders as theta varies along the positive half-disk.
312 std::vector<std::vector<std::pair<int, double> > > anglePerm1(num_pts_dgm);
313 std::vector<std::vector<std::pair<int, double> > > anglePerm2(num_pts_dgm);
314
315 int m1 = angles1.size();
316 for (int i = 0; i < m1; i++) {
317 double theta = angles1[i].first;
318 int p = angles1[i].second.first;
319 int q = angles1[i].second.second;
320 anglePerm1[order1[p]].emplace_back(p, theta);
321 anglePerm1[order1[q]].emplace_back(q, theta);
322 int a = order1[p];
323 int b = order1[q];
324 order1[p] = b;
325 order1[q] = a;
326 }
327
328 int m2 = angles2.size();
329 for (int i = 0; i < m2; i++) {
330 double theta = angles2[i].first;
331 int p = angles2[i].second.first;
332 int q = angles2[i].second.second;
333 anglePerm2[order2[p]].emplace_back(p, theta);
334 anglePerm2[order2[q]].emplace_back(q, theta);
335 int a = order2[p];
336 int b = order2[q];
337 order2[p] = b;
338 order2[q] = a;
339 }
340
341 for (int i = 0; i < num_pts_dgm; i++) {
342 anglePerm1[order1[i]].emplace_back(i, pi / 2);
343 anglePerm2[order2[i]].emplace_back(i, pi / 2);
344 }
345
346 // Compute the SW distance with the list of inversions.
347 for (int i = 0; i < num_pts_dgm; i++) {
348 std::vector<std::pair<int, double> > u, v;
349 u = anglePerm1[i];
350 v = anglePerm2[i];
351 double theta1, theta2;
352 theta1 = -pi / 2;
353 unsigned int ku, kv;
354 ku = 0;
355 kv = 0;
356 theta2 = std::min(u[ku].second, v[kv].second);
357 while (theta1 != pi / 2) {
358 if (diagram1[u[ku].first].first != diagram2[v[kv].first].first ||
359 diagram1[u[ku].first].second != diagram2[v[kv].first].second)
360 if (theta1 != theta2) sw += _compute_int(theta1, theta2, u[ku].first, v[kv].first, diagram1, diagram2);
361 theta1 = theta2;
362 if ((theta2 == u[ku].second) && ku < u.size() - 1) ku++;
363 if ((theta2 == v[kv].second) && kv < v.size() - 1) kv++;
364 theta2 = std::min(u[ku].second, v[kv].second);
365 }
366 }
367 } else {
368 double step = pi / this->approx_;
369 std::vector<double> v1, v2;
370 for (int i = 0; i < this->approx_; i++) {
371 v1.clear();
372 v2.clear();
373 std::merge(this->projections_[i].begin(),
374 this->projections_[i].end(),
375 second.projections_diagonal_[i].begin(),
376 second.projections_diagonal_[i].end(),
377 std::back_inserter(v1));
378 std::merge(second.projections_[i].begin(),
379 second.projections_[i].end(),
380 this->projections_diagonal_[i].begin(),
381 this->projections_diagonal_[i].end(),
382 std::back_inserter(v2));
383
384 int n = v1.size();
385 double f = 0;
386 for (int j = 0; j < n; j++) f += std::abs(v1[j] - v2[j]);
387 sw += f * step;
388 }
389 }
390
391 return sw / pi;
392 }
393
394}; // class Sliced_Wasserstein
395
396} // namespace Persistence_representations
397} // namespace Gudhi
398
399#endif // SLICED_WASSERSTEIN_H_
Sliced_Wasserstein(const Persistence_diagram &diagram, double sigma=1.0, int approx=10)
Sliced Wasserstein kernel constructor.
Definition Sliced_Wasserstein.h:77
double compute_scalar_product(const Sliced_Wasserstein &second) const
Evaluation of the kernel on a pair of diagrams.
Definition Sliced_Wasserstein.h:89
double distance(const Sliced_Wasserstein &second) const
Evaluation of the distance between images of diagrams in the Hilbert space of the kernel.
Definition Sliced_Wasserstein.h:102
This file contain an implementation of some common procedures used in the Persistence_representations...
constexpr double pi
Definition common_persistence_representations.h:45
std::vector< std::pair< double, double > > Persistence_diagram
Definition common_persistence_representations.h:38
Type get_uniform(const Type &min, const Type &max, CustomRandomGenerator &&rng=get_default_random())
Generates a random number in the range [min, max].
Definition random.h:117
Gudhi namespace.
Definition SimplicialComplexForAlpha.h:14