BlockForest.cpp 119 KB
Newer Older
1
2
//======================================================================================================================
//
3
//  This file is part of waLBerla. waLBerla is free software: you can
4
//  redistribute it and/or modify it under the terms of the GNU General Public
5
//  License as published by the Free Software Foundation, either version 3 of
6
//  the License, or (at your option) any later version.
7
8
9
10
//
//  waLBerla is distributed in the hope that it will be useful, but WITHOUT
//  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11
//  for more details.
12
//
13
14
15
16
17
18
19
20
21
22
//  You should have received a copy of the GNU General Public License along
//  with waLBerla (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>.
//
//! \file BlockForest.cpp
//! \ingroup blockforest
//! \author Florian Schornbaum <florian.schornbaum@fau.de>
//
//======================================================================================================================

#include "BlockForest.h"
23
#include "BlockForestFile.h"
24
25
26
27
28
29
30
31
32
33
34
35
#include "BlockNeighborhoodSection.h"
#include "SetupBlockForest.h"
#include "core/Abort.h"
#include "core/EndianIndependentSerialization.h"
#include "core/debug/CheckFunctions.h"
#include "core/mpi/BufferSystem.h"
#include "core/mpi/Gatherv.h"
#include "core/mpi/Reduce.h"
#include "core/mpi/SetReduction.h"
#include "core/mpi/MPIManager.h"

#include <fstream>
36
#include <memory>
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#include <set>
#include <stack>
#include <utility>


namespace walberla {
namespace blockforest {



bool BlockForest::BlockInformation::operator==( const BlockInformation & rhs ) const
{
   if( nodes_.size() != rhs.nodes_.size() )
      return false;

   for( uint_t i = 0; i != nodes_.size(); ++i ) {
      if( !(nodes_[i]) ) {
         if( rhs.nodes_[i] )
            return false;
      }
      else if( !(rhs.nodes_[i]) || *(nodes_[i]) != *(rhs.nodes_[i]) )
         return false;
   }

   return true;
}



void BlockForest::BlockInformation::getAllBlocks( std::vector< shared_ptr< IBlockID > > & blocks ) const
{
   const uint_t treeIdMarker = uintPow2( forest_.getTreeIdDigits() - 1 );

   for( uint_t i = 0; i != nodes_.size(); ++i )
   {
      if( !(nodes_[i]) )
         continue;

      std::stack< std::pair< const Node *, BlockID > > stack;

      stack.push( std::make_pair( nodes_[i].get(), BlockID( i, treeIdMarker ) ) );

      while( !stack.empty() ) {

         std::pair< const Node *, BlockID > node = stack.top();
         stack.pop();

         WALBERLA_ASSERT_NOT_NULLPTR( node.first );

         if( !node.first->children_.empty() ) {
            for( uint_t c = 8; c-- != 0; )
               stack.push( std::make_pair( node.first->children_[c].get(), BlockID( node.second, c ) ) );
         }
         else {
            blocks.push_back( make_shared< BlockID >( node.second ) );
         }
      }
   }
}



bool BlockForest::BlockInformation::getId( BlockID & id, const real_t x, const real_t y, const real_t z ) const
{
   const AABB & domain = forest_.getDomain();

   if( nodes_.empty() || !domain.contains(x,y,z) )
      return false;

   const real_t rootBlockXSize = forest_.getRootBlockXSize();
   const real_t rootBlockYSize = forest_.getRootBlockYSize();
   const real_t rootBlockZSize = forest_.getRootBlockZSize();

   uint_t xi = static_cast< uint_t >( ( x - domain.xMin() ) / rootBlockXSize );
   uint_t yi = static_cast< uint_t >( ( y - domain.yMin() ) / rootBlockYSize );
   uint_t zi = static_cast< uint_t >( ( z - domain.zMin() ) / rootBlockZSize );

   if( xi >= forest_.getXSize() ) xi = forest_.getXSize() - 1; // shouldn't happen, ...
   if( yi >= forest_.getYSize() ) yi = forest_.getYSize() - 1; // ... but might happen due to ...
   if( zi >= forest_.getZSize() ) zi = forest_.getZSize() - 1; // ... floating point inaccuracy?

   const uint_t index = zi * forest_.getYSize() * forest_.getXSize() + yi * forest_.getXSize() + xi;

   id.clear();
   id.init( index, uint_c(1) << ( forest_.getTreeIdDigits() - 1 ) );

   auto node = nodes_[index];

   if( !node )
      return false;

   AABB aabb = AABB::createFromMinMaxCorner( domain.xMin() + static_cast< real_t >( xi ) * rootBlockXSize,
                                             domain.yMin() + static_cast< real_t >( yi ) * rootBlockYSize,
                                             domain.zMin() + static_cast< real_t >( zi ) * rootBlockZSize,
                                             ( xi+1 == forest_.getXSize() ) ? domain.xMax() : domain.xMin() + static_cast< real_t >( xi+1 ) * rootBlockXSize,
                                             ( yi+1 == forest_.getYSize() ) ? domain.yMax() : domain.yMin() + static_cast< real_t >( yi+1 ) * rootBlockYSize,
                                             ( zi+1 == forest_.getZSize() ) ? domain.zMax() : domain.zMin() + static_cast< real_t >( zi+1 ) * rootBlockZSize );
   WALBERLA_ASSERT( aabb.contains(x,y,z) );

   while( !node->children_.empty() ) {

      uint_t branchId = 0;

      const real_t xMid = ( aabb.xMin() + aabb.xMax() ) / real_c(2);
      const real_t yMid = ( aabb.yMin() + aabb.yMax() ) / real_c(2);
      const real_t zMid = ( aabb.zMin() + aabb.zMax() ) / real_c(2);

      if( x >= xMid ) ++branchId;
      if( y >= yMid ) branchId += 2;
      if( z >= zMid ) branchId += 4;

      aabb.initMinMaxCorner( ( branchId & 1 ) ? xMid : aabb.xMin(), ( branchId & 2 ) ? yMid : aabb.yMin(), ( branchId & 4 ) ? zMid : aabb.zMin(),
                             ( branchId & 1 ) ? aabb.xMax() : xMid, ( branchId & 2 ) ? aabb.yMax() : yMid, ( branchId & 4 ) ? aabb.zMax() : zMid );

      WALBERLA_ASSERT( aabb.contains(x,y,z) );
      WALBERLA_ASSERT_LESS( branchId, node->children_.size() );
      WALBERLA_ASSERT_NOT_NULLPTR( node->children_[ branchId ] );

      id.appendBranchId( branchId );

      node = node->children_[ branchId ];
   }

   return true;
}



const BlockForest::BlockInformation::Node * BlockForest::BlockInformation::getNode( const BlockID & id ) const
{
   if( nodes_.empty() )
168
      return nullptr;
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

   const uint_t treeIdDigits = forest_.getTreeIdDigits();

   WALBERLA_ASSERT_GREATER_EQUAL( id.getUsedBits(), treeIdDigits );
   WALBERLA_ASSERT_EQUAL( ( id.getUsedBits() - treeIdDigits ) % 3, 0 );

   BlockID blockId( id );

   const uint_t levels = ( blockId.getUsedBits() - treeIdDigits ) / 3;

   std::vector< uint_t > branchId( levels );

   for( uint_t i = levels; i-- != 0; ) {
      branchId[i] = blockId.getBranchId();
      blockId.removeBranchId();
   }

   const uint_t index = blockId.getTreeIndex();

   if( index >= nodes_.size() || !(nodes_[index]) )
189
      return nullptr;
190
191
192
193
194

   auto node = nodes_[index];

   for( uint_t i = 0; i != levels; ++i ) {
      if( node->children_.empty() )
195
         return nullptr;
196
197
198
199
200
201
202
203
204
205
206
207
208
209
      WALBERLA_ASSERT_NOT_NULLPTR( node->children_[ branchId[i] ] );
      node = node->children_[ branchId[i] ];
   }

   return node.get();
}



const BlockForest::BlockInformation::Node * BlockForest::BlockInformation::getNode( const real_t x, const real_t y, const real_t z ) const
{
   const AABB & domain = forest_.getDomain();

   if( nodes_.empty() || !domain.contains(x,y,z) )
210
      return nullptr;
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

   const real_t rootBlockXSize =  forest_.getRootBlockXSize();
   const real_t rootBlockYSize =  forest_.getRootBlockYSize();
   const real_t rootBlockZSize =  forest_.getRootBlockZSize();

   uint_t xi = static_cast< uint_t >( ( x - domain.xMin() ) / rootBlockXSize );
   uint_t yi = static_cast< uint_t >( ( y - domain.yMin() ) / rootBlockYSize );
   uint_t zi = static_cast< uint_t >( ( z - domain.zMin() ) / rootBlockZSize );

   if( xi >= forest_.getXSize() ) xi = forest_.getXSize() - 1; // shouldn't happen, ...
   if( yi >= forest_.getYSize() ) yi = forest_.getYSize() - 1; // ... but might happen due to ...
   if( zi >= forest_.getZSize() ) zi = forest_.getZSize() - 1; // ... floating point inaccuracy?

   const uint_t index = zi * forest_.getYSize() * forest_.getXSize() + yi * forest_.getXSize() + xi;

   auto node = nodes_[index];

   if( !node )
229
      return nullptr;
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299

   AABB aabb = AABB::createFromMinMaxCorner( domain.xMin() + static_cast< real_t >( xi ) * rootBlockXSize,
                                             domain.yMin() + static_cast< real_t >( yi ) * rootBlockYSize,
                                             domain.zMin() + static_cast< real_t >( zi ) * rootBlockZSize,
                                             ( xi+1 == forest_.getXSize() ) ? domain.xMax() : domain.xMin() + static_cast< real_t >( xi+1 ) * rootBlockXSize,
                                             ( yi+1 == forest_.getYSize() ) ? domain.yMax() : domain.yMin() + static_cast< real_t >( yi+1 ) * rootBlockYSize,
                                             ( zi+1 == forest_.getZSize() ) ? domain.zMax() : domain.zMin() + static_cast< real_t >( zi+1 ) * rootBlockZSize );
   WALBERLA_ASSERT( aabb.contains(x,y,z) );

   while( !node->children_.empty() ) {

      uint_t branchId = 0;

      const real_t xMid = ( aabb.xMin() + aabb.xMax() ) / real_c(2);
      const real_t yMid = ( aabb.yMin() + aabb.yMax() ) / real_c(2);
      const real_t zMid = ( aabb.zMin() + aabb.zMax() ) / real_c(2);

      if( x >= xMid ) ++branchId;
      if( y >= yMid ) branchId += 2;
      if( z >= zMid ) branchId += 4;

      aabb.initMinMaxCorner( ( branchId & 1 ) ? xMid : aabb.xMin(), ( branchId & 2 ) ? yMid : aabb.yMin(), ( branchId & 4 ) ? zMid : aabb.zMin(),
                             ( branchId & 1 ) ? aabb.xMax() : xMid, ( branchId & 2 ) ? aabb.yMax() : yMid, ( branchId & 4 ) ? aabb.zMax() : zMid );

      WALBERLA_ASSERT( aabb.contains(x,y,z) );
      WALBERLA_ASSERT_LESS( branchId, node->children_.size() );
      WALBERLA_ASSERT_NOT_NULLPTR( node->children_[ branchId ] );

      node = node->children_[ branchId ];
   }

   return node.get();
}



BlockForest::BlockForest( const uint_t process, const SetupBlockForest& forest, const bool keepGlobalBlockInformation ) :

   BlockStorage( forest.getDomain(), forest.isXPeriodic(), forest.isYPeriodic(), forest.isZPeriodic() ),

   process_( process ), processIdBytes_( forest.getProcessIdBytes() ), depth_( forest.getDepth() ), treeIdDigits_( forest.getTreeIdDigits() ),
   insertBuffersIntoProcessNetwork_( forest.insertBuffersIntoProcessNetwork() ), modificationStamp_( uint_t(0) ),
   recalculateBlockLevelsInRefresh_( true ), alwaysRebalanceInRefresh_( false ), allowMultipleRefreshCycles_( true ),
   reevaluateMinTargetLevelsAfterForcedRefinement_( false ),
   checkForEarlyOutInRefresh_( true ), checkForLateOutInRefresh_( true ), allowChangingDepth_( true ), checkForEarlyOutAfterLoadBalancing_( false ),
   phantomBlockMigrationIterations_( uint_t(0) ),
   nextCallbackBeforeBlockDataIsPackedHandle_( uint_t(0) ), nextCallbackBeforeBlockDataIsUnpackedHandle_( uint_t(0) ),
   nextCallbackAfterBlockDataIsUnpackedHandle_( uint_t(0) ),
   snapshotExists_( false ), snapshotDepth_( uint_t(0) ), snapshotBlockDataItems_( uint_t(0) )
{
   blockInformation_ = make_shared< BlockInformation >( *this );

   size_[0] = forest.getXSize();
   size_[1] = forest.getYSize();
   size_[2] = forest.getZSize();

   if( forest.isWorkerProcess( process ) ) {

      std::vector< const SetupBlock* > blocks;

      forest.getProcessSpecificBlocks( blocks, process );

      WALBERLA_ASSERT( !blocks.empty() );

      std::set< uint_t > neighbors;

      for( uint_t i = 0; i != blocks.size(); ++i ) {

         WALBERLA_ASSERT( blocks_.find( blocks[i]->getId() ) == blocks_.end() );

300
         blocks_[ blocks[i]->getId() ] = std::make_shared< Block >( *this, blocks[i] );
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359

         for( uint_t j = 0; j != blocks[i]->getNeighborhoodSize(); ++j )
            if( blocks[i]->getNeighbor(j)->getProcess() != process )
               neighbors.insert( blocks[i]->getNeighbor(j)->getProcess() );
      }

      if( insertBuffersIntoProcessNetwork_ && ( process + 1 ) < forest.getNumberOfProcesses() &&
          forest.isBufferProcess( process + 1 ) )
         neighbors.insert( process + 1 );

      for( std::set< uint_t >::iterator it = neighbors.begin(); it != neighbors.end(); ++it )
         neighborhood_.push_back( *it );
   }
   else if( insertBuffersIntoProcessNetwork_ )
   {
      WALBERLA_ASSERT( forest.isBufferProcess( process ) );
      WALBERLA_ASSERT_GREATER( process, 0 );

      neighborhood_.push_back( process - 1 );

      if( ( process + 1 ) < forest.getNumberOfProcesses() )
      {
         WALBERLA_ASSERT( !( forest.isBufferProcess( process - 1 ) && forest.isWorkerProcess( process + 1 ) ) );

         if( forest.isBufferProcess( process + 1 ) )
            neighborhood_.push_back( process + 1 );
      }
   }

   if( keepGlobalBlockInformation ) {
      constructBlockInformation( forest );
#ifndef NDEBUG
      checkBlockInformationConsistency( forest );
#endif
   }

   registerRefreshTimer();
}



BlockForest::BlockForest( const uint_t process, const char* const filename, const bool broadcastFile, const bool keepGlobalBlockInformation ) :

   BlockStorage( AABB(), false, false, false ),

   process_( process ),  modificationStamp_( uint_t(0) ),
   recalculateBlockLevelsInRefresh_( true ), alwaysRebalanceInRefresh_( false ), allowMultipleRefreshCycles_( true ),
   reevaluateMinTargetLevelsAfterForcedRefinement_( false ),
   checkForEarlyOutInRefresh_( true ), checkForLateOutInRefresh_( true ), allowChangingDepth_( true ), checkForEarlyOutAfterLoadBalancing_( false ),
   phantomBlockMigrationIterations_( uint_t(0) ),
   nextCallbackBeforeBlockDataIsPackedHandle_( uint_t(0) ), nextCallbackBeforeBlockDataIsUnpackedHandle_( uint_t(0) ),
   nextCallbackAfterBlockDataIsUnpackedHandle_( uint_t(0) ),
   snapshotExists_( false ), snapshotDepth_( uint_t(0) ), snapshotBlockDataItems_( uint_t(0) )
{
   blockInformation_ = make_shared< BlockInformation >( *this );

   uint_t offset = 0;
   std::vector< uint8_t > buffer;

360
   if( broadcastFile && (mpi::MPIManager::instance()->numProcesses() > 1) )
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
   {
      std::ifstream file;
      uint_t length = 0;

      WALBERLA_ROOT_SECTION() {
         file.open( filename, std::ios::binary );
         if( file.fail() )
            WALBERLA_ABORT( "Loading BlockForest from file \'" << filename << "\' failed:\n"
                            "Opening the file failed. Does the file even exist?" );
         file.seekg( 0, std::ios::end );
         length = uint_c( static_cast< std::streamoff >( file.tellg() ) );
         file.seekg( 0, std::ios::beg );
      }
      MPI_Bcast( reinterpret_cast< void* >( &length ), 1, MPITrait< uint_t >::type(), 0, MPI_COMM_WORLD );

      buffer.resize( length );

      WALBERLA_ROOT_SECTION() {
         file.read( reinterpret_cast< char* >( &(buffer[0]) ), numeric_cast< std::streamsize >( length ) );
         file.close();
      }
      MPI_Bcast( reinterpret_cast< void* >( &(buffer[0]) ), numeric_cast< int >( length ), MPITrait< uint8_t >::type(), 0, MPI_COMM_WORLD );
   }
   else
   {
      std::ifstream file;
      file.open( filename, std::ios::binary );
      if( file.fail() )
         WALBERLA_ABORT( "Loading BlockForest from file \'" << filename << "\' failed:\n"
                         "Opening the file failed. Does the file even exist?" );

      file.seekg( 0, std::ios::end );
      const uint_t length = uint_c( static_cast< std::streamoff >( file.tellg() ) );
      file.seekg( 0, std::ios::beg );

      buffer.resize( length );

      file.read( reinterpret_cast< char* >( &(buffer[0]) ), numeric_cast< std::streamsize >( length ) );
      file.close();
   }

   // HEADER

   // domain AABB

   real_t domain[6];

   for( uint_t i = 0; i != 6; ++i ) {
      domain[i] = byteArrayToReal< real_t >( buffer, offset );
      offset += sizeof( real_t ) + 1 + 2;
   }

   domain_.initMinMaxCorner( domain[0], domain[1], domain[2], domain[3], domain[4], domain[5] );

   // number of coarse/root blocks in each direction

   for( uint_t i = 0; i != 3; ++i ) {
      size_[i] = byteArrayToUint( buffer, offset, 4 );
      offset += 4;
   }

   // domain periodicity

   for( uint_t i = 0; i != 3; ++i ) {
      periodic_[i] = ( byteArrayToUint( buffer, offset, 1 ) == uint_c(1) );
      ++offset;
   }

   // block forest depth (= number of levels - 1)

   depth_ = byteArrayToUint( buffer, offset, 1 );
   ++offset;

   // treeIdDigits (= number of bits used for storing the tree ID [tree ID marker + tree index])

   treeIdDigits_ = byteArrayToUint( buffer, offset, 1 );
   ++offset;

   // processIdBytes (= number of bytes required for storing process IDs)

   processIdBytes_ = byteArrayToUint( buffer, offset, 1 );
   ++offset;

   // insertBuffersIntoProcessNetwork?

   insertBuffersIntoProcessNetwork_ = ( byteArrayToUint( buffer, offset, 1 ) == uint_c(1) );
   ++offset;

   // number of processes

   const uint_t numberOfProcesses = byteArrayToUint( buffer, offset, 4 );
   offset += 4;

   if( numberOfProcesses != uint_c( MPIManager::instance()->numProcesses() ) )
      WALBERLA_ABORT( "Loading BlockForest from file \'" << filename << "\' failed:\n"
                      "The number of MPI processes (" << MPIManager::instance()->numProcesses() << ") does not match the number of "
                      "processes stored in this file (" << numberOfProcesses << ")" );

   if( process >= numberOfProcesses )
      WALBERLA_ABORT( "Loading BlockForest from file \'" << filename << "\' failed:\n"
                      "The process index \'" << process << "\' exceeds the number of available processes (" << numberOfProcesses << ")!" );

   // SUID MAPPING

   // number of SUIDs

   const uint_t numberOfSUIDs = byteArrayToUint( buffer, offset, 1 );
   ++offset;

   const uint_t suidBytes = ( ( numberOfSUIDs % 8 == 0 ) ? ( numberOfSUIDs / 8 ) : ( numberOfSUIDs / 8 + 1 ) );

   std::vector< SUID > suidMap;

   // for every SUID ...

   for( uint_t i = 0; i != numberOfSUIDs; ++i ) {

      // length of its identifier string

      const uint_t identifierLength = byteArrayToUint( buffer, offset, 1 );
      ++offset;

      // the identifier string

      const std::string identifier( reinterpret_cast< const char* >( &(buffer[offset]) ), identifierLength );
      offset += identifierLength;

      SUID suid( identifier, false );

      suidMap.push_back( suid );
   }

   // BLOCK DATA

   const uint_t blockIdBytes = getBlockIdBytes();

   // calculate offsets to block and neighborhood data of each process

   std::vector< uint_t > offsetBlocks( numberOfProcesses );
   std::vector< uint_t > offsetNeighbors( numberOfProcesses );

   for( uint_t i = 0; i != numberOfProcesses; ++i )
   {
      offsetBlocks[i] = offset;

      const uint_t numberOfBlocks = byteArrayToUint( buffer, offset, 2 );
      offset += 2 + numberOfBlocks * ( blockIdBytes + suidBytes );

      offsetNeighbors[i] = offset;

      offset += 2 + byteArrayToUint( buffer, offset, 2 ) * processIdBytes_;
   }

   // process neighborhood (= all neighboring processes)

   const uint_t numberOfNeighbors = byteArrayToUint( buffer, offsetNeighbors[ process_ ], 2 );

   for( uint_t i = 0; i != numberOfNeighbors; ++i )
      neighborhood_.push_back( byteArrayToUint( buffer, offsetNeighbors[ process_ ] + 2 + i * processIdBytes_, processIdBytes_ ) );

   // number of blocks associated with this process

   const uint_t numberOfBlocks = byteArrayToUint( buffer, offsetBlocks[ process_ ], 2 );

   if( numberOfBlocks > 0 )
   {
      // construct neighborhood reconstruction blocks (required for initializing the blocks of this process)

      BlockReconstruction::AABBReconstruction aabbReconstruction( domain_, size_[0], size_[1], size_[2], treeIdDigits_ );
      BlockReconstruction::NeighborhoodReconstruction< Block > neighborhoodReconstruction( domain_, periodic_[0], periodic_[1], periodic_[2] );

      std::vector< BlockReconstruction::NeighborhoodReconstructionBlock > neighbors;

      for( uint_t i = 0; i != numberOfBlocks; ++i ) {

         offset = offsetBlocks[ process_ ] + 2 + i * ( blockIdBytes + suidBytes );

         const BlockID id( buffer, offset, blockIdBytes );

         Set<SUID> state;
541
542
543
544
         std::vector< bool > suidBoolVec = byteArrayToBoolVector( buffer, offset + blockIdBytes, suidBytes );
         for( uint_t j = 0; j != suidBoolVec.size(); ++j ) {
            WALBERLA_ASSERT( !suidBoolVec[ j ] || j < suidMap.size() );
            if( suidBoolVec[j])
545
546
547
               state += suidMap[j];
         }

548
         neighbors.emplace_back( id, process_, state, aabbReconstruction );
549
550
551
552
553
554
555
556
557
558
559
560
561
562
      }

      for( uint_t i = 0; i != numberOfNeighbors; ++i ) {

         const uint_t neighborProcess = neighborhood_[i];
         const uint_t numberOfNeighborBlocks = byteArrayToUint( buffer, offsetBlocks[ neighborProcess ], 2 );

         for( uint_t j = 0; j != numberOfNeighborBlocks; ++j ) {

            offset = offsetBlocks[ neighborProcess ] + 2 + j * ( blockIdBytes + suidBytes );

            const BlockID id( buffer, offset, blockIdBytes );

            Set<SUID> state;
563
564
565
566
            std::vector< bool > suidBoolVec = byteArrayToBoolVector( buffer, offset + blockIdBytes, suidBytes );
            for( uint_t k = 0; k != suidBoolVec.size(); ++k ) {
               WALBERLA_ASSERT( !suidBoolVec[k] || k < suidMap.size() );
               if( suidBoolVec[k])
567
568
569
                  state += suidMap[k];
            }

570
            neighbors.emplace_back( id, neighborProcess, state, aabbReconstruction );
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
         }
      }

      // for each block ...

      for( uint_t i = 0; i != numberOfBlocks; ++i ) {

         offset = offsetBlocks[ process_ ] + 2 + i * ( blockIdBytes + suidBytes );

         // block ID

         const BlockID id( buffer, offset, blockIdBytes );

         // block state (SUID set)

         Set<SUID> state;
587
588
589
590
         std::vector< bool > suidBoolVec = byteArrayToBoolVector( buffer, offset + blockIdBytes, suidBytes );
         for( uint_t j = 0; j != suidBoolVec.size(); ++j ) {
            WALBERLA_ASSERT( !suidBoolVec[j] || j < suidMap.size() );
            if( suidBoolVec[j])
591
592
593
594
595
596
597
598
               state += suidMap[j];
         }

         // create block using the just constructed reconstruction information

         AABB aabb;
         const uint_t level = aabbReconstruction( aabb, id );

599
         auto block = std::make_shared< Block >( *this, id, aabb, state, level, neighborhoodReconstruction, neighbors );
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617

         blocks_[ id ] = block;
      }
   }

   if( keepGlobalBlockInformation ) {

      std::vector< BlockID > ids;
      std::vector< shared_ptr< BlockInformation::Node > > nodes;

      for( uint_t i = 0; i != numberOfProcesses; ++i ) {

         const uint_t numBlocks = byteArrayToUint( buffer, offsetBlocks[ i ], 2 );

         for( uint_t j = 0; j != numBlocks; ++j ) {

            offset = offsetBlocks[ i ] + 2 + j * ( blockIdBytes + suidBytes );

618
            ids.emplace_back( buffer, offset, blockIdBytes );
619
620

            Set<SUID> state;
621
622
623
624
            std::vector< bool > suidBoolVec = byteArrayToBoolVector( buffer, offset + blockIdBytes, suidBytes );
            for( uint_t k = 0; k != suidBoolVec.size(); ++k ) {
               WALBERLA_ASSERT( !suidBoolVec[k] || k < suidMap.size() );
               if( suidBoolVec[k])
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
                  state += suidMap[k];
            }

            nodes.push_back( make_shared< BlockInformation::Node >( i, state ) );
         }
      }

      constructBlockInformation( ids, nodes );
   }

   registerRefreshTimer();
}



void BlockForest::getBlockID( IBlockID& id, const real_t x, const real_t y, const real_t z ) const {

   WALBERLA_ASSERT_EQUAL( dynamic_cast< BlockID* >( &id ), &id );

   if( blockInformation_->active() ) {
      if( !blockInformation_->getId( *static_cast< BlockID* >( &id ), x, y, z ) ) {
         WALBERLA_ABORT( "Getting block ID failed: There exists no block at global location (" << x << "," << y << "," << z <<")!" );
      }
   }
   else {
      const Block* const block = getBlock(x,y,z);
651
      if( block == nullptr ) {
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
         WALBERLA_ABORT( "Getting block ID failed: Locally, there exists no block at global location (" << x << "," << y << "," << z <<")!\n"
                         "                         (for simulation global information you have to explicitly construct the block forest to "
                         "contain global knowledge)");
      }
      id = block->getId();
   }
}



void BlockForest::getAABB( AABB& aabb, const IBlockID& id ) const {

   WALBERLA_ASSERT_EQUAL( dynamic_cast< const BlockID* >( &id ), &id );

   if( blockInformation_->active() ) {
      const BlockID& bid = *static_cast< const BlockID* >( &id );
      if( !blockInformation_->exists( bid ) ) {
         WALBERLA_ABORT( "Getting block AABB failed: There exists no block with block ID \'" << id << "\'" );
      }
      getAABBFromBlockId( aabb, bid );
   }
   else {
      const Block* const block = getBlock( id );
675
      if( block == nullptr )
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
      {
         const BlockID& bid = *static_cast< const BlockID* >( &id );
         aabb = getAABBFromBlockId( bid );
      }
      else
      {
         aabb = block->getAABB();
      }
   }
}



void BlockForest::getState( Set<SUID>& state, const IBlockID& id ) const {

   WALBERLA_ASSERT_EQUAL( dynamic_cast< const BlockID* >( &id ), &id );

   if( blockInformation_->active() ) {
      if( !blockInformation_->getState( state, *static_cast< const BlockID* >( &id ) ) ) {
         WALBERLA_ABORT( "Getting block state failed: There exists no block with block ID \'" << id << "\'" );
      }
   }
   else {
      const Block* const block = getBlock( id );
700
      if( block == nullptr ) {
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
         WALBERLA_ABORT( "Getting block state failed: Locally, there exists no block with block ID \'" << id << "\'\n"
                         "                            (for simulation global information you have to explicitly construct "
                         "the block forest to contain global knowledge)" );
      }
      state = block->getState();
   }
}



void BlockForest::getProcessRank( uint_t& rank, const IBlockID& id ) const {

   WALBERLA_ASSERT_EQUAL( dynamic_cast< const BlockID* >( &id ), &id );

   if( blockInformation_->active() ) {
      if( !blockInformation_->getProcess( rank, *static_cast< const BlockID* >( &id ) ) ) {
         WALBERLA_ABORT( "Getting block process rank failed: There exists no block with block ID \'" << id << "\'" );
      }
   }
   else {
      const Block* const block = getBlock( id );
722
      if( block == nullptr ) {
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
         WALBERLA_ABORT( "Getting block process rank failed: Locally, there exists no block with block ID \'" << id << "\'\n"
                         "                                   (for simulation global information you have to explicitly construct "
                         "the block forest to contain global knowledge)" );
      }
      rank = block->getProcess();
   }
}



void BlockForest::getRootBlockAABB( AABB& aabb, const uint_t x, const uint_t y, const uint_t z ) const {

   if( blockInformation_->active() ) {

      if( !blockInformation_->rootBlockExists(x,y,z) ) {
         WALBERLA_ABORT( "Getting root block AABB failed: There exists no root block [" << x << "," << y << "," << z <<"]!" );
      }

      const real_t xw = getRootBlockXSize();
      const real_t yw = getRootBlockYSize();
      const real_t zw = getRootBlockZSize();

      aabb.initMinMaxCorner( domain_.xMin() + static_cast< real_t >(  x  ) * xw,
                             domain_.yMin() + static_cast< real_t >(  y  ) * yw,
                             domain_.zMin() + static_cast< real_t >(  z  ) * zw,
                             ( x+1 == size_[0] ) ? domain_.xMax() : domain_.xMin() + static_cast< real_t >( x+1 ) * xw,
                             ( y+1 == size_[1] ) ? domain_.yMax() : domain_.yMin() + static_cast< real_t >( y+1 ) * yw,
                             ( z+1 == size_[2] ) ? domain_.zMax() : domain_.zMin() + static_cast< real_t >( z+1 ) * zw );
   }
   else {
      const Block* const block = getRootBlock(x,y,z);
754
      if( block == nullptr ) {
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
         WALBERLA_ABORT( "Getting root block AABB failed: Locally, there exists no root block [" << x << "," << y << "," << z <<"]!\n"
                         "                                (for simulation global information you have to explicitly construct "
                         "the block forest to contain global knowledge)" );
      }
      aabb = block->getAABB();
   }
}



void BlockForest::getRootBlockState( Set<SUID>& state, const uint_t x, const uint_t y, const uint_t z ) const {

   if( blockInformation_->active() ) {
      if( !blockInformation_->getRootBlockState( state, x, y, z ) ) {
         WALBERLA_ABORT( "Getting root block state failed: There exists no root block [" << x << "," << y << "," << z <<"]!" );
      }
   }
   else {
      const Block* const block = getRootBlock(x,y,z);
774
      if( block == nullptr ) {
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
         WALBERLA_ABORT( "Getting root block state failed: Locally, there exists no root block [" << x << "," << y << "," << z <<"]!\n"
                         "                                 (for simulation global information you have to explicitly construct "
                         "the block forest to contain global knowledge)" );
      }
      state = block->getState();
   }
}



void BlockForest::getRootBlockProcessRank( uint_t& rank, const uint_t x, const uint_t y, const uint_t z ) const {

   if( blockInformation_->active() ) {
      if( !blockInformation_->getRootBlockProcess( rank, x, y, z ) ) {
         WALBERLA_ABORT( "Getting root block process rank failed: There exists no root block [" << x << "," << y << "," << z <<"]!" );
      }
   }
   else {
      const Block* const block = getRootBlock(x,y,z);
794
      if( block == nullptr ) {
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
         WALBERLA_ABORT( "Getting root block process rank failed: Locally, there exists no root block [" << x << "," << y << "," << z <<"]!\n"
                         "                                        (for simulation global information you have to explicitly construct "
                         "the block forest to contain global knowledge)" );
      }
      rank = block->getProcess();
   }
}



void BlockForest::getForestCoordinates( uint_t& x, uint_t& y, uint_t& z, const BlockID& id ) const {

   WALBERLA_ASSERT_GREATER_EQUAL( id.getUsedBits(), treeIdDigits_ );
   WALBERLA_ASSERT_EQUAL( ( id.getUsedBits() - treeIdDigits_ ) % 3, 0 );

   BlockID blockId( id );

   const uint_t levels = ( blockId.getUsedBits() - treeIdDigits_ ) / 3;
   for( uint_t i = levels; i-- != 0; )
      blockId.removeBranchId();

   uint_t index = blockId.getTreeIndex();

       z = index / ( size_[0] * size_[1] );
   index = index % ( size_[0] * size_[1] );
       y = index / size_[0];
       x = index % size_[0];
}



std::map< uint_t, std::vector< Vector3<real_t> > > BlockForest::getNeighboringProcessOffsets() const
{
   std::map< uint_t, std::vector< Vector3<real_t> > > offsets;

   for( auto it = blocks_.begin(); it != blocks_.end(); ++it )
   {
      const auto & block = it->second;
      const AABB & blockAABB = block->getAABB();

      const real_t eps[] = { real_c( 1.0E-6 ) * ( blockAABB.xMax() - blockAABB.xMin() ),
                             real_c( 1.0E-6 ) * ( blockAABB.yMax() - blockAABB.yMin() ),
                             real_c( 1.0E-6 ) * ( blockAABB.zMax() - blockAABB.zMin() ) };

      uint_t i[] = { uint_c(0), uint_c(0), uint_c(0) };

      for( i[2] = 0; i[2] != 3; ++i[2] ) {
         for( i[1] = 0; i[1] != 3; ++i[1] ) {
            for( i[0] = 0; i[0] != 3; ++i[0] )
            {
               if( i[0] == 1 && i[1] == 1 && i[2] == 1 )
                  continue;

               const auto sectionIndex = getBlockNeighborhoodSectionIndex( i[0], i[1], i[2] );
               const auto neighbors = block->getNeighborhoodSection( sectionIndex );

               for( auto neighbor = neighbors.begin(); neighbor != neighbors.end(); ++neighbor )
               {
                  if( (*neighbor)->getProcess() == getProcess() )
                     continue;

                  AABB aabb;
                  getAABBFromBlockId( aabb, (*neighbor)->getId() );

                  Vector3< real_t > offset;

                  for( uint_t j = 0; j != 3; ++j )
                  {
                     if( i[j] == 0 ) offset[j] = aabb.max(j) - blockAABB.min(j);
                     else if( i[j] == 2 ) offset[j] = aabb.min(j) - blockAABB.max(j);
                     else offset[j] = real_c(0);

                     if( realIsEqual( offset[j], real_c(0), eps[j] ) )
                        offset[j] = real_c(0);

                     WALBERLA_ASSERT( realIsIdentical( offset[j], real_c(0) ) ||
                             ( isPeriodic(j) && realIsEqual( std::fabs( offset[j] ), getDomain().max(j) - getDomain().min(j), eps[j] ) ) );
                  }

                  const auto process = (*neighbor)->getProcess();
                  auto & processOffsets = offsets[ process ];

                  bool newOffset = true;
                  for( auto vec = processOffsets.begin(); vec != processOffsets.end() && newOffset; ++vec )
                  {
                     if( realIsEqual( (*vec)[0], offset[0], eps[0] ) && realIsEqual( (*vec)[1], offset[1], eps[1] ) &&
                         realIsEqual( (*vec)[2], offset[2], eps[2] ) ) newOffset = false;
                  }
                  if( newOffset )
                     processOffsets.push_back( offset );
               }
            }
         }
      }
   }
   return offsets;
}



void BlockForest::refresh()
{
   WALBERLA_LOG_PROGRESS( "BlockForest refresh: starting distributed refresh of the block structure" );

   bool rebalanceAndRedistribute( true );
   bool additionalRefreshCycleRequired( false );

   refreshTiming_[ "block level determination" ].start();

   for( auto block = blocks_.begin(); block != blocks_.end(); ++block )
   {
      WALBERLA_ASSERT_NOT_NULLPTR( block->second );
      block->second->setTargetLevel( block->second->getLevel() );
   }
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
   if( recalculateBlockLevelsInRefresh_ )
   {
      WALBERLA_LOG_PROGRESS( "BlockForest refresh: determining new block levels" );

      bool rerun( true );
      while( rerun )
      {
         rebalanceAndRedistribute = determineBlockTargetLevels( additionalRefreshCycleRequired, rerun );
      }

      if( !rebalanceAndRedistribute )
         WALBERLA_LOG_PROGRESS( "BlockForest refresh: block levels do not change" );
   }
   else
   {
      WALBERLA_LOG_PROGRESS( "BlockForest refresh: block levels do not change" );
   }

   refreshTiming_[ "block level determination" ].end();

   if( alwaysRebalanceInRefresh_ && refreshPhantomBlockMigrationPreparationFunction_ )
      rebalanceAndRedistribute = true;
932

933
934
935
   while( rebalanceAndRedistribute )
   {
      // create phantom block forest
936

937
938
939
940
941
942
      WALBERLA_LOG_PROGRESS( "BlockForest refresh: creating phantom forest/blocks" );

      refreshTiming_[ "phantom forest creation" ].start();

      PhantomBlockForest phantomForest( *this );
      phantomForest.initialize( refreshBlockStateDeterminationFunction_, allowChangingDepth_ );
943

944
945
946
      refreshTiming_[ "phantom forest creation" ].end();

      // move phantom blocks between processes (= dynamic load balancing)
947

948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
      WALBERLA_MPI_SECTION()
      {
         refreshTiming_[ "phantom block redistribution (= load balancing)" ].start();

         if( refreshPhantomBlockMigrationPreparationFunction_ )
         {
            phantomForest.assignBlockData( refreshPhantomBlockDataAssignmentFunction_ );

            WALBERLA_LOG_PROGRESS( "BlockForest refresh: performing phantom block redistribution/load balancing" );

            uint_t iteration = uint_t(0);
            bool runAgain( true );
            while( runAgain )
            {
               WALBERLA_LOG_PROGRESS( "BlockForest refresh: decide about which phantom blocks need to migrate" );
               runAgain = phantomForest.calculateMigrationInformation( refreshPhantomBlockMigrationPreparationFunction_, iteration );
               WALBERLA_LOG_PROGRESS( "BlockForest refresh: migrate phantom blocks" );
               phantomForest.migrate( refreshPhantomBlockDataPackFunction_, refreshPhantomBlockDataUnpackFunction_ );
               ++iteration;
            }
            phantomBlockMigrationIterations_ = iteration;
969

970
971
972
973
974
            WALBERLA_LOG_PROGRESS( "BlockForest refresh: phantom block redistribution/load balancing finished after " << phantomBlockMigrationIterations_ << " iterations" );
         }

         refreshTiming_[ "phantom block redistribution (= load balancing)" ].end();
      }
975

976
      // update block forest: transfer block data (includes migrating, deleting and creating blocks), adapt depth, adapt process neighborhood, etc.
977

978
979
980
981
982
983
984
985
      bool performUpdate( true );
      if( checkForEarlyOutAfterLoadBalancing_ )
      {
         performUpdate = false;
         const auto & phantomBlocks = phantomForest.getBlockMap();
         for( auto phantom = phantomBlocks.begin(); phantom != phantomBlocks.end() && !performUpdate; ++phantom )
         {
            const auto & sourceProcess = phantom->second->getSourceProcess();
986
            for( auto it = sourceProcess.begin(); it != sourceProcess.end() && !performUpdate; ++it )
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
               performUpdate = ( *it != process_ );
         }
         mpi::allReduceInplace( performUpdate, mpi::LOGICAL_OR );
      }

      if( performUpdate )
      {
         WALBERLA_LOG_PROGRESS( "BlockForest refresh: update block structure" );

         refreshTiming_[ "block structure update (includes data migration)" ].start();
         update( phantomForest );
         refreshTiming_[ "block structure update (includes data migration)" ].end();

         WALBERLA_LOG_PROGRESS( "BlockForest refresh: updating block structure finished" );
For faster browsing, not all history is shown. View entire blame