3.6-git
DUNE for Multi-{Phase, Component, Scale, Physics, ...} flow and transport in porous media
structuredlatticegridcreator.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 * See the file COPYING for full copying permissions. *
5 * *
6 * This program is free software: you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation, either version 3 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
18 *****************************************************************************/
24#ifndef DUMUX_IO_STRUCTURED_LATTICE_GRID_CREATOR_HH
25#define DUMUX_IO_STRUCTURED_LATTICE_GRID_CREATOR_HH
26
27#if HAVE_DUNE_FOAMGRID
28
29#include <vector>
30#include <memory>
31#include <type_traits>
32#include <random>
33
34#include <dune/common/concept.hh>
35#include <dune/common/exceptions.hh>
36#include <dune/grid/common/gridfactory.hh>
37#include <dune/grid/yaspgrid.hh>
38#include <dune/geometry/referenceelements.hh>
39
40// FoamGrid specific includes
41#include <dune/foamgrid/foamgrid.hh>
42#include <dune/foamgrid/dgffoam.hh>
43
47
48namespace Dumux::PoreNetwork {
49
50namespace Concept {
51
56template<class GlobalPosition>
57struct LowDimElementSelector
58{
59 template<class F>
60 auto require(F&& f) -> decltype(
61 bool(f(std::declval<const GlobalPosition&>(), std::declval<const GlobalPosition&>()))
62 );
63};
64} // end namespace Concept
65
70template<int dimWorld>
71class StructuredLatticeGridCreator
72{
73 using GridType = Dune::FoamGrid<1, dimWorld>;
74 using Element = typename GridType::template Codim<0>::Entity;
75 using GlobalPosition = typename Element::Geometry::GlobalCoordinate;
76 using CoordScalar = typename GridType::ctype;
78 using HostGridView = typename HostGrid::LeafGridView;
79 using ReferenceElements = typename Dune::ReferenceElements<CoordScalar, dimWorld>;
80 // grid factory expects unsigned int, will yield compiler warning for std::size_t
81 using VertexIndexPair = std::pair<unsigned int, unsigned int>;
82
83 struct Diagonal
84 {
85 VertexIndexPair localVertexIndices;
86 unsigned int directionNumber;
87 };
88public:
89
90 using Grid = GridType;
91
92 void init(const std::string& paramGroup = "")
93 {
94 auto useAllElements = [](const GlobalPosition& a, const GlobalPosition& b){ return true; };
95 init(useAllElements, paramGroup);
96 }
97
98 template<class LowDimElementSelector,
99 typename std::enable_if_t<Dune::models<Concept::LowDimElementSelector<GlobalPosition>, LowDimElementSelector>(), int> = 0>
100 void init(const LowDimElementSelector& lowDimElementSelector,
101 const std::string& paramGroup = "")
102 {
103 paramGroup_ = paramGroup;
104 removeThroatsOnBoundary_ = getParamFromGroup<std::vector<std::size_t>>(paramGroup, "Grid.RemoveThroatsOnBoundary",
105 std::vector<std::size_t>());
106
107 setElementSelector_(lowDimElementSelector);
108 initRandomNumberGenerator_();
109
110 // create the host grid
111 const auto hostGridInputData = getHostGridInputData_();
113 using HastGridManager = GridManager<HostGrid>;
114 HastGridManager hostGridManager;
115 hostGridManager.init(hostGridInputData.positions, hostGridInputData.cells, hostGridInputData.grading, paramGroup_);
116 hostGridView_ = std::make_unique<HostGridView>(hostGridManager.grid().leafGridView());
117
118 hostGridLowerLeft_ = hostGridInputData.lowerLeft;
119 hostGridUpperRight_ = hostGridInputData.upperRight;
120
121 convertHostGridToLowDimGrid_();
122 }
123
127 void loadBalance()
128 {
129 if (Dune::MPIHelper::getCommunication().size() > 1)
130 gridPtr_->loadBalance();
131 }
132
136 Grid& grid()
137 { return *gridPtr(); }
138
142 std::shared_ptr<Grid>& gridPtr()
143 { return gridPtr_; }
144
145private:
146
147 template<class LowDimElementSelector>
148 void setElementSelector_(const LowDimElementSelector& lowDimElementSelector)
149 {
150 if (!removeThroatsOnBoundary_.empty())
151 {
152 auto finalSelector = [&](const GlobalPosition& a, const GlobalPosition& b)
153 {
154 static const auto lambdaToRemoveThroatsOnBoundary = getLambdaToRemoveThroatsOnBoundary_();
155 using std::min;
156 return min(lambdaToRemoveThroatsOnBoundary(a, b), lowDimElementSelector(a, b));
157 };
158 considerLowDimElement_ = finalSelector;
159 }
160 else
161 considerLowDimElement_ = lowDimElementSelector;
162 }
163
164 void initRandomNumberGenerator_()
165 {
166 directionProbability_ = getDirectionProbability_();
167
168 if (hasParamInGroup(paramGroup_, "Grid.DeletionRandomNumberSeed"))
169 {
170 const auto seed = getParamFromGroup<std::size_t>(paramGroup_, "Grid.DeletionRandomNumberSeed");
171 generator_.seed(seed);
172 }
173 else
174 {
175 std::random_device rd;
176 generator_.seed(rd());
177 }
178 }
179
180 void convertHostGridToLowDimGrid_()
181 {
182 resizeContainers_();
183
184 for (const auto& element : elements(*hostGridView_))
185 {
186 const auto& geometry = element.geometry();
187 const auto& refElement = ReferenceElements::general(geometry.type());
188 treatEdges_(element, refElement, geometry);
189 treatDiagonals_(element, refElement, geometry);
190 }
191 if (elementSet_.empty())
192 DUNE_THROW(Dune::GridError, "Trying to create pore network with zero elements!");
193
194 // make the actual network grid
195 Dune::GridFactory<Grid> factory;
196 for (auto&& vertex : vertexSet_)
197 factory.insertVertex(vertex);
198 for (auto&& element : elementSet_)
199 factory.insertElement(Dune::GeometryTypes::cube(1), {element.first, element.second});
200
201 gridPtr_ = std::shared_ptr<Grid>(factory.createGrid());
202 }
203
204 void resizeContainers_()
205 {
206 vertexInserted_.resize(hostGridView_->size(dimWorld), false);
207 hostVertexIdxToVertexIdx_.resize(hostGridView_->size(dimWorld));
208 edgeInserted_.resize(hostGridView_->size(dimWorld-1), false);
209 faceInserted_.resize(hostGridView_->size(dimWorld-2), false);
210 }
211
212 template<class HostGridElement>
213 bool maybeInsertElementAndVertices_(const HostGridElement& hostGridElement,
214 const typename HostGridElement::Geometry& hostGridElementGeometry,
215 std::size_t localVertexIdx0,
216 std::size_t localVertexIdx1,
217 double directionProbability)
218 {
219 if (neglectElement_(hostGridElementGeometry, localVertexIdx0, localVertexIdx1, directionProbability))
220 return false;
221 else
222 {
223 insertElementAndVertices_(hostGridElement, hostGridElementGeometry, localVertexIdx0, localVertexIdx1, directionProbability);
224 return true;
225 }
226 }
227
228 template<class HostGridElement>
229 void insertElementAndVertices_(const HostGridElement& hostGridElement,
230 const typename HostGridElement::Geometry& hostGridElementGeometry,
231 std::size_t localVertexIdx0,
232 std::size_t localVertexIdx1,
233 double directionProbability)
234 {
235 // get global vertex indices w.r.t. host grid
236 const auto vIdxGlobal0 = hostGridView_->indexSet().subIndex(hostGridElement, localVertexIdx0, dimWorld);
237 const auto vIdxGlobal1 = hostGridView_->indexSet().subIndex(hostGridElement, localVertexIdx1, dimWorld);
238
239 auto getGobalVertexIdx = [&](auto globalIdx, auto localIdx)
240 {
241 if (!vertexInserted_[globalIdx])
242 {
243 vertexInserted_[globalIdx] = true;
244 hostVertexIdxToVertexIdx_[globalIdx] = vertexSet_.size();
245 vertexSet_.push_back(hostGridElementGeometry.corner(localIdx));
246 }
247
248 return hostVertexIdxToVertexIdx_[globalIdx];
249 };
250
251 const auto newVertexIdx0 = getGobalVertexIdx(vIdxGlobal0, localVertexIdx0);
252 const auto newVertexIdx1 = getGobalVertexIdx(vIdxGlobal1, localVertexIdx1);
253 elementSet_.emplace_back(newVertexIdx0, newVertexIdx1);
254 }
255
256 auto getDirectionProbability_() const
257 {
258 std::array<double, numDirections_()> directionProbability;
259 directionProbability.fill(0.0); // do not delete any throats
260
261 // convenience option to delete all diagonal throats
262 if (getParamFromGroup<bool>(paramGroup_, "Grid.RegularLattice", false))
263 {
264 directionProbability.fill(1.0); // delete all throats ...
265 for (int i = 0; i < dimWorld; ++i)
266 directionProbability[i] = 0.0; // ... but not the ones parallel to the main axes
267
268 return directionProbability;
269 }
270
271 // get user input or print out help message explaining correct usage
272 if (hasParamInGroup(paramGroup_, "Grid.DeletionProbability"))
273 {
274 try
275 {
276 directionProbability = getParamFromGroup<decltype(directionProbability)>(paramGroup_, "Grid.DeletionProbability");
277 }
279 {
280 throwDirectionError_();
281 }
282 }
283
284 return directionProbability;
285 }
286
287 void throwDirectionError_() const
288 {
289 // define directions (to be used for user specified anisotropy)
290 Dune::FieldVector<std::string, numDirections_()> directions;
291 if (dimWorld < 3) // 2D
292 {
293 // x, y
294 directions[0] = "1: (1, 0)\n";
295 directions[1] = "2: (0, 1)\n";
296 // diagonals through cell midpoint
297 directions[2] = "3: (1, 1)\n";
298 directions[3] = "4: (1, -1)\n";
299 }
300 else // 3D
301 {
302 // x, y, z
303 directions[0] = " 1: (1, 0, 0)\n";
304 directions[1] = "2: (0, 1, 0)\n";
305 directions[2] = "3: (0, 0, 1)\n";
306 //face diagonals
307 directions[3] = "4: (1, 1, 0)\n";
308 directions[4] = "5: (1, -1, 0)\n";
309 directions[5] = "6: (1, 0, 1)\n";
310 directions[6] = "7: (1, 0, -1)\n";
311 directions[7] = "8: (0, 1, 1)\n";
312 directions[8] = "9: (0, 1, -1)\n";
313 // diagonals through cell midpoint
314 directions[9] = "10: (1, 1, 1)\n";
315 directions[10] = "11: (1, 1, -1)\n";
316 directions[11] = "12: (-1, 1, 1)\n";
317 directions[12] = "13: (-1, -1, 1)\n";
318 }
319 DUNE_THROW(ParameterException, "You must specify probabilities for all directions (" << numDirections_() << ") \n" << directions << "\nExample (3D):\n\n"
320 << "DeletionProbability = 0.5 0.5 0 0 0 0 0 0 0 0 0 0 0 \n\n"
321 << "deletes approximately 50% of all throats in x and y direction, while no deletion in any other direction takes place.\n" );
322 }
323
324 static constexpr std::size_t numDirections_()
325 { return (dimWorld < 3) ? 4 : 13; }
326
327 template<class Geometry>
328 bool neglectElement_(Geometry& hostGridElementGeometry,
329 std::size_t localVertexIdx0,
330 std::size_t localVertexIdx1,
331 double directionProbability)
332 {
333 if (randomNumer_() < directionProbability)
334 return true;
335
336 // TODO Change order of execution: check considerLowDimElement_ before checking the random number
337 // TODO This change will alter the reference solution because randomNumer_() gets called less, therefore the random numbers are different
338 if (!considerLowDimElement_(hostGridElementGeometry.corner(localVertexIdx0), hostGridElementGeometry.corner(localVertexIdx1)))
339 return true;
340
341 return false;
342 }
343
344 auto randomNumer_()
345 { return uniformdist_(generator_); }
346
347 auto getHostGridInputData_() const
348 {
349 struct InputData
350 {
351 std::array<std::vector<int>, dimWorld> cells;
352 std::array<std::vector<CoordScalar>, dimWorld> positions;
353 std::array<std::vector<CoordScalar>, dimWorld> grading;
354 GlobalPosition lowerLeft;
355 GlobalPosition upperRight;
356 } inputData;
357
358 // convenience references
359 auto& cells = inputData.cells;
360 auto& positions = inputData.positions;
361 auto& grading = inputData.grading;
362 auto& lowerLeft = inputData.lowerLeft;
363 auto& upperRight = inputData.upperRight;
364
365 // try to get the pore positions explicitly ...
366 for (int i = 0; i < dimWorld; ++i)
367 positions[i] = getParamFromGroup<std::vector<CoordScalar>>(paramGroup_, "Grid.Positions" + std::to_string(i), std::vector<CoordScalar>{});
368 if (std::none_of(positions.begin(), positions.end(), [&](auto& v){ return v.empty(); }))
369 {
370 for (int i = 0; i < dimWorld; ++i)
371 {
372 cells[i].resize(positions[i].size()-1, 1.0);
373 grading[i].resize(positions[i].size()-1, 1.0);
374 }
375 }
376 else // .. or calculate positions from input data
377 {
378 const auto lowerLeft = getParamFromGroup<GlobalPosition>(paramGroup_, "Grid.LowerLeft", GlobalPosition(0.0));
379 const auto upperRight = getParamFromGroup<GlobalPosition>(paramGroup_, "Grid.UpperRight");
380 const auto numPores = getParamFromGroup<std::vector<unsigned int>>(paramGroup_, "Grid.NumPores");
381 if (numPores.size() != dimWorld)
382 DUNE_THROW(ParameterException, "Grid.NumPores has to be a space-separated list of " << dimWorld << " integers!");
383
384 for (int i = 0; i < dimWorld; ++i)
385 {
386 positions[i].push_back(lowerLeft[i]);
387 positions[i].push_back(upperRight[i]);
388 cells[i].push_back(numPores[i] - 1);
389 grading[i].resize(positions[i].size()-1, 1.0);
390 grading[i] = getParamFromGroup<std::vector<CoordScalar>>(paramGroup_, "Grid.Grading" + std::to_string(i), grading[i]);
391 }
392 }
393
394 // get the lower left position
395 lowerLeft = [&]()
396 {
397 GlobalPosition result;
398 for (int i = 0; i < dimWorld; ++i)
399 result[i] = positions[i][0];
400 return result;
401 }();
402
403 // get the upper right position
404 upperRight = [&]()
405 {
406 GlobalPosition result;
407 for (int i = 0; i < dimWorld; ++i)
408 result[i] = positions[i].back();
409 return result;
410 }();
411
412 return inputData;
413 }
414
415 template<class HostGridElement, class ReferenceElement, class Geometry>
416 void treatEdges_(const HostGridElement& element, const ReferenceElement& refElement, const Geometry& geometry)
417 {
418 // go over all edges and add them as elements if they passed all the tests
419 for (unsigned int edgeIdx = 0; edgeIdx < element.subEntities(dimWorld-1); ++edgeIdx)
420 {
421 const auto vIdxLocal0 = refElement.subEntity(edgeIdx, dimWorld-1, 0, dimWorld);
422 const auto vIdxLocal1 = refElement.subEntity(edgeIdx, dimWorld-1, 1, dimWorld);
423 const auto edgeIdxGlobal = hostGridView_->indexSet().subIndex(element, edgeIdx, dimWorld-1);
424
425 if (edgeInserted_[edgeIdxGlobal])
426 continue;
427 else
428 edgeInserted_[edgeIdxGlobal] = true;
429
430 std::size_t directionNumber = 0;
431
432 if(dimWorld == 2 ) // 2D
433 {
434 if(edgeIdx < 2) // y-direction
435 directionNumber = 0;
436 else // x-direction
437 directionNumber = 1;
438 }
439 else // 3D
440 {
441 if(edgeIdx < 4) // z-direction
442 directionNumber = 2;
443 else if(edgeIdx == 4 || edgeIdx == 5 || edgeIdx == 8 || edgeIdx == 9) // y-direction
444 directionNumber = 1;
445 else if(edgeIdx == 6 || edgeIdx == 7 || edgeIdx == 10 || edgeIdx == 11) // x-direction
446 directionNumber = 0;
447 }
448 maybeInsertElementAndVertices_(element, geometry, vIdxLocal0, vIdxLocal1, directionProbability_[directionNumber]);
449 }
450 }
451
452 template<class HostGridElement, class ReferenceElement, class Geometry>
453 void treatDiagonals_(const HostGridElement& element, const ReferenceElement& refElement, const Geometry& geometry)
454 {
455 if constexpr (dimWorld < 3)
456 treatDiagonalConnections2D_(element, geometry);
457 else
458 treatDiagonalConnections3D_(element, refElement, geometry);
459 }
460
461 template<class HostGridElement, class Geometry>
462 void treatDiagonalConnections2D_(const HostGridElement& element,
463 const Geometry& geometry)
464 {
465 static constexpr std::array<Diagonal, 2> diagonals{ Diagonal{std::make_pair(0, 3), 2},
466 Diagonal{std::make_pair(1, 2), 3} };
467
468 treatIntersectingDiagonals_(element, geometry, diagonals);
469 }
470
471 template<class HostGridElement, class ReferenceElement, class Geometry>
472 void treatDiagonalConnections3D_(const HostGridElement& element,
473 const ReferenceElement& refElement,
474 const Geometry& geometry)
475 {
476 // set diagonals on host grid element faces
477 for (auto faceIdx = 0; faceIdx < element.subEntities(dimWorld-2); ++faceIdx)
478 {
479 const auto faceIdxGlobal = hostGridView_->indexSet().subIndex(element, faceIdx, dimWorld-2);
480 // face already checked?
481 if (faceInserted_[faceIdxGlobal])
482 continue;
483 else
484 faceInserted_[faceIdxGlobal] = true;
485
486 // get local vertex indices
487 std::array<unsigned int, 4> vIdxLocal;
488 for (int i = 0; i < 4; i++)
489 vIdxLocal[i] = refElement.subEntity(faceIdx, dimWorld-2, i, dimWorld);
490
491 const auto directionNumbers = [&]()
492 {
493 if (faceIdx < 2)
494 return std::make_pair<unsigned int, unsigned int>(8,7);
495 else if (faceIdx < 4)
496 return std::make_pair<unsigned int, unsigned int>(6,5);
497 else
498 return std::make_pair<unsigned int, unsigned int>(4,3);
499 }();
500
501 const std::array<Diagonal, 2> diagonals{ Diagonal{std::make_pair(vIdxLocal[1], vIdxLocal[2]), directionNumbers.first},
502 Diagonal{std::make_pair(vIdxLocal[0], vIdxLocal[3]), directionNumbers.second} };
503
504 treatIntersectingDiagonals_(element, geometry, diagonals);
505 }
506
507 static constexpr std::array<Diagonal, 4> diagonals{ Diagonal{std::make_pair(0, 7), 9},
508 Diagonal{std::make_pair(3, 4), 10},
509 Diagonal{std::make_pair(1, 6), 11},
510 Diagonal{std::make_pair(2, 5), 12}, };
511
512 treatIntersectingDiagonals_(element, geometry, diagonals);
513 }
514
515 template<class HostGridElement, class Geometry, class Diagonals>
516 void treatIntersectingDiagonals_(const HostGridElement& element,
517 const Geometry& geometry,
518 const Diagonals& diagonals)
519 {
520 static const bool allowIntersectingDiagonals = getParamFromGroup<bool>(paramGroup_, "Grid.AllowIntersectingDiagonals", true);
521
522 auto treat = [&](const Diagonal& diagonal)
523 {
524 return maybeInsertElementAndVertices_(element, geometry,
525 diagonal.localVertexIndices.first, diagonal.localVertexIndices.second,
526 directionProbability_[diagonal.directionNumber]);
527 };
528
529 if (allowIntersectingDiagonals)
530 {
531 // insert all diagonals
532 for (const auto& diagonal : diagonals)
533 treat(diagonal);
534 }
535 else
536 {
537 auto order = createOrderedList_(diagonals.size());
538 std::shuffle(order.begin(), order.end(), generator_);
539 for (auto i : order)
540 {
541 const auto& diagonal = diagonals[i];
542 const bool inserted = treat(diagonal);
543 if (inserted)
544 return;
545 }
546 }
547 }
548
549 std::vector<std::size_t> createOrderedList_(const std::size_t size) const
550 {
551 std::vector<std::size_t> result(size);
552 std::iota(result.begin(), result.end(), 0);
553 return result;
554 }
555
556 auto getLambdaToRemoveThroatsOnBoundary_() const
557 {
558 auto negletElementsOnBoundary = [&](const GlobalPosition& a, const GlobalPosition& b)
559 {
560 const auto center = 0.5 * (a + b);
561 const auto eps = (a-b).two_norm() * 1e-5;
562
563 bool neglectElement = false;
564 for (auto i : removeThroatsOnBoundary_)
565 {
566 switch(i)
567 {
568 case 0: neglectElement = center[0] < hostGridLowerLeft_[0] + eps; break;
569 case 1: neglectElement = center[0] > hostGridUpperRight_[0] - eps; break;
570 case 2: if constexpr (dimWorld > 1)
571 {
572 neglectElement = center[1] < hostGridLowerLeft_[1] + eps;
573 break;
574 }
575 case 3: if constexpr (dimWorld > 1)
576 {
577 neglectElement = center[1] > hostGridUpperRight_[1] - eps;
578 break;
579 }
580 case 4: if constexpr (dimWorld > 2)
581 {
582 neglectElement = center[2] < hostGridLowerLeft_[2] + eps;
583 break;
584 }
585 case 5: if constexpr (dimWorld > 2)
586 {
587 neglectElement = center[2] > hostGridUpperRight_[2] - eps;
588 break;
589 }
590 }
591
592 if (neglectElement)
593 return false;
594 }
595
596 return true;
597 };
598
599 return negletElementsOnBoundary;
600 }
601
602 std::string paramGroup_;
603 GlobalPosition hostGridLowerLeft_;
604 GlobalPosition hostGridUpperRight_;
605 std::vector<std::size_t> removeThroatsOnBoundary_;
606 std::unique_ptr<const HostGridView> hostGridView_;
607 std::function<bool(const GlobalPosition&, const GlobalPosition&)> considerLowDimElement_;
608
609 std::vector<GlobalPosition> vertexSet_;
610 std::vector<VertexIndexPair> elementSet_;
611
612 std::vector<bool> vertexInserted_;
613 std::vector<std::size_t> hostVertexIdxToVertexIdx_;
614 std::vector<std::size_t> edgeInserted_;
615 std::vector<std::size_t> faceInserted_;
616
617 mutable std::mt19937 generator_;
618 std::uniform_real_distribution<> uniformdist_{0, 1};
619 std::array<double, numDirections_()> directionProbability_;
620
621 std::shared_ptr<Grid> gridPtr_;
622};
623
624} // end namespace Dumux::PoreNetwork
625
626#endif // HAVE_DUNE_FOAMGRID
627
628#endif
Some exceptions thrown in DuMux
The infrastructure to retrieve run-time parameters from Dune::ParameterTrees.
Grid manager specialization for YaspGrid.
Corners::value_type center(const Corners &corners)
The center of a given list of corners.
Definition: center.hh:36
T getParamFromGroup(Args &&... args)
A free function to get a parameter from the parameter tree singleton with a model group.
Definition: parameters.hh:161
bool hasParamInGroup(const std::string &paramGroup, const std::string &param)
Check whether a key exists in the parameter tree with a model group prefix.
Definition: parameters.hh:177
Definition: discretization/porenetwork/fvelementgeometry.hh:34
Exception thrown if a run-time parameter is not specified correctly.
Definition: exceptions.hh:60
Definition: consistentlyorientedgrid.hh:32