ViennaLS
Loading...
Searching...
No Matches
lsGeometricAdvect.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <hrleSparseIterator.hpp>
4
6#include <lsConcepts.hpp>
7#include <lsDomain.hpp>
8#include <lsExpand.hpp>
9#include <lsFromMesh.hpp>
12#include <lsToDiskMesh.hpp>
13
14#include <vcLogger.hpp>
15#include <vcSmartPointer.hpp>
16#include <vcVectorType.hpp>
17
18#ifndef NDEBUG // if in debug build
19#include <lsCheck.hpp>
20#include <lsToMesh.hpp>
21#include <lsVTKWriter.hpp>
22#endif
23
24namespace viennals {
25
26using namespace viennacore;
27
35template <class T, int D> class GeometricAdvect {
36 using hrleIndexType = viennahrle::IndexType;
37 using hrleCoordType = viennahrle::CoordType;
38
39 SmartPointer<Domain<T, D>> levelSet = nullptr;
40 SmartPointer<Domain<T, D>> maskLevelSet = nullptr;
41 SmartPointer<GeometricAdvectDistribution<T, D>> dist = nullptr;
42 static constexpr T cutoffValue =
43 T(1.) + std::numeric_limits<T>::epsilon() * T(100);
44
45 static void incrementIndices(viennahrle::Index<D> &indices,
46 const viennahrle::Index<D> &min,
47 const viennahrle::Index<D> &max) {
48 int dim = 0;
49 for (; dim < D - 1; ++dim) {
50 if (indices[dim] < max[dim])
51 break;
52 indices[dim] = min[dim];
53 }
54 ++indices[dim];
55 }
56
57 template <class K, class V, template <class...> class MapType, class... Ts>
58 MapType<V, K> inverseTranslator(MapType<K, V, Ts...> &map) {
59 MapType<V, K> inv;
60 std::for_each(map.begin(), map.end(), [&inv](const std::pair<K, V> &p) {
61 inv.insert(std::make_pair(p.second, p.first));
62 });
63 return inv;
64 }
65
66public:
67 GeometricAdvect() = default;
68
69 GeometricAdvect(SmartPointer<Domain<T, D>> passedLevelSet,
70 SmartPointer<GeometricAdvectDistribution<T, D>> passedDist,
71 SmartPointer<Domain<T, D>> passedMaskLevelSet = nullptr)
72 : levelSet(passedLevelSet), maskLevelSet(passedMaskLevelSet),
73 dist(passedDist) {}
74
76 void setLevelSet(SmartPointer<Domain<T, D>> passedLevelSet) {
77 levelSet = passedLevelSet;
78 }
79
83 SmartPointer<GeometricAdvectDistribution<T, D>> passedDist) {
84 dist = passedDist;
85 }
86
90 void setMaskLevelSet(SmartPointer<Domain<T, D>> passedMaskLevelSet) {
91 maskLevelSet = passedMaskLevelSet;
92 }
93
95 void apply() {
96 if (levelSet == nullptr) {
97 Logger::getInstance()
98 .addError("No level set passed to GeometricAdvect. Not Advecting.")
99 .print();
100 return;
101 }
102 if (dist == nullptr) {
103 Logger::getInstance()
104 .addError("No GeometricAdvectDistribution passed to "
105 "GeometricAdvect. Not "
106 "Advecting.")
107 .print();
108 return;
109 }
110
111 // levelSet must have at least a width of 3
112 Expand<T, D>(levelSet, 3).apply();
113
114 if (maskLevelSet != nullptr) {
115 Expand<T, D>(maskLevelSet, 3).apply();
116 }
117
118 dist->prepare(levelSet);
119
120 typedef typename Domain<T, D>::DomainType DomainType;
121
122 auto &domain = levelSet->getDomain();
123
124 auto &grid = levelSet->getGrid();
125 const auto gridDelta = grid.getGridDelta();
126 const bool useSurfacePointId = dist->useSurfacePointId();
127
128 // Extract the original surface as a point cloud of grid
129 // points shifted to the surface (disk mesh)
130 auto surfaceMesh = SmartPointer<Mesh<hrleCoordType>>::New();
131 auto pointIdTranslator =
132 SmartPointer<typename ToDiskMesh<T, D>::TranslatorType>::New();
133 ToDiskMesh<T, D, hrleCoordType>(levelSet, surfaceMesh, pointIdTranslator)
134 .apply();
135 if (!useSurfacePointId)
136 *pointIdTranslator = inverseTranslator(*pointIdTranslator);
137
138 // find bounds of distribution
139 auto distBounds = dist->getBounds();
140
141 // TODO: need to add support for periodic boundary conditions!
142 viennahrle::Index<D> distMin, distMax;
143
144 bool minPointNegative = domain.getDomainSegment(0).definedValues[0] < 0.;
145 bool maxPointNegative =
146 domain.getDomainSegment(domain.getNumberOfSegments() - 1)
147 .definedValues.back() < 0.;
148 bool distIsPositive = true;
149
150 // find bounding box of old domain
151 hrleIndexType bounds[6];
152 domain.getDomainBounds(bounds);
153 viennahrle::Index<D> min, max;
154 for (unsigned i = 0; i < D; ++i) {
155 // translate from coords to indices
156 distMin[i] =
157 distBounds[2 * i] / gridDelta + ((distBounds[2 * i] < 0) ? -2 : 2);
158 distMax[i] = distBounds[2 * i + 1] / gridDelta +
159 ((distBounds[2 * i + 1] < 0) ? -2 : 2);
160 if (distBounds[2 * i] >= 0) {
161 distIsPositive = false;
162 }
163
164 // use the extent of the diskMesh to identify bounding box of new
165 // level set
166 // TODO: respect periodic boundary condition
167 min[i] = surfaceMesh->minimumExtent[i] / gridDelta;
168 // TODO also do the same thing for positive point and etching
169 if (grid.isNegBoundaryInfinite(i) && minPointNegative && distMin[i] < 0) {
170 min[i] -= 2;
171 } else {
172 if (distIsPositive) {
173 min[i] += distMin[i];
174 } else {
175 min[i] -= distMin[i];
176 }
177 }
178 // if calculated index is out of bounds, set the extent
179 // TODO: need to add periodic BNC handling here
180 if (min[i] < grid.getMinGridPoint(i)) {
181 min[i] = grid.getMinGridPoint(i);
182 }
183
184 max[i] = surfaceMesh->maximumExtent[i] / gridDelta;
185 if (grid.isPosBoundaryInfinite(i) && maxPointNegative && distMax[i] > 0) {
186 max[i] += 2;
187 } else {
188 if (distIsPositive) {
189 max[i] += distMax[i];
190 } else {
191 max[i] -= distMax[i];
192 }
193 }
194 if (max[i] > grid.getMaxGridPoint(i)) {
195 max[i] = grid.getMaxGridPoint(i);
196 }
197 }
198
199 // Remove contribute points if they are part of the mask
200 // If a mask is supplied, remove all contribute points which
201 // lie on (or inside) the mask
202 if (maskLevelSet != nullptr) {
203 // Go over all contribute points and see if they are on the mask surface
204 auto &maskDomain = maskLevelSet->getDomain();
205 auto values = surfaceMesh->cellData.getScalarData("LSValues");
206 auto valueIt = values->begin();
207
208 auto newSurfaceMesh = SmartPointer<Mesh<hrleCoordType>>::New();
209 PointData<hrleCoordType>::ScalarDataType newValues;
210 viennahrle::ConstSparseIterator<DomainType> maskIt(maskDomain);
211 for (auto &node : surfaceMesh->getNodes()) {
212 viennahrle::Index<D> index;
213 for (unsigned i = 0; i < D; ++i) {
214 index[i] = std::round(node[i] / gridDelta);
215 }
216 // can do sequential, because surfaceNodes are lexicographically sorted
217 // from lsToDiskMesh
218 maskIt.goToIndicesSequential(index);
219 // if it is a mask point, mark it to maybe use it in new level set
220 if (!maskIt.isDefined() || !(maskIt.getValue() < *valueIt + 1e-5)) {
221 newSurfaceMesh->insertNextNode(node);
222 newValues.push_back(*valueIt);
223 // insert vertex
224 std::array<unsigned, 1> vertex{};
225 vertex[0] = newSurfaceMesh->nodes.size();
226 newSurfaceMesh->insertNextVertex(vertex);
227 }
228 ++valueIt;
229 }
230 newSurfaceMesh->cellData.insertNextScalarData(newValues, "LSValues");
231 // use new mesh as surfaceMesh
232 newSurfaceMesh->minimumExtent = surfaceMesh->minimumExtent;
233 newSurfaceMesh->maximumExtent = surfaceMesh->maximumExtent;
234 surfaceMesh = newSurfaceMesh;
235 }
236
237#ifndef NDEBUG // if in debug build
238 {
239 VIENNACORE_LOG_DEBUG("GeomAdvect: Writing debug meshes");
241 "DEBUG_lsGeomAdvectMesh_contributewoMask.vtp")
242 .apply();
243 auto mesh = SmartPointer<Mesh<T>>::New();
244 if (maskLevelSet != nullptr) {
245 ToMesh<T, D>(maskLevelSet, mesh).apply();
247 "DEBUG_lsGeomAdvectMesh_mask.vtp")
248 .apply();
249 }
250 ToMesh<T, D>(levelSet, mesh).apply();
252 "DEBUG_lsGeomAdvectMesh_initial.vtp")
253 .apply();
254 }
255
256#endif
257
258 const auto &surfaceNodes = surfaceMesh->getNodes();
259
260 // initialize with segmentation for whole range
261 typename viennahrle::Domain<T, D>::IndexPoints segmentation;
262
263 {
264 unsigned long long numPoints = 1;
265 unsigned long long pointsPerDimension[D];
266 for (unsigned i = 0; i < D; ++i) {
267 pointsPerDimension[i] = numPoints;
268 numPoints *= max[i] - min[i];
269 }
270 unsigned long numberOfSegments = domain.getNumberOfSegments();
271 unsigned long long pointsPerSegment = numPoints / numberOfSegments;
272 unsigned long long pointId = 0;
273 for (unsigned i = 0; i < numberOfSegments - 1; ++i) {
274 pointId = pointsPerSegment * (i + 1);
275 viennahrle::Index<D> segmentPoint;
276 for (int j = D - 1; j >= 0; --j) {
277 segmentPoint[j] = pointId / (pointsPerDimension[j]) + min[j];
278 pointId %= pointsPerDimension[j];
279 }
280 segmentation.push_back(segmentPoint);
281 }
282 }
283
284 typedef std::vector<std::pair<viennahrle::Index<D>, T>> PointValueVector;
285 std::vector<PointValueVector> newPoints;
286 newPoints.resize(domain.getNumberOfSegments());
287
288 const T initialDistance = (distIsPositive)
289 ? std::numeric_limits<double>::max()
290 : std::numeric_limits<double>::lowest();
291
292#ifndef NDEBUG
293 {
294 std::ostringstream oss;
295 oss << "GeomAdvect: Min: " << min << ", Max: " << max << std::endl;
296 VIENNACORE_LOG_DEBUG(oss.str());
297 }
298#endif
299// set up multithreading
300#pragma omp parallel for
301 for (unsigned p = 0; p < domain.getNumberOfSegments(); ++p) {
302
303 viennahrle::Index<D> startVector;
304 if (p == 0) {
305 startVector = min;
306 } else {
307 startVector = segmentation[p - 1];
308 incrementIndices(startVector, min, max);
309 }
310
311 viennahrle::Index<D> endVector =
312 (p != static_cast<int>(domain.getNumberOfSegments() - 1))
313 ? segmentation[p]
314 : grid.incrementIndices(max);
315
316 viennahrle::ConstSparseIterator<DomainType> checkIt(levelSet->getDomain(),
317 startVector);
318
319 // Mask iterator for checking whether inside mask or not
320 std::unique_ptr<viennahrle::ConstSparseIterator<DomainType>> maskIt =
321 nullptr;
322 if (maskLevelSet != nullptr) {
323 maskIt = std::make_unique<viennahrle::ConstSparseIterator<DomainType>>(
324 maskLevelSet->getDomain(), startVector);
325 }
326
327 // Iterate through the bounds of new lsDomain lexicographically
328 for (viennahrle::Index<D> currentIndex = startVector;
329 currentIndex <= endVector;
330 incrementIndices(currentIndex, min, max)) {
331 // if point is already full in old level set, skip it
332 checkIt.goToIndicesSequential(currentIndex);
333 T oldValue = checkIt.getValue();
334 // if run is already negative undefined, just ignore the point
335 if (distIsPositive) {
336 if (oldValue < -cutoffValue) {
337 continue;
338 }
339 } else if (oldValue > cutoffValue) {
340 continue;
341 }
342
343 VectorType<hrleCoordType, 3> currentCoords{};
344 VectorType<hrleCoordType, 3> currentDistMin{};
345 VectorType<hrleCoordType, 3> currentDistMax{};
346
347 for (unsigned i = 0; i < D; ++i) {
348 currentCoords[i] = currentIndex[i] * gridDelta;
349
350 currentDistMin[i] = currentIndex[i] - std::abs(distMin[i]);
351 if (currentDistMin[i] < grid.getMinGridPoint(i)) {
352 currentDistMin[i] = grid.getMinGridPoint(i);
353 }
354 currentDistMin[i] *= gridDelta;
355
356 currentDistMax[i] = currentIndex[i] + std::abs(distMax[i]);
357 if (currentDistMin[i] > grid.getMaxGridPoint(i)) {
358 currentDistMin[i] = grid.getMaxGridPoint(i);
359 }
360 currentDistMax[i] *= gridDelta;
361 }
362
363 T distance = initialDistance;
364
365 unsigned long currentPointId = 0;
366 // now check which surface points contribute to currentIndex
367 for (auto surfIt = surfaceNodes.begin(); surfIt != surfaceNodes.end();
368 ++surfIt, ++currentPointId) {
369
370 auto &currentNode = *surfIt;
371
372 // if we are outside min/max go to next index inside
373 {
374 bool outside = false;
375 for (unsigned i = 0; i < D; ++i) {
376 if ((currentNode[i] < currentDistMin[i]) ||
377 (currentNode[i] > currentDistMax[i])) {
378 outside = true;
379 break;
380 }
381 }
382 if (outside) {
383 continue;
384 }
385 }
386
387 // TODO: does this really save time? Try without it.
388 if (!dist->isInside(currentNode, currentCoords, 2 * gridDelta)) {
389 continue;
390 }
391
392 // get filling fraction from distance to dist surface
393 auto pointId = currentPointId;
394 if (!useSurfacePointId) {
395 pointId = pointIdTranslator->find(currentPointId)->second;
396 }
397 T tmpDistance =
398 dist->getSignedDistance(currentNode, currentCoords, pointId) /
399 gridDelta;
400
401 // if cell is far within a distribution, set it filled
402 if (distIsPositive) {
403 if (tmpDistance <= -cutoffValue) {
404 distance = std::numeric_limits<T>::lowest();
405 break;
406 }
407
408 if (tmpDistance < distance) {
409 distance = tmpDistance;
410 }
411 } else {
412 if (tmpDistance >= cutoffValue) {
413 distance = std::numeric_limits<T>::max();
414 break;
415 }
416
417 if (tmpDistance > distance) {
418 distance = tmpDistance;
419 }
420 }
421 }
422
423 // TODO: There are still issues with positive box distributions
424 // if there is a mask used!
425 // if point is part of the mask, keep smaller value
426 if (maskLevelSet != nullptr) {
427 maskIt->goToIndicesSequential(currentIndex);
428
429 // if dist is positive, flip logic of comparison
430 if (distIsPositive ^
431 (std::abs(oldValue - maskIt->getValue()) < 1e-6)) {
432 if (!distIsPositive && std::abs(oldValue) <= cutoffValue) {
433 newPoints[p].push_back(std::make_pair(currentIndex, oldValue));
434 continue;
435 }
436 } else {
437 if (distance != initialDistance) {
438 distance = std::min(maskIt->getValue(), distance);
439 } else if (distIsPositive || oldValue >= 0.) {
440 newPoints[p].push_back(std::make_pair(currentIndex, oldValue));
441 continue;
442 }
443 }
444 }
445
446 if (std::abs(distance) <= cutoffValue) {
447 // avoid using distribution in wrong direction
448 if (distIsPositive && oldValue >= 0.) {
449 newPoints[p].push_back(std::make_pair(currentIndex, distance));
450 } else if (!distIsPositive && oldValue <= 0.) {
451 // if we are etching, need to make sure, we are not inside mask
452 if (maskIt == nullptr || maskIt->getValue() > -cutoffValue) {
453 newPoints[p].push_back(std::make_pair(currentIndex, distance));
454 }
455 } else {
456 // this only happens if distribution is very small, < 2 * gridDelta
457 newPoints[p].push_back(std::make_pair(currentIndex, oldValue));
458 }
459 }
460 }
461 }
462
463 // copy all points into the first vector
464 {
465 unsigned long long numberOfPoints = newPoints[0].size();
466 for (unsigned i = 1; i < domain.getNumberOfSegments(); ++i) {
467 numberOfPoints += newPoints[i].size();
468 }
469 newPoints[0].reserve(numberOfPoints);
470 for (unsigned i = 1; i < domain.getNumberOfSegments(); ++i) {
471 std::move(std::begin(newPoints[i]), std::end(newPoints[i]),
472 std::back_inserter(newPoints[0]));
473 }
474 }
475
476 auto mesh = SmartPointer<Mesh<T>>::New();
477 // output all points directly to mesh
478 {
479 std::vector<T> scalarData;
480 for (auto it = newPoints[0].begin(); it != newPoints[0].end(); ++it) {
481 Vec3D<T> node{};
482 for (unsigned i = 0; i < D; ++i) {
483 node[i] = T((it->first)[i]) * gridDelta;
484 }
485
486 mesh->insertNextNode(node);
487 std::array<unsigned, 1> vertex{};
488 vertex[0] = mesh->vertices.size();
489 mesh->insertNextVertex(vertex);
490 scalarData.push_back(it->second);
491 }
492 mesh->cellData.insertNextScalarData(scalarData, "LSValues");
493 }
494
495#ifndef NDEBUG // if in debug build
496 VIENNACORE_LOG_DEBUG("GeomAdvect: Writing final mesh...");
497 VTKWriter<T>(mesh, FileFormatEnum::VTP, "DEBUG_lsGeomAdvectMesh_final.vtp")
498 .apply();
499#endif
500
501 FromMesh<T, D>(levelSet, mesh).apply();
502
503#ifndef NDEBUG // if in debug build
504 VIENNACORE_LOG_DEBUG("GeomAdvect: Writing final LS...");
505 ToMesh<T, D>(levelSet, mesh).apply();
506 VTKWriter<T>(mesh, FileFormatEnum::VTP, "DEBUG_lsGeomAdvectLS_final.vtp")
507 .apply();
508#endif
509
510 Prune<T, D>(levelSet).apply();
511
512 levelSet->getDomain().segment();
513 levelSet->finalize(1);
514
515 Expand<T, D>(levelSet, 2).apply();
516
517 dist->finalize();
518 }
519};
520
521// add all template specialisations for this class
522PRECOMPILE_PRECISION_DIMENSION(GeometricAdvect)
523
524} // namespace viennals
constexpr int D
Definition Epitaxy.cpp:12
double T
Definition Epitaxy.cpp:13
Class containing all information about the level set, including the dimensions of the domain,...
Definition lsDomain.hpp:27
viennahrle::Domain< T, D > DomainType
Definition lsDomain.hpp:32
DomainType & getDomain()
get const reference to the underlying hrleDomain data structure
Definition lsDomain.hpp:147
Expand()=default
Base class for distributions used by lsGeometricAdvect. All functions are pure virtual and must be im...
Definition lsGeometricAdvectDistributions.hpp:15
void setLevelSet(SmartPointer< Domain< T, D > > passedLevelSet)
Set the levelset which should be advected.
Definition lsGeometricAdvect.hpp:76
void setMaskLevelSet(SmartPointer< Domain< T, D > > passedMaskLevelSet)
Set the levelset, which should be used as a mask. This level set has to be wrapped by the levelset se...
Definition lsGeometricAdvect.hpp:90
GeometricAdvect(SmartPointer< Domain< T, D > > passedLevelSet, SmartPointer< GeometricAdvectDistribution< T, D > > passedDist, SmartPointer< Domain< T, D > > passedMaskLevelSet=nullptr)
Definition lsGeometricAdvect.hpp:69
void apply()
Perform geometrical advection.
Definition lsGeometricAdvect.hpp:95
void setAdvectionDistribution(SmartPointer< GeometricAdvectDistribution< T, D > > passedDist)
Set which advection distribution to use. Must be derived from GeometricAdvectDistribution.
Definition lsGeometricAdvect.hpp:82
Prune()=default
ToMesh()=default
#define PRECOMPILE_PRECISION_DIMENSION(className)
Definition lsPreCompileMacros.hpp:24
Definition lsAdvect.hpp:41
@ VTP
Definition lsFileFormats.hpp:6