version 3.11-dev
Loading...
Searching...
No Matches
triangulation.hh
Go to the documentation of this file.
1// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2// vi: set et ts=4 sw=4 sts=4:
3//
4// SPDX-FileCopyrightText: Copyright © DuMux Project contributors, see AUTHORS.md in root folder
5// SPDX-License-Identifier: GPL-3.0-or-later
6//
14#ifndef DUMUX_GEOMETRY_TRIANGULATION_HH
15#define DUMUX_GEOMETRY_TRIANGULATION_HH
16
17#include <vector>
18#include <array>
19#include <algorithm>
20#include <iterator>
21#include <type_traits>
22#include <tuple>
23
24#include <dune/common/exceptions.hh>
25#include <dune/common/fvector.hh>
26
27#include <dumux/common/math.hh>
30
31namespace Dumux {
33
37
41
44
45#ifndef DOXYGEN
46namespace Detail {
47using DefaultDimPolicies = std::tuple<DelaunayPolicy, MidPointPolicy, ConvexHullPolicy>;
48} // end namespace Detail
49#endif
50
52template<int dim, int dimWorld>
53using DefaultPolicy = std::tuple_element_t<dim-1, Detail::DefaultDimPolicies>;
54
55} // end namespace TriangulationPolicy
56
64template<int dim, int dimWorld, class ctype>
65using Triangulation = std::vector< std::array<Dune::FieldVector<ctype, dimWorld>, dim+1> >;
66
77template< int dim, int dimWorld, class Policy = TriangulationPolicy::DefaultPolicy<dim, dimWorld>,
78 class RandomAccessContainer,
79 std::enable_if_t< std::is_same_v<Policy, TriangulationPolicy::DelaunayPolicy>
80 && dim == 1, int> = 0 >
82triangulate(const RandomAccessContainer& points)
83{
84 using ctype = typename RandomAccessContainer::value_type::value_type;
85 using Point = Dune::FieldVector<ctype, dimWorld>;
86
87 static_assert(std::is_same_v<typename RandomAccessContainer::value_type, Point>,
88 "Triangulation expects Dune::FieldVector as point type");
89
90 if (points.size() == 2)
91 return Triangulation<dim, dimWorld, ctype>({ {points[0], points[1]} });
92
94 assert(points.size() > 1);
95 DUNE_THROW(Dune::NotImplemented, "1d triangulation for point cloud size > 2");
96}
97
110template< int dim, int dimWorld, class Policy = TriangulationPolicy::DefaultPolicy<dim, dimWorld>,
111 class RandomAccessContainer,
112 std::enable_if_t< std::is_same_v<Policy, TriangulationPolicy::MidPointPolicy>
113 && dim == 2, int> = 0 >
115triangulate(const RandomAccessContainer& convexHullPoints)
116{
117 using ctype = typename RandomAccessContainer::value_type::value_type;
118 using Point = Dune::FieldVector<ctype, dimWorld>;
119 using Triangle = std::array<Point, 3>;
120
121 static_assert(std::is_same_v<typename RandomAccessContainer::value_type, Point>,
122 "Triangulation expects Dune::FieldVector as point type");
123
124 if (convexHullPoints.size() < 3)
125 DUNE_THROW(Dune::InvalidStateException, "Try to triangulate point cloud with less than 3 points!");
126
127 if (convexHullPoints.size() == 3)
128 return std::vector<Triangle>(1, {convexHullPoints[0], convexHullPoints[1], convexHullPoints[2]});
129
130 Point midPoint(0.0);
131 for (const auto& p : convexHullPoints)
132 midPoint += p;
133 midPoint /= convexHullPoints.size();
134
135 std::vector<Triangle> triangulation;
136 triangulation.reserve(convexHullPoints.size());
137
138 for (std::size_t i = 0; i < convexHullPoints.size()-1; ++i)
139 triangulation.emplace_back(Triangle{midPoint, convexHullPoints[i], convexHullPoints[i+1]});
140
141 triangulation.emplace_back(Triangle{midPoint, convexHullPoints[convexHullPoints.size()-1], convexHullPoints[0]});
142
143 return triangulation;
144}
145
158template< int dim, int dimWorld, class Policy = TriangulationPolicy::DefaultPolicy<dim, dimWorld>,
159 class RandomAccessContainer,
160 std::enable_if_t< std::is_same_v<Policy, TriangulationPolicy::ConvexHullPolicy>
161 && dim == 2, int> = 0 >
163triangulate(const RandomAccessContainer& points)
164{
165 const auto convexHullPoints = grahamConvexHull<2>(points);
167}
168
179template< int dim, int dimWorld, class Policy = TriangulationPolicy::DefaultPolicy<dim, dimWorld>,
180 class RandomAccessContainer,
181 std::enable_if_t< std::is_same_v<Policy, TriangulationPolicy::ConvexHullPolicy>
182 && dim == 3, int> = 0 >
184triangulate(const RandomAccessContainer& points)
185{
186 using ctype = typename RandomAccessContainer::value_type::value_type;
187 using Point = Dune::FieldVector<ctype, dimWorld>;
188 using Tetrahedron = std::array<Point, 4>;
189
190 static_assert(std::is_same_v<typename RandomAccessContainer::value_type, Point>,
191 "Triangulation expects Dune::FieldVector as point type");
192
193 const auto numPoints = points.size();
194 if (numPoints < 4)
195 DUNE_THROW(Dune::InvalidStateException, "Trying to create 3D triangulation of point cloud with less than 4 points!");
196
197 if (numPoints == 4)
198 return std::vector<Tetrahedron>(1, {points[0], points[1], points[2], points[3]});
199
200 // compute the mid point of the point cloud (not the midpoint of the convex hull but this
201 // should not matter too much for the applications we have in mind here)
202 Point midPoint(0.0);
203 Point lowerLeft(1e100);
204 Point upperRight(-1e100);
205 for (const auto& p : points)
206 {
207 midPoint += p;
208 for (int i = 0; i < dimWorld; ++i)
209 {
210 using std::max; using std::min;
211 lowerLeft[i] = min(p[i], lowerLeft[i]);
212 upperRight[i] = max(p[i], upperRight[i]);
213 }
214 }
215 midPoint /= numPoints;
216
217 auto magnitude = 0.0;
218 using std::max;
219 for (int i = 0; i < dimWorld; ++i)
220 magnitude = max(upperRight[i] - lowerLeft[i], magnitude);
221 const auto eps = 1e-7*magnitude;
222 const auto eps2 = eps*eps;
223 const auto epsDist = 1e-8*magnitude;
224
225 // faces of the convex hull given by the sorted indices of their (coplanar) points
226 std::vector<std::vector<int>> faces;
227 faces.reserve(2*numPoints);
228 std::vector<int> face;
229 face.reserve(numPoints);
230
231 const auto isOnFace = [&](int i, int j, int k)
232 {
233 return std::any_of(faces.begin(), faces.end(), [&](const auto& f)
234 {
235 return std::binary_search(f.begin(), f.end(), i)
236 && std::binary_search(f.begin(), f.end(), j)
237 && std::binary_search(f.begin(), f.end(), k);
238 });
239 };
240
241 // Two faces of a convex polytope share at most an edge, so two faces sharing
242 // three points that are not on a line are the same face, found from triangles
243 // that classified coplanar points differently. Points on a common edge deviate
244 // from it by about the coplanarity tolerance epsDist, far below the threshold used here.
245 const auto isSameFace = [&](const auto& f, const auto& g)
246 {
247 std::vector<int> shared;
248 std::set_intersection(f.begin(), f.end(), g.begin(), g.end(), std::back_inserter(shared));
249 if (shared.size() < 3)
250 return false;
251
252 std::size_t a = 0, b = 1;
253 for (std::size_t m = 0; m < shared.size(); ++m)
254 for (std::size_t n = m+1; n < shared.size(); ++n)
255 if ((points[shared[n]] - points[shared[m]]).two_norm2() > (points[shared[b]] - points[shared[a]]).two_norm2())
256 { a = m; b = n; }
257
258 const auto line = points[shared[b]] - points[shared[a]];
259 const auto lineLength = line.two_norm();
260 return std::any_of(shared.begin(), shared.end(), [&](int c)
261 { return crossProduct(line, points[c] - points[shared[a]]).two_norm() > 1e-6*magnitude*lineLength; });
262 };
263
264 // brute force algorithm: Try all possible triangles and check
265 // if they are triangles of the convex hull. This is achieved by checking if all
266 // other points are in the same half-space (side)
267 // the algorithm is O(n^4), so only do this for very small point clouds
268 for (int i = 0; i < numPoints; ++i)
269 {
270 for (int j = i+1; j < numPoints; ++j)
271 {
272 for (int k = j+1; k < numPoints; ++k)
273 {
274 // this triangle lies on a face that has already been found
275 if (isOnFace(i, j, k))
276 continue;
277
278 const auto pointI = points[i];
279 const auto ab = points[j] - pointI;
280 const auto ac = points[k] - pointI;
281 const auto normal = crossProduct(ab, ac);
282
283 // check if points are colinear and we can't form a triangle
284 // if so, skip this triangle
285 if (normal.two_norm2() < eps2*eps2)
286 continue;
287
288 // check if this triangle ijk is admissible which means
289 // it is on the convex hull (all other points in the cloud are in the same half-space/side)
290 // and collect the points that are coplanar with it
291 face.assign({ i, j, k });
292 const bool isAdmissible = [&]()
293 {
294 int marker = 0; // 0 means undecided side (or coplanar)
295 for (int m = 0; m < numPoints; ++m)
296 {
297 if (m != i && m != j && m != k)
298 {
299 // check scalar product with surface normal to decide side
300 const auto ad = points[m] - pointI;
301 const auto sp = normal*ad;
302
303 // if the sign changes wrt the previous sign, the triangle is not part of the convex hull
304 // sp is a triple product, so divide by the normal to obtain a distance
305 using std::abs; using std::signbit;
306 const bool coplanar = abs(sp) < epsDist*normal.two_norm();
307 int newMarker = coplanar ? 0 : signbit(sp) ? -1 : 1;
308
309 // make decision for a side as soon as the next marker is != 0
310 // keep track of the previous marker
311 if (marker == 0 && newMarker != 0)
312 marker = newMarker;
313
314 // if marker flips, not all points are on one side
315 // zero marker (undecided side / coplanar point) shouldn't abort the process
316 if (newMarker != 0 && marker != newMarker)
317 return false;
318
319 if (coplanar)
320 face.push_back(m);
321 }
322 }
323
324 // we require that not all points are coplanar, so
325 // there will be always at least one non-coplanar point
326 // to check on which side the other points are.
327 // Hence, once we get here, the triangle or coplanar point cluster is part of the convex hull
328 return true;
329 }();
330
331 if (isAdmissible)
332 {
333 std::sort(face.begin(), face.end());
334 faces.push_back(face);
335 }
336 }
337 }
338 }
339
340 for (bool merged = true; merged; )
341 {
342 merged = false;
343 for (std::size_t f = 0; f < faces.size() && !merged; ++f)
344 {
345 for (std::size_t g = f+1; g < faces.size() && !merged; ++g)
346 {
347 if (isSameFace(faces[f], faces[g]))
348 {
349 std::vector<int> united;
350 std::set_union(faces[f].begin(), faces[f].end(), faces[g].begin(), faces[g].end(), std::back_inserter(united));
351 faces[f] = std::move(united);
352 faces.erase(faces.begin() + g);
353 merged = true;
354 }
355 }
356 }
357 }
358
359 // reserve memory conservatively to avoid reallocation
360 std::vector<Tetrahedron> triangulation;
361 triangulation.reserve(numPoints);
362
363 // connect the triangles of each face to the mid point
364 const auto addTetrahedron = [&](const Point& a, const Point& b, const Point& c)
365 {
366 const auto normal = crossProduct(b - a, c - a);
367 using std::signbit;
368 if (signbit(normal*(midPoint - a)))
369 triangulation.emplace_back(Tetrahedron{ a, c, b, midPoint });
370 else
371 triangulation.emplace_back(Tetrahedron{ a, b, c, midPoint });
372 };
373
374 std::vector<Point> facePoints;
375 for (const auto& f : faces)
376 {
377 if (f.size() == 3)
378 addTetrahedron(points[f[0]], points[f[1]], points[f[2]]);
379
380 // a cluster of coplanar points forms one of the faces of the convex hull:
381 // compute its (2d) convex hull first and triangulate
382 else
383 {
384 facePoints.clear();
385 for (int idx : f)
386 facePoints.push_back(points[idx]);
387 for (const auto& triangle : triangulate<2, 3, TriangulationPolicy::ConvexHullPolicy>(facePoints))
388 addTetrahedron(triangle[0], triangle[1], triangle[2]);
389 }
390 }
391
392 // sanity check: if points are not coplanar, then using the mid point policy, we get at least 4 tetrahedrons
393 if (triangulation.size() < 4)
394 DUNE_THROW(Dune::InvalidStateException, "Something went wrong with the triangulation!");
395
396 return triangulation;
397}
398
399} // end namespace Dumux
400
401#endif
A function to compute the convex hull of a point cloud.
Dune::FieldVector< Scalar, 3 > crossProduct(const Dune::FieldVector< Scalar, 3 > &vec1, const Dune::FieldVector< Scalar, 3 > &vec2)
Cross product of two vectors in three-dimensional Euclidean space.
Definition math.hh:671
Triangulation< dim, dimWorld, typename RandomAccessContainer::value_type::value_type > triangulate(const RandomAccessContainer &points)
Triangulate area given points of a convex hull (1d).
Definition triangulation.hh:82
Vector normal(const Vector &v)
Create a vector normal to the given one (v is expected to be non-zero).
Definition normal.hh:26
std::vector< Dune::FieldVector< ctype, dimWorld > > grahamConvexHull(std::vector< Dune::FieldVector< ctype, dimWorld > > &points)
Compute the points making up the convex hull around the given set of unordered points.
Definition grahamconvexhull.hh:186
std::vector< std::array< Dune::FieldVector< ctype, dimWorld >, dim+1 > > Triangulation
The default data type to store triangulations.
Definition triangulation.hh:65
Detect if a point intersects a simplex (including boundary).
Define some often used mathematical functions.
Definition cvfelocalresidual.hh:25
Definition triangulation.hh:32
std::tuple_element_t< dim-1, Detail::DefaultDimPolicies > DefaultPolicy
Default policy for a given dimension.
Definition triangulation.hh:53
Definition adapt.hh:17
Definition triangulation.hh:40
Delaunay-type triangulations.
Definition triangulation.hh:43
Definition triangulation.hh:36