ViennaLS
Loading...
Searching...
No Matches
lsAdvect.hpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <functional>
6#include <limits>
7#include <vector>
8
9#include <hrleSparseIterator.hpp>
10#include <hrleSparseStarIterator.hpp>
11
12#include <vcLogger.hpp>
13#include <vcSmartPointer.hpp>
14
16#include <lsDomain.hpp>
17#include <lsMarkVoidPoints.hpp>
18#include <lsReduce.hpp>
19
20// Spatial discretization schemes
21#include <lsEngquistOsher.hpp>
22#include <lsLaxFriedrichs.hpp>
27#include <lsWENO.hpp>
28
29// Include implementation of time integration schemes
31
32// Velocity accessor
33#include <lsVelocityField.hpp>
34
35// #define DEBUG_LS_ADVECT_HPP
36#ifdef DEBUG_LS_ADVECT_HPP
37#include <lsToMesh.hpp>
38#include <lsVTKWriter.hpp>
39#endif
40
41namespace viennals {
42
43using namespace viennacore;
44
54template <class T, int D> class Advect {
55 using ConstSparseIterator =
56 viennahrle::ConstSparseIterator<typename Domain<T, D>::DomainType>;
57 using hrleIndexType = viennahrle::IndexType;
58
59 // Allow the time integration struct to access private members
61
62 std::vector<SmartPointer<Domain<T, D>>> levelSets;
63 SmartPointer<VelocityField<T>> velocities = nullptr;
66 double timeStepRatio = 0.4999;
67 double dissipationAlpha = 1.0;
68 bool calculateNormalVectors = true;
69 bool ignoreVoids = false;
70 double advectionTime = 0.;
71 bool performOnlySingleStep = false;
72 double advectedTime = 0.;
73 unsigned numberOfTimeSteps = 0;
74 bool saveAdvectionVelocities = false;
75 bool updatePointData = true;
76 bool checkDissipation = true;
77 double integrationCutoff = 0.5;
78 bool adaptiveTimeStepping = false;
79 unsigned adaptiveTimeStepSubdivisions = 20;
80 static constexpr double wrappingLayerEpsilon = 1e-4;
81 SmartPointer<Domain<T, D>> originalLevelSet = nullptr;
82 std::function<bool(SmartPointer<Domain<T, D>>)> velocityUpdateCallback =
83 nullptr;
84
85 // this vector will hold the maximum time step for each point and the
86 // corresponding velocity
87 std::vector<std::vector<std::pair<std::pair<T, T>, T>>> storedRates;
88 double currentTimeStep = -1.;
89
90 VectorType<T, 3> findGlobalAlphas() const {
91
92 auto &topDomain = levelSets.back()->getDomain();
93 auto &grid = levelSets.back()->getGrid();
94
95 const T gridDelta = grid.getGridDelta();
96 const T deltaPos = gridDelta;
97 const T deltaNeg = -gridDelta;
98
99 VectorType<T, 3> finalAlphas = {0., 0., 0.};
100
101#pragma omp parallel num_threads((levelSets.back())->getNumberOfSegments())
102 {
103 VectorType<T, 3> localAlphas = {0., 0., 0.};
104 int p = 0;
105#ifdef _OPENMP
106 p = omp_get_thread_num();
107#endif
108 viennahrle::Index<D> startVector =
109 (p == 0) ? grid.getMinGridPoint()
110 : topDomain.getSegmentation()[p - 1];
111 viennahrle::Index<D> endVector =
112 (p != static_cast<int>(topDomain.getNumberOfSegments() - 1))
113 ? topDomain.getSegmentation()[p]
114 : grid.incrementIndices(grid.getMaxGridPoint());
115
116 // an iterator for each level set
117 std::vector<ConstSparseIterator> iterators;
118 for (auto const &ls : levelSets) {
119 iterators.emplace_back(ls->getDomain());
120 }
121
122 // neighborIterator for the top level set
123 viennahrle::ConstSparseStarIterator<typename Domain<T, D>::DomainType, 1>
124 neighborIterator(topDomain);
125
126 for (ConstSparseIterator it(topDomain, startVector);
127 it.getStartIndices() < endVector; ++it) {
128
129 if (!it.isDefined() || std::abs(it.getValue()) > integrationCutoff)
130 continue;
131
132 const T value = it.getValue();
133 const auto indices = it.getStartIndices();
134
135 // check if there is any other levelset at the same point:
136 // if yes, take the velocity of the lowest levelset
137 for (unsigned lowerLevelSetId = 0; lowerLevelSetId < levelSets.size();
138 ++lowerLevelSetId) {
139 // put iterator to same position as the top levelset
140 iterators[lowerLevelSetId].goToIndicesSequential(indices);
141
142 // if the lower surface is actually outside, i.e. its LS value
143 // is lower or equal
144 if (iterators[lowerLevelSetId].getValue() <=
145 value + wrappingLayerEpsilon) {
146
147 // move neighborIterator to current position
148 neighborIterator.goToIndicesSequential(indices);
149
150 Vec3D<T> coords{};
151 for (unsigned i = 0; i < D; ++i) {
152 coords[i] = indices[i] * gridDelta;
153 }
154
155 Vec3D<T> normal{};
156 T normalModulus = 0.;
157 for (unsigned i = 0; i < D; ++i) {
158 const T phiPos = neighborIterator.getNeighbor(i).getValue();
159 const T phiNeg = neighborIterator.getNeighbor(i + D).getValue();
160
161 T diffPos = (phiPos - value) / deltaPos;
162 T diffNeg = (phiNeg - value) / deltaNeg;
163
164 normal[i] = (diffNeg + diffPos) * 0.5;
165 normalModulus += normal[i] * normal[i];
166 }
167 normalModulus = std::sqrt(normalModulus);
168 for (unsigned i = 0; i < D; ++i)
169 normal[i] /= normalModulus;
170
171 T scaVel = velocities->getScalarVelocity(
172 coords, lowerLevelSetId, normal,
173 neighborIterator.getCenter().getPointId());
174 auto vecVel = velocities->getVectorVelocity(
175 coords, lowerLevelSetId, normal,
176 neighborIterator.getCenter().getPointId());
177
178 for (unsigned i = 0; i < D; ++i) {
179 T tempAlpha = std::abs((scaVel + vecVel[i]) * normal[i]);
180 localAlphas[i] = std::max(localAlphas[i], tempAlpha);
181 }
182
183 // exit material loop
184 break;
185 }
186 }
187 }
188
189#pragma omp critical
190 {
191 for (unsigned i = 0; i < D; ++i) {
192 finalAlphas[i] = std::max(finalAlphas[i], localAlphas[i]);
193 }
194 }
195 } // end of parallel section
196
197 return finalAlphas;
198 }
199
200 // Helper function for linear combination:
201 // target = wTarget * target + wSource * source
202 void combineLevelSets(double wTarget, double wSource) {
203
204 auto &domainDest = levelSets.back()->getDomain();
205 auto &grid = levelSets.back()->getGrid();
206
207#pragma omp parallel num_threads(domainDest.getNumberOfSegments())
208 {
209 int p = 0;
210#ifdef _OPENMP
211 p = omp_get_thread_num();
212#endif
213 auto &segDest = domainDest.getDomainSegment(p);
214
215 viennahrle::Index<D> start = (p == 0)
216 ? grid.getMinGridPoint()
217 : domainDest.getSegmentation()[p - 1];
218 viennahrle::Index<D> end =
219 (p != static_cast<int>(domainDest.getNumberOfSegments()) - 1)
220 ? domainDest.getSegmentation()[p]
221 : grid.incrementIndices(grid.getMaxGridPoint());
222
223 ConstSparseIterator itDest(domainDest, start);
224 ConstSparseIterator itTarget(originalLevelSet->getDomain(), start);
225
226 unsigned definedValueIndex = 0;
227 for (; itDest.getStartIndices() < end; ++itDest) {
228 if (itDest.isDefined()) {
229 itTarget.goToIndicesSequential(itDest.getStartIndices());
230 T valSource = itDest.getValue();
231 T valTarget = itTarget.getValue();
232 segDest.definedValues[definedValueIndex++] =
233 wTarget * valTarget + wSource * valSource;
234 }
235 }
236 }
237 }
238
239 void rebuildLS() {
240 // TODO: this function uses Manhattan distances for renormalisation,
241 // since this is the quickest. For visualisation applications, better
242 // renormalisation is needed, so it might be good to implement
243 // Euler distance renormalisation as an option
244 auto &grid = levelSets.back()->getGrid();
245 auto newlsDomain = SmartPointer<Domain<T, D>>::New(grid);
246 auto &newDomain = newlsDomain->getDomain();
247 auto &domain = levelSets.back()->getDomain();
248
249 // Determine cutoff and width based on discretization scheme to avoid
250 // immediate re-expansion
251 T cutoff = 1.0;
252 int finalWidth = 2;
253 if (spatialScheme ==
255 cutoff = 1.5;
256 finalWidth = 3;
257 }
258
259 newDomain.initialize(domain.getNewSegmentation(),
260 domain.getAllocation() *
261 (2.0 / levelSets.back()->getLevelSetWidth()));
262
263 const bool updateData = updatePointData;
264 // save how data should be transferred to new level set
265 // list of indices into the old pointData vector
266 std::vector<std::vector<unsigned>> newDataSourceIds;
267 if (updateData)
268 newDataSourceIds.resize(newDomain.getNumberOfSegments());
269
270#ifdef DEBUG_LS_ADVECT_HPP
271 {
272 auto mesh = SmartPointer<Mesh<T>>::New();
273 ToMesh<T, D>(levelSets.back(), mesh).apply();
274 VTKWriter<T>(mesh, "Advect_beforeRebuild.vtk").apply();
275 }
276#endif
277
278#pragma omp parallel num_threads(newDomain.getNumberOfSegments())
279 {
280 int p = 0;
281#ifdef _OPENMP
282 p = omp_get_thread_num();
283#endif
284 auto &domainSegment = newDomain.getDomainSegment(p);
285
286 viennahrle::Index<D> startVector =
287 (p == 0) ? grid.getMinGridPoint()
288 : newDomain.getSegmentation()[p - 1];
289
290 viennahrle::Index<D> endVector =
291 (p != static_cast<int>(newDomain.getNumberOfSegments() - 1))
292 ? newDomain.getSegmentation()[p]
293 : grid.incrementIndices(grid.getMaxGridPoint());
294
295 // reserve a bit more to avoid reallocation
296 // would expect number of points to roughly double
297 if (updateData)
298 newDataSourceIds[p].reserve(2.5 * domainSegment.getNumberOfPoints());
299
300 for (viennahrle::SparseStarIterator<typename Domain<T, D>::DomainType, 1>
301 it(domain, startVector);
302 it.getIndices() < endVector; ++it) {
303
304 // if the center is an active grid point
305 // <1.0 since it could have been change by 0.5 max
306 if (std::abs(it.getCenter().getValue()) <= 1.0) {
307
308 int k = 0;
309 for (; k < 2 * D; k++)
310 if (std::signbit(it.getNeighbor(k).getValue() - 1e-7) !=
311 std::signbit(it.getCenter().getValue() + 1e-7))
312 break;
313
314 // if there is at least one neighbor of opposite sign
315 if (k != 2 * D) {
316 if (it.getCenter().getDefinedValue() > 0.5) {
317 int j = 0;
318 for (; j < 2 * D; j++) {
319 if (std::abs(it.getNeighbor(j).getValue()) <= 1.0)
320 if (it.getNeighbor(j).getDefinedValue() < -0.5)
321 break;
322 }
323 if (j == 2 * D) {
324 domainSegment.insertNextDefinedPoint(
325 it.getIndices(), it.getCenter().getDefinedValue());
326 if (updateData)
327 newDataSourceIds[p].push_back(it.getCenter().getPointId());
328 // if there is at least one active grid point, which is < -0.5
329 } else {
330 domainSegment.insertNextDefinedPoint(it.getIndices(), 0.5);
331 if (updateData)
332 newDataSourceIds[p].push_back(it.getNeighbor(j).getPointId());
333 }
334 } else if (it.getCenter().getDefinedValue() < -0.5) {
335 int j = 0;
336 for (; j < 2 * D; j++) {
337 if (std::abs(it.getNeighbor(j).getValue()) <= 1.0)
338 if (it.getNeighbor(j).getDefinedValue() > 0.5)
339 break;
340 }
341
342 if (j == 2 * D) {
343 domainSegment.insertNextDefinedPoint(
344 it.getIndices(), it.getCenter().getDefinedValue());
345 if (updateData)
346 newDataSourceIds[p].push_back(it.getCenter().getPointId());
347 // if there is at least one active grid point, which is > 0.5
348 } else {
349 domainSegment.insertNextDefinedPoint(it.getIndices(), -0.5);
350 if (updateData)
351 newDataSourceIds[p].push_back(it.getNeighbor(j).getPointId());
352 }
353 } else {
354 domainSegment.insertNextDefinedPoint(
355 it.getIndices(), it.getCenter().getDefinedValue());
356 if (updateData)
357 newDataSourceIds[p].push_back(it.getCenter().getPointId());
358 }
359 } else {
360 domainSegment.insertNextUndefinedPoint(
361 it.getIndices(), (it.getCenter().getDefinedValue() < 0)
364 }
365
366 } else { // if the center is not an active grid point
367 if (it.getCenter().getValue() >= 0) {
368 int usedNeighbor = -1;
369 T distance = Domain<T, D>::POS_VALUE;
370 for (int i = 0; i < 2 * D; i++) {
371 T value = it.getNeighbor(i).getValue();
372 if (std::abs(value) <= 1.0 && (value < 0.)) {
373 if (distance > value + 1.0) {
374 distance = value + 1.0;
375 usedNeighbor = i;
376 }
377 }
378 }
379
380 if (distance <= cutoff) {
381 domainSegment.insertNextDefinedPoint(it.getIndices(), distance);
382 if (updateData)
383 newDataSourceIds[p].push_back(
384 it.getNeighbor(usedNeighbor).getPointId());
385 } else {
386 domainSegment.insertNextUndefinedPoint(it.getIndices(),
388 }
389
390 } else {
391 int usedNeighbor = -1;
392 T distance = Domain<T, D>::NEG_VALUE;
393 for (int i = 0; i < 2 * D; i++) {
394 T value = it.getNeighbor(i).getValue();
395 if (std::abs(value) <= 1.0 && (value > 0)) {
396 if (distance < value - 1.0) {
397 // distance = std::max(distance, value - T(1.0));
398 distance = value - 1.0;
399 usedNeighbor = i;
400 }
401 }
402 }
403
404 if (distance >= -cutoff) {
405 domainSegment.insertNextDefinedPoint(it.getIndices(), distance);
406 if (updateData)
407 newDataSourceIds[p].push_back(
408 it.getNeighbor(usedNeighbor).getPointId());
409 } else {
410 domainSegment.insertNextUndefinedPoint(it.getIndices(),
412 }
413 }
414 }
415 }
416 }
417
418 // now copy old data into new level set
419 if (updateData) {
420 auto &pointData = levelSets.back()->getPointData();
421 newlsDomain->getPointData().translateFromMultiData(pointData,
422 newDataSourceIds);
423 }
424
425 newDomain.finalize();
426 newDomain.segment();
427 levelSets.back()->deepCopy(newlsDomain);
428 levelSets.back()->finalize(finalWidth);
429 }
430
435 template <class DiscretizationSchemeType>
436 double integrateTime(DiscretizationSchemeType spatialScheme,
437 double maxTimeStep) {
438
439 auto &topDomain = levelSets.back()->getDomain();
440 auto &grid = levelSets.back()->getGrid();
441
442 typename PointData<T>::ScalarDataType *voidMarkerPointer;
443 if (ignoreVoids) {
444 MarkVoidPoints<T, D>(levelSets.back()).apply();
445 auto &pointData = levelSets.back()->getPointData();
446 voidMarkerPointer =
448 if (voidMarkerPointer == nullptr) {
449 VIENNACORE_LOG_WARNING("Advect: Cannot find void point markers. Not "
450 "ignoring void points.");
451 ignoreVoids = false;
452 }
453 }
454 const bool ignoreVoidPoints = ignoreVoids;
455 const bool useAdaptiveTimeStepping = adaptiveTimeStepping;
456
457 if (!storedRates.empty()) {
458 VIENNACORE_LOG_WARNING("Advect: Overwriting previously stored rates.");
459 }
460
461 storedRates.resize(topDomain.getNumberOfSegments());
462
463#pragma omp parallel num_threads(topDomain.getNumberOfSegments())
464 {
465 int p = 0;
466#ifdef _OPENMP
467 p = omp_get_thread_num();
468#endif
469 viennahrle::Index<D> startVector =
470 (p == 0) ? grid.getMinGridPoint()
471 : topDomain.getSegmentation()[p - 1];
472
473 viennahrle::Index<D> endVector =
474 (p != static_cast<int>(topDomain.getNumberOfSegments() - 1))
475 ? topDomain.getSegmentation()[p]
476 : grid.incrementIndices(grid.getMaxGridPoint());
477
478 double tempMaxTimeStep = maxTimeStep;
479 auto &tempRates = storedRates[p];
480 tempRates.reserve(
481 topDomain.getNumberOfPoints() /
482 static_cast<double>((levelSets.back())->getNumberOfSegments()) +
483 10);
484
485 // an iterator for each level set
486 std::vector<ConstSparseIterator> iterators;
487 for (auto const &ls : levelSets) {
488 iterators.emplace_back(ls->getDomain());
489 }
490
491 DiscretizationSchemeType scheme(spatialScheme);
492
493 for (ConstSparseIterator it(topDomain, startVector);
494 it.getStartIndices() < endVector; ++it) {
495
496 if (!it.isDefined() || std::abs(it.getValue()) > integrationCutoff)
497 continue;
498
499 T value = it.getValue();
500 double maxStepTime = 0;
501 double cfl = timeStepRatio;
502
503 for (int currentLevelSetId = levelSets.size() - 1;
504 currentLevelSetId >= 0; --currentLevelSetId) {
505
506 std::pair<T, T> gradNDissipation;
507
508 if (!(ignoreVoidPoints && (*voidMarkerPointer)[it.getPointId()])) {
509 // check if there is any other levelset at the same point:
510 // if yes, take the velocity of the lowest levelset
511 for (unsigned lowerLevelSetId = 0;
512 lowerLevelSetId < levelSets.size(); ++lowerLevelSetId) {
513 // put iterator to same position as the top levelset
514 iterators[lowerLevelSetId].goToIndicesSequential(
515 it.getStartIndices());
516
517 // if the lower surface is actually outside, i.e. its LS value
518 // is lower or equal
519 if (iterators[lowerLevelSetId].getValue() <=
520 value + wrappingLayerEpsilon) {
521 gradNDissipation =
522 scheme(it.getStartIndices(), lowerLevelSetId);
523 break;
524 }
525 }
526 }
527
528 T velocity = gradNDissipation.first - gradNDissipation.second;
529 if (velocity > 0.) {
530 // Case 1: Growth / Deposition (Velocity > 0)
531 // Limit the time step based on the standard CFL condition.
532 maxStepTime += cfl / velocity;
533 tempRates.push_back(std::make_pair(gradNDissipation,
534 -std::numeric_limits<T>::max()));
535 break;
536 } else if (velocity == 0.) {
537 // Case 2: Static (Velocity == 0)
538 // No time step limit imposed by this point.
539 maxStepTime = std::numeric_limits<T>::max();
540 tempRates.push_back(std::make_pair(gradNDissipation,
541 std::numeric_limits<T>::max()));
542 break;
543 } else {
544 // Case 3: Etching (Velocity < 0)
545 // Retrieve the interface location of the underlying material.
546 T valueBelow;
547 if (currentLevelSetId > 0) {
548 iterators[currentLevelSetId - 1].goToIndicesSequential(
549 it.getStartIndices());
550 valueBelow = iterators[currentLevelSetId - 1].getValue();
551 } else {
552 valueBelow = std::numeric_limits<T>::max();
553 }
554 // Calculate the top material thickness
555 T difference = std::abs(valueBelow - value);
556
557 if (difference >= cfl) {
558 // Sub-case 3a: Standard Advection
559 // Far from interface: Use full CFL time step.
560 maxStepTime -= cfl / velocity;
561 tempRates.push_back(std::make_pair(
562 gradNDissipation, std::numeric_limits<T>::max()));
563 break;
564
565 } else {
566 // Sub-case 3b: Interface Interaction
567 auto adaptiveFactor = 1.0 / adaptiveTimeStepSubdivisions;
568 if (useAdaptiveTimeStepping && difference > 0.2 * cfl) {
569 // Adaptive Sub-stepping:
570 // Approaching boundary: Force small steps to gather
571 // flux statistics and prevent numerical overshoot ("Soft
572 // Landing").
573 maxStepTime -= adaptiveFactor * cfl / velocity;
574 tempRates.push_back(std::make_pair(
575 gradNDissipation, std::numeric_limits<T>::min()));
576 } else {
577 // Terminal Step:
578 // Within tolerance: Snap to boundary, consume budget, and
579 // switch material.
580 tempRates.push_back(
581 std::make_pair(gradNDissipation, valueBelow));
582 cfl -= difference;
583 value = valueBelow;
584 maxStepTime -= difference / velocity;
585 }
586 }
587 }
588 }
589
590 if (maxStepTime < tempMaxTimeStep)
591 tempMaxTimeStep = maxStepTime;
592 }
593
594#pragma omp critical
595 {
596 // If a Lax Friedrichs scheme is selected the time step is
597 // reduced depending on the dissipation coefficients
598 // For Engquist Osher scheme this function is empty.
599 scheme.reduceTimeStepHamiltonJacobi(
600 tempMaxTimeStep, levelSets.back()->getGrid().getGridDelta());
601
602 // set global timestep maximum
603 if (tempMaxTimeStep < maxTimeStep)
604 maxTimeStep = tempMaxTimeStep;
605 }
606 } // end of parallel section
607
608 // maxTimeStep is now the maximum time step possible for all points
609 // and rates are stored in a vector
610 return maxTimeStep;
611 }
612
615 void computeRates(double maxTimeStep = std::numeric_limits<double>::max()) {
616 prepareLS();
617 if (spatialScheme == SpatialSchemeEnum::ENGQUIST_OSHER_1ST_ORDER) {
618 auto is = lsInternal::EngquistOsher<T, D, 1>(levelSets.back(), velocities,
619 calculateNormalVectors);
620 currentTimeStep = integrateTime(is, maxTimeStep);
621 } else if (spatialScheme == SpatialSchemeEnum::ENGQUIST_OSHER_2ND_ORDER) {
622 auto is = lsInternal::EngquistOsher<T, D, 2>(levelSets.back(), velocities,
623 calculateNormalVectors);
624 currentTimeStep = integrateTime(is, maxTimeStep);
625 } else if (spatialScheme == SpatialSchemeEnum::LAX_FRIEDRICHS_1ST_ORDER) {
626 auto alphas = findGlobalAlphas();
627 auto is = lsInternal::LaxFriedrichs<T, D, 1>(levelSets.back(), velocities,
628 dissipationAlpha, alphas,
629 calculateNormalVectors);
630 currentTimeStep = integrateTime(is, maxTimeStep);
631 } else if (spatialScheme == SpatialSchemeEnum::LAX_FRIEDRICHS_2ND_ORDER) {
632 auto alphas = findGlobalAlphas();
633 auto is = lsInternal::LaxFriedrichs<T, D, 2>(levelSets.back(), velocities,
634 dissipationAlpha, alphas,
635 calculateNormalVectors);
636 currentTimeStep = integrateTime(is, maxTimeStep);
637 } else if (spatialScheme ==
640 levelSets.back(), velocities);
641 currentTimeStep = integrateTime(is, maxTimeStep);
642 } else if (spatialScheme ==
645 levelSets.back(), velocities, dissipationAlpha);
646 currentTimeStep = integrateTime(is, maxTimeStep);
647 } else if (spatialScheme ==
650 levelSets.back(), velocities, dissipationAlpha);
651 currentTimeStep = integrateTime(is, maxTimeStep);
652 } else if (spatialScheme ==
655 levelSets.back(), velocities, dissipationAlpha);
656 currentTimeStep = integrateTime(is, maxTimeStep);
657 } else if (spatialScheme ==
660 levelSets.back(), velocities, dissipationAlpha);
661 currentTimeStep = integrateTime(is, maxTimeStep);
662 } else if (spatialScheme ==
665 levelSets.back(), velocities, dissipationAlpha);
666 currentTimeStep = integrateTime(is, maxTimeStep);
667 } else if (spatialScheme == SpatialSchemeEnum::WENO_3RD_ORDER) {
668 // Instantiate WENO with order 3
669 auto is = lsInternal::WENO<T, D, 3>(levelSets.back(), velocities,
670 dissipationAlpha);
671 currentTimeStep = integrateTime(is, maxTimeStep);
672 } else if (spatialScheme == SpatialSchemeEnum::WENO_5TH_ORDER) {
673 // Instantiate WENO with order 5
674 auto is = lsInternal::WENO<T, D, 5>(levelSets.back(), velocities,
675 dissipationAlpha);
676 currentTimeStep = integrateTime(is, maxTimeStep);
677 } else {
678 VIENNACORE_LOG_ERROR("Advect: Discretization scheme not found.");
679 currentTimeStep = -1.;
680 }
681 }
682
683 // Level Sets below are also considered in order to adjust the advection
684 // depth accordingly if there would be a material change.
685 void updateLevelSet(double dt) {
686 if (timeStepRatio >= 0.5) {
687 VIENNACORE_LOG_WARNING(
688 "Integration time step ratio should be smaller than 0.5. "
689 "Advection might fail!");
690 }
691
692 auto &topDomain = levelSets.back()->getDomain();
693
694 assert(dt >= 0. && "No time step set!");
695 assert(storedRates.size() == topDomain.getNumberOfSegments());
696
697 // reduce to one layer thickness and apply new values directly to the
698 // domain segments --> DO NOT CHANGE SEGMENTATION HERE (true parameter)
699 Reduce<T, D>(levelSets.back(), 1, true).apply();
700
701 const bool saveVelocities = saveAdvectionVelocities;
702 std::vector<std::vector<double>> dissipationVectors(
703 levelSets.back()->getNumberOfSegments());
704 std::vector<std::vector<double>> velocityVectors(
705 levelSets.back()->getNumberOfSegments());
706
707 const bool checkDiss = checkDissipation;
708
709#pragma omp parallel num_threads(topDomain.getNumberOfSegments())
710 {
711 int p = 0;
712#ifdef _OPENMP
713 p = omp_get_thread_num();
714#endif
715 auto itRS = storedRates[p].cbegin();
716 auto &segment = topDomain.getDomainSegment(p);
717 const unsigned maxId = segment.getNumberOfPoints();
718
719 if (saveVelocities) {
720 velocityVectors[p].resize(maxId);
721 dissipationVectors[p].resize(maxId);
722 }
723
724 for (unsigned localId = 0; localId < maxId; ++localId) {
725 T &value = segment.definedValues[localId];
726
727 // Skip points that were not part of computeRates (outer layers)
728 if (std::abs(value) > integrationCutoff)
729 continue;
730
731 double time = dt;
732
733 // if there is a change in materials during one time step, deduct
734 // the time taken to advect up to the end of the top material and
735 // set the LS value to the one below
736 auto const [gradient, dissipation] = itRS->first;
737 T velocity = gradient - dissipation;
738 // check if dissipation is too high
739 if (checkDiss && (gradient < 0 && velocity > 0) ||
740 (gradient > 0 && velocity < 0)) {
741 velocity = 0;
742 }
743
744 T rate = time * velocity;
745 while (std::abs(itRS->second - value) < std::abs(rate)) {
746 time -= std::abs((itRS->second - value) / velocity);
747 value = itRS->second;
748 ++itRS; // advance the TempStopRates iterator by one
749
750 // recalculate velocity and rate
751 velocity = itRS->first.first - itRS->first.second;
752 if (checkDiss && (itRS->first.first < 0 && velocity > 0) ||
753 (itRS->first.first > 0 && velocity < 0)) {
754 velocity = 0;
755 }
756 rate = time * velocity;
757 }
758
759 // now deduct the velocity times the time step we take
760 value -= rate;
761
762 if (saveVelocities) {
763 velocityVectors[p][localId] = rate;
764 dissipationVectors[p][localId] = itRS->first.second;
765 }
766
767 // this is run when two materials are close but the velocity is too slow
768 // to actually reach the second material, to get rid of the extra
769 // entry in the TempRatesStop
770 while (std::abs(itRS->second) != std::numeric_limits<T>::max())
771 ++itRS;
772
773 // advance the TempStopRates iterator by one
774 ++itRS;
775 }
776 } // end of parallel section
777
778 if (saveVelocities) {
779 auto &pointData = levelSets.back()->getPointData();
780
781 typename PointData<T>::ScalarDataType vels;
782 typename PointData<T>::ScalarDataType diss;
783
784 for (unsigned i = 0; i < velocityVectors.size(); ++i) {
785 vels.insert(vels.end(),
786 std::make_move_iterator(velocityVectors[i].begin()),
787 std::make_move_iterator(velocityVectors[i].end()));
788 diss.insert(diss.end(),
789 std::make_move_iterator(dissipationVectors[i].begin()),
790 std::make_move_iterator(dissipationVectors[i].end()));
791 }
792 pointData.insertReplaceScalarData(std::move(vels), velocityLabel);
793 pointData.insertReplaceScalarData(std::move(diss), dissipationLabel);
794 }
795
796 // clear the stored rates since surface has changed
797 storedRates.clear();
798 }
799
800 void adjustLowerLayers() {
801 // Adjust all level sets below the advected one
802 if (spatialScheme !=
804 for (unsigned i = 0; i < levelSets.size() - 1; ++i) {
806 levelSets[i], levelSets.back(),
808 .apply();
809 }
810 }
811 }
812
815 double advect(double maxTimeStep) {
816 switch (temporalScheme) {
819 *this, maxTimeStep);
822 *this, maxTimeStep);
824 default:
826 *this, maxTimeStep);
827 }
828 }
829
830public:
831 static constexpr char velocityLabel[] = "AdvectionVelocities";
832 static constexpr char dissipationLabel[] = "Dissipation";
833
834 Advect() = default;
835
836 explicit Advect(SmartPointer<Domain<T, D>> passedlsDomain) {
837 levelSets.push_back(passedlsDomain);
838 }
839
840 Advect(SmartPointer<Domain<T, D>> passedlsDomain,
841 SmartPointer<VelocityField<T>> passedVelocities) {
842 levelSets.push_back(passedlsDomain);
843 velocities = passedVelocities;
844 }
845
846 Advect(std::vector<SmartPointer<Domain<T, D>>> passedlsDomains,
847 SmartPointer<VelocityField<T>> passedVelocities)
848 : levelSets(passedlsDomains) {
849 velocities = passedVelocities;
850 }
851
854 void insertNextLevelSet(SmartPointer<Domain<T, D>> passedlsDomain) {
855 levelSets.push_back(passedlsDomain);
856 }
857
858 void clearLevelSets() { levelSets.clear(); }
859
862 void setVelocityField(SmartPointer<VelocityField<T>> passedVelocities) {
863 velocities = passedVelocities;
864 }
865
871 void setAdvectionTime(double time) { advectionTime = time; }
872
877 void setSingleStep(bool singleStep) { performOnlySingleStep = singleStep; }
878
883 void setTimeStepRatio(const double &cfl) { timeStepRatio = cfl; }
884
889 void setCalculateNormalVectors(bool cnv) { calculateNormalVectors = cnv; }
890
897 void setIgnoreVoids(bool iV) { ignoreVoids = iV; }
898
902 void setAdaptiveTimeStepping(bool aTS = true, unsigned subdivisions = 20) {
903 adaptiveTimeStepping = aTS;
904 if (subdivisions < 1) {
905 VIENNACORE_LOG_WARNING("Advect: Adaptive time stepping subdivisions must "
906 "be at least 1. Setting to 1.");
907 subdivisions = 1;
908 }
909 adaptiveTimeStepSubdivisions = subdivisions;
910 }
911
914 void setSaveAdvectionVelocities(bool sAV) { saveAdvectionVelocities = sAV; }
915
918 double getAdvectedTime() const { return advectedTime; }
919
921 double getCurrentTimeStep() const { return currentTimeStep; }
922
924 unsigned getNumberOfTimeSteps() const { return numberOfTimeSteps; }
925
927 double getTimeStepRatio() const { return timeStepRatio; }
928
930 bool getCalculateNormalVectors() const { return calculateNormalVectors; }
931
934 void setSpatialScheme(SpatialSchemeEnum scheme) { spatialScheme = scheme; }
935
936 // Deprecated and will be removed in future versions:
937 // use setSpatialScheme instead
938 [[deprecated("Use setSpatialScheme instead")]] void
939 setIntegrationScheme(IntegrationSchemeEnum scheme) {
940 VIENNACORE_LOG_WARNING(
941 "Advect::setIntegrationScheme is deprecated and will be removed in "
942 "future versions. Use setSpatialScheme instead.");
943 spatialScheme = scheme;
944 }
945
947 void setTemporalScheme(TemporalSchemeEnum scheme) { temporalScheme = scheme; }
948
953 void setDissipationAlpha(const double &a) { dissipationAlpha = a; }
954
955 // Sets the velocity to 0 if the dissipation is too high
956 void setCheckDissipation(bool check) { checkDissipation = check; }
957
960 void setUpdatePointData(bool update) { updatePointData = update; }
961
965 std::function<bool(SmartPointer<Domain<T, D>>)> callback) {
966 velocityUpdateCallback = callback;
967 }
968
969 // Prepare the levelset for advection, based on the provided spatial
970 // discretization scheme.
971 void prepareLS() {
972 // check whether a level set and velocities have been given
973 if (levelSets.empty()) {
974 VIENNACORE_LOG_ERROR("No level sets passed to Advect.");
975 return;
976 }
977
978 if (spatialScheme == SpatialSchemeEnum::ENGQUIST_OSHER_1ST_ORDER) {
980 } else if (spatialScheme == SpatialSchemeEnum::ENGQUIST_OSHER_2ND_ORDER) {
982 } else if (spatialScheme == SpatialSchemeEnum::LAX_FRIEDRICHS_1ST_ORDER) {
984 } else if (spatialScheme == SpatialSchemeEnum::LAX_FRIEDRICHS_2ND_ORDER) {
986 } else if (spatialScheme ==
989 levelSets.back());
990 } else if (spatialScheme ==
993 } else if (spatialScheme ==
996 } else if (spatialScheme ==
999 } else if (spatialScheme ==
1002 } else if (spatialScheme ==
1005 levelSets.back());
1006 } else if (spatialScheme == SpatialSchemeEnum::WENO_3RD_ORDER) {
1007 lsInternal::WENO<T, D, 3>::prepareLS(levelSets.back());
1008 } else if (spatialScheme == SpatialSchemeEnum::WENO_5TH_ORDER) {
1009 lsInternal::WENO<T, D, 5>::prepareLS(levelSets.back());
1010 } else {
1011 VIENNACORE_LOG_ERROR("Advect: Discretization scheme not found.");
1012 }
1013 }
1014
1015 void apply() {
1016 // check whether a level set and velocities have been given
1017 if (levelSets.empty()) {
1018 VIENNACORE_LOG_ERROR("No level sets passed to Advect. Not advecting.");
1019 return;
1020 }
1021 if (velocities == nullptr) {
1022 VIENNACORE_LOG_ERROR(
1023 "No velocity field passed to Advect. Not advecting.");
1024 return;
1025 }
1026
1027 if (advectionTime == 0.) {
1028 advectedTime = advect(std::numeric_limits<double>::max());
1029 numberOfTimeSteps = 1;
1030 } else {
1031 double currentTime = 0.0;
1032 numberOfTimeSteps = 0;
1033 while (currentTime < advectionTime) {
1034 currentTime += advect(advectionTime - currentTime);
1035 ++numberOfTimeSteps;
1036 if (performOnlySingleStep)
1037 break;
1038 }
1039 advectedTime = currentTime;
1040 }
1041 }
1042};
1043
1044// add all template specializations for this class
1046
1047} // namespace viennals
constexpr int D
Definition Epitaxy.cpp:11
double T
Definition Epitaxy.cpp:12
Engquist-Osher spatial discretization scheme based on the upwind spatial discretization scheme....
Definition lsEngquistOsher.hpp:18
static void prepareLS(SmartPointer< viennals::Domain< T, D > > passedlsDomain)
Definition lsEngquistOsher.hpp:28
Lax Friedrichs spatial discretization scheme with constant alpha value for dissipation....
Definition lsLaxFriedrichs.hpp:19
static void prepareLS(SmartPointer< viennals::Domain< T, D > > passedlsDomain)
Definition lsLaxFriedrichs.hpp:32
Lax Friedrichs spatial discretization scheme, which uses alpha values provided by the user in getDiss...
Definition lsLocalLaxFriedrichsAnalytical.hpp:20
static void prepareLS(SmartPointer< viennals::Domain< T, D > > passedlsDomain)
Definition lsLocalLaxFriedrichsAnalytical.hpp:48
Lax Friedrichs spatial discretization scheme, which uses a first neighbour stencil to calculate the a...
Definition lsLocalLaxFriedrichs.hpp:20
static void prepareLS(SmartPointer< viennals::Domain< T, D > > passedlsDomain)
Definition lsLocalLaxFriedrichs.hpp:49
Lax Friedrichs spatial discretization scheme, which considers only the current point for alpha calcul...
Definition lsLocalLocalLaxFriedrichs.hpp:18
static void prepareLS(SmartPointer< viennals::Domain< T, D > > passedlsDomain)
Definition lsLocalLocalLaxFriedrichs.hpp:29
Stencil Local Lax Friedrichs Discretization Scheme. It uses a stencil of order around active points,...
Definition lsStencilLocalLaxFriedrichsScalar.hpp:33
static void prepareLS(LevelSetType passedlsDomain)
Definition lsStencilLocalLaxFriedrichsScalar.hpp:197
Weighted Essentially Non-Oscillatory (WENO) scheme. This kernel acts as the grid-interface for the ma...
Definition lsWENO.hpp:20
static void prepareLS(SmartPointer< viennals::Domain< T, D > > passedlsDomain)
Definition lsWENO.hpp:42
void setVelocityField(SmartPointer< VelocityField< T > > passedVelocities)
Set the velocity field used for advection. This should be a concrete implementation of lsVelocityFiel...
Definition lsAdvect.hpp:862
static constexpr char velocityLabel[]
Definition lsAdvect.hpp:831
void insertNextLevelSet(SmartPointer< Domain< T, D > > passedlsDomain)
Pushes the passed level set to the back of the list of level sets used for advection.
Definition lsAdvect.hpp:854
void setVelocityUpdateCallback(std::function< bool(SmartPointer< Domain< T, D > >)> callback)
Set a callback function that is called after the level set has been updated during intermediate time ...
Definition lsAdvect.hpp:964
void setUpdatePointData(bool update)
Set whether the point data in the old LS should be translated to the advected LS. Defaults to true.
Definition lsAdvect.hpp:960
void setSpatialScheme(SpatialSchemeEnum scheme)
Set which spatial discretization scheme should be used out of the ones specified in SpatialSchemeEnum...
Definition lsAdvect.hpp:934
bool getCalculateNormalVectors() const
Get whether normal vectors were calculated.
Definition lsAdvect.hpp:930
void setIgnoreVoids(bool iV)
Set whether level set values, which are not part of the "top" geometrically connected part of values,...
Definition lsAdvect.hpp:897
Advect()=default
void clearLevelSets()
Definition lsAdvect.hpp:858
void setCalculateNormalVectors(bool cnv)
Set whether normal vectors should be calculated at each level set point. Defaults to true....
Definition lsAdvect.hpp:889
void apply()
Definition lsAdvect.hpp:1015
void setSingleStep(bool singleStep)
If set to true, only a single advection step will be performed, even if the advection time set with s...
Definition lsAdvect.hpp:877
void prepareLS()
Definition lsAdvect.hpp:971
double getAdvectedTime() const
Get by how much the physical time was advanced during the last apply() call.
Definition lsAdvect.hpp:918
void setTemporalScheme(TemporalSchemeEnum scheme)
Set which time integration scheme should be used.
Definition lsAdvect.hpp:947
void setDissipationAlpha(const double &a)
Set the alpha dissipation coefficient. For lsLaxFriedrichs, this is used as the alpha value....
Definition lsAdvect.hpp:953
void setCheckDissipation(bool check)
Definition lsAdvect.hpp:956
Advect(std::vector< SmartPointer< Domain< T, D > > > passedlsDomains, SmartPointer< VelocityField< T > > passedVelocities)
Definition lsAdvect.hpp:846
void setIntegrationScheme(IntegrationSchemeEnum scheme)
Definition lsAdvect.hpp:939
double getCurrentTimeStep() const
Return the last applied time step.
Definition lsAdvect.hpp:921
void setAdvectionTime(double time)
Set the time until when the level set should be advected. If this takes more than one advection step,...
Definition lsAdvect.hpp:871
unsigned getNumberOfTimeSteps() const
Get how many advection steps were performed during the last apply() call.
Definition lsAdvect.hpp:924
void setAdaptiveTimeStepping(bool aTS=true, unsigned subdivisions=20)
Set whether adaptive time stepping should be used when approaching material boundaries during etching...
Definition lsAdvect.hpp:902
void setTimeStepRatio(const double &cfl)
Set the CFL condition to use during advection. The CFL condition sets the maximum distance a surface ...
Definition lsAdvect.hpp:883
Advect(SmartPointer< Domain< T, D > > passedlsDomain)
Definition lsAdvect.hpp:836
Advect(SmartPointer< Domain< T, D > > passedlsDomain, SmartPointer< VelocityField< T > > passedVelocities)
Definition lsAdvect.hpp:840
double getTimeStepRatio() const
Get the value of the CFL number.
Definition lsAdvect.hpp:927
void setSaveAdvectionVelocities(bool sAV)
Set whether the velocities applied to each point should be saved in the level set for debug purposes.
Definition lsAdvect.hpp:914
static constexpr char dissipationLabel[]
Definition lsAdvect.hpp:832
This class is used to perform boolean operations on two level sets and write the resulting level set ...
Definition lsBooleanOperation.hpp:43
void apply()
Perform operation.
Definition lsBooleanOperation.hpp:316
Class containing all information about the level set, including the dimensions of the domain,...
Definition lsDomain.hpp:28
viennahrle::Domain< T, D > DomainType
Definition lsDomain.hpp:33
static constexpr T NEG_VALUE
Definition lsDomain.hpp:53
static constexpr T POS_VALUE
Definition lsDomain.hpp:52
This class is used to mark points of the level set which are enclosed in a void.
Definition lsMarkVoidPoints.hpp:28
void apply()
Definition lsMarkVoidPoints.hpp:154
static constexpr char voidPointLabel[]
Definition lsMarkVoidPoints.hpp:86
std::vector< T > ScalarDataType
Definition lsPointData.hpp:24
ScalarDataType * getScalarData(int index)
Definition lsPointData.hpp:134
Reduce the level set size to the specified width. This means all level set points with value <= 0....
Definition lsReduce.hpp:14
void apply()
Reduces the leveleSet to the specified number of layers. The largest value in the levelset is thus wi...
Definition lsReduce.hpp:55
Extract the regular grid, on which the level set values are defined, to an explicit Mesh<>....
Definition lsToMesh.hpp:19
void apply()
Definition lsToMesh.hpp:49
Class handling the output of an Mesh<> to VTK file types.
Definition lsVTKWriter.hpp:33
void apply()
Definition lsVTKWriter.hpp:136
Abstract class defining the interface for the velocity field used during advection using lsAdvect.
Definition lsVelocityField.hpp:11
#define PRECOMPILE_PRECISION_DIMENSION(className)
Definition lsPreCompileMacros.hpp:24
Definition lsAdvect.hpp:41
SpatialSchemeEnum
Enumeration for the different spatial discretization schemes used by the advection kernel.
Definition lsAdvectIntegrationSchemes.hpp:10
@ LOCAL_LOCAL_LAX_FRIEDRICHS_2ND_ORDER
Definition lsAdvectIntegrationSchemes.hpp:17
@ STENCIL_LOCAL_LAX_FRIEDRICHS_1ST_ORDER
Definition lsAdvectIntegrationSchemes.hpp:20
@ LOCAL_LOCAL_LAX_FRIEDRICHS_1ST_ORDER
Definition lsAdvectIntegrationSchemes.hpp:16
@ LAX_FRIEDRICHS_2ND_ORDER
Definition lsAdvectIntegrationSchemes.hpp:14
@ LOCAL_LAX_FRIEDRICHS_1ST_ORDER
Definition lsAdvectIntegrationSchemes.hpp:18
@ ENGQUIST_OSHER_2ND_ORDER
Definition lsAdvectIntegrationSchemes.hpp:12
@ LAX_FRIEDRICHS_1ST_ORDER
Definition lsAdvectIntegrationSchemes.hpp:13
@ LOCAL_LAX_FRIEDRICHS_2ND_ORDER
Definition lsAdvectIntegrationSchemes.hpp:19
@ WENO_3RD_ORDER
Definition lsAdvectIntegrationSchemes.hpp:21
@ ENGQUIST_OSHER_1ST_ORDER
Definition lsAdvectIntegrationSchemes.hpp:11
@ LOCAL_LAX_FRIEDRICHS_ANALYTICAL_1ST_ORDER
Definition lsAdvectIntegrationSchemes.hpp:15
@ WENO_5TH_ORDER
Definition lsAdvectIntegrationSchemes.hpp:22
TemporalSchemeEnum
Enumeration for the different time integration schemes used to select the advection kernel.
Definition lsAdvectIntegrationSchemes.hpp:31
@ RUNGE_KUTTA_2ND_ORDER
Definition lsAdvectIntegrationSchemes.hpp:33
@ RUNGE_KUTTA_3RD_ORDER
Definition lsAdvectIntegrationSchemes.hpp:34
@ FORWARD_EULER
Definition lsAdvectIntegrationSchemes.hpp:32
@ INTERSECT
Definition lsBooleanOperation.hpp:26
Definition lsAdvectIntegrationSchemes.hpp:43
static double evolveRungeKutta3(AdvectType &kernel, double maxTimeStep)
Definition lsAdvectIntegrationSchemes.hpp:102
static double evolveForwardEuler(AdvectType &kernel, double maxTimeStep)
Definition lsAdvectIntegrationSchemes.hpp:46
static double evolveRungeKutta2(AdvectType &kernel, double maxTimeStep)
Definition lsAdvectIntegrationSchemes.hpp:59