FFmmAlgorithmThreadProcPeriodic.hpp 108 KB
Newer Older
1
// See LICENCE file at project root
berenger-bramas's avatar
berenger-bramas committed
2 3
#ifndef FFMMALGORITHMTHREADPROCPPERIODIC_HPP
#define FFMMALGORITHMTHREADPROCPPERIODIC_HPP
4

5 6
#include <algorithm>
#include <array>
7
#include <vector>
8

9 10
#include "Utils/FAssert.hpp"
#include "Utils/FLog.hpp"
11

12 13 14 15
#include "Utils/FTic.hpp"
#include "Utils/FGlobal.hpp"
#include "Utils/FMemUtils.hpp"
#include "Utils/FEnv.hpp"
16

17
#include "Containers/FVector.hpp"
18 19 20
#include "Containers/FBoolArray.hpp"
#include "Containers/FOctree.hpp"
#include "Containers/FLightOctree.hpp"
21

22 23
#include "Containers/FBufferWriter.hpp"
#include "Containers/FBufferReader.hpp"
24

25
#include "Utils/FEnv.hpp"
berenger-bramas's avatar
berenger-bramas committed
26

27
#include "Utils/FMpi.hpp"
28
#ifdef _OPENMP
29
#include <omp.h>
30
#endif
31
#include "FCoreCommon.hpp"
32
#include "FP2PExclusion.hpp"
33

34 35
#include "Utils/FAlgorithmTimers.hpp"

36 37
#include <memory>

38
/**
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
 * @author Berenger Bramas (berenger.bramas@inria.fr)
 * @class FFmmAlgorithmThreadProcPeriodic
 * @brief
 * Please read the license
 *
 * This class is a threaded FMM algorithm with mpi.
 * It just iterates on a tree and call the kernels with good arguments.
 * It used the inspector-executor model :
 * iterates on the tree and builds an array to work in parallel on this array
 *
 * Of course this class does not deallocate pointer given in arguements.
 *
 * Threaded & based on the inspector-executor model
 * schedule(runtime) export OMP_NUM_THREADS=2
 * export OMPI_CXX=`which g++-4.4`
 * mpirun -np 2 valgrind --suppressions=/usr/share/openmpi/openmpi-valgrind.supp
 * --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes
 * ./Tests/testFmmAlgorithmProc ../Data/testLoaderSmall.fma.tmp
 */
58
template<class FReal, class OctreeClass, class CellClass, class ContainerClass, class KernelClass, class LeafClass, class P2PExclusionClass = FP2PMiddleExclusion>
59
class FFmmAlgorithmThreadProcPeriodic : public FAbstractAlgorithm, public FAlgorithmTimers {
60 61
  OctreeClass* const tree;                 ///< The octree to work on
  KernelClass** kernels;                   ///< The kernels
62

63
  const FMpi::FComm& comm;                 ///< MPI communicator
64

65 66 67
  CellClass rootCellFromProc;     ///< root of tree needed by the periodicity
  const int nbLevelsAboveRoot;    ///< The nb of level the user ask to go above the tree (>= -1)
  const int offsetRealTree;       ///< nbLevelsAboveRoot GetFakeLevel
68 69


70 71
  typename OctreeClass::Iterator* iterArray;  ///<  Used to store pointers to cells/leafs to work with
  typename OctreeClass::Iterator* iterArrayComm;   ///< Used to store pointers to cells/leafs to send/rcv
72

73 74 75 76 77
  int numberOfLeafs;           ///< To store the size at the previous level
  const int MaxThreads;        ///< Max number of thread allowed by openmp
  const int nbProcess;         ///< Process count
  const int idProcess;         ///< Current process id
  const int OctreeHeight;      ///< Tree height
78

79 80
  const int userChunkSize;
  const int leafLevelSeparationCriteria;
81

82 83 84 85 86 87 88 89 90
  struct Interval{
    MortonIndex leftIndex;
    MortonIndex rightIndex;
  };

  /// Current process interval
  Interval*const intervals;
  /// All processes intervals
  Interval*const workingIntervalsPerLevel;
91

92
public:
93

94 95 96
  using multipole_t = typename CellClass::multipole_t;
  using local_expansion_t = typename CellClass::local_expansion_t;
  using symbolic_data_t = CellClass;
97

98
private:
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
  /// Get an interval from a process id and tree level
  Interval& getWorkingInterval( int level,  int proc){
    return workingIntervalsPerLevel[OctreeHeight * proc + level];
  }

  /// Get an interval from a process id and tree level
  const Interval& getWorkingInterval( int level,  int proc) const {
    return workingIntervalsPerLevel[OctreeHeight * proc + level];
  }

  /// Does \a procIdx have work at given \a idxLevel
  /** i.e. does it hold cells and is responsible of them ? */
  bool procHasWorkAtLevel(const int idxLevel , const int idxProc) const {
    return getWorkingInterval(idxLevel, idxProc).leftIndex <= getWorkingInterval(idxLevel, idxProc).rightIndex;
  }

  /** True if the \a idxProc left cell at \a idxLevel+1 has the same parent as us for our right cell */
  bool procCoversMyRightBorderCell(const int idxLevel , const int idxProc) const {
    return (getWorkingInterval((idxLevel+1) , idProcess).rightIndex>>3) == (getWorkingInterval((idxLevel+1) ,idxProc).leftIndex >>3);
  }

  /** True if the idxProc right cell at idxLevel+1 has the same parent as us for our left cell */
  bool procCoversMyLeftBorderCell(const int idxLevel , const int idxProc) const {
    return (getWorkingInterval((idxLevel+1) , idxProc).rightIndex >>3) == (getWorkingInterval((idxLevel+1) , idProcess).leftIndex>>3);
  }
124

125 126
public:

127 128 129 130 131 132
  void setKernel(KernelClass*const inKernels){
    this->kernels = new KernelClass*[MaxThreads];
#pragma omp parallel num_threads(MaxThreads)
    {
#pragma omp critical (InitFFmmAlgorithmThreadProcPeriodic)
      {
133
        this->kernels[omp_get_thread_num()] = new KernelClass(*inKernels);
134
      }
135
    }
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  }


  Interval& getWorkingInterval(const int level){
    return getWorkingInterval(level, idProcess);
  }

  /// Does the current process have some work at this level ?
  bool hasWorkAtLevel(int level){
    return idProcess == 0 || (getWorkingInterval(level, idProcess - 1).rightIndex) < (getWorkingInterval(level, idProcess).rightIndex);
  }

  /** The constructor need the octree and the kernels used for computation
   * @param inTree the octree to work on
   * @param inKernels the kernels to call
   *
   * An assert is launched if one of the arguments is null
   */
  FFmmAlgorithmThreadProcPeriodic(const FMpi::FComm& inComm,
155 156 157 158
                                  OctreeClass* const inTree,
                                  const int inUpperLevel = 2,
                                  const int inUserChunkSize = 10,
                                  const int inLeafLevelSeperationCriteria = 1)
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    : tree(inTree) ,
      kernels(nullptr),
      comm(inComm),
      nbLevelsAboveRoot(inUpperLevel),
      offsetRealTree(inUpperLevel + 2),
      numberOfLeafs(0),
      MaxThreads(FEnv::GetValue("SCALFMM_ALGO_NUM_THREADS",omp_get_max_threads())),
      nbProcess(inComm.processCount()),
      idProcess(inComm.processId()),
      OctreeHeight(tree->getHeight()),
      userChunkSize(inUserChunkSize),
      leafLevelSeparationCriteria(inLeafLevelSeperationCriteria),
      intervals(new Interval[inComm.processCount()]),
      workingIntervalsPerLevel(new Interval[inComm.processCount() * tree->getHeight()]) {

    FAssertLF(tree, "tree cannot be null");
    FAssertLF(-1 <= inUpperLevel, "inUpperLevel cannot be < -1");
    FAssertLF(leafLevelSeparationCriteria < 3, "Separation criteria should be < 3");

    FAbstractAlgorithm::setNbLevelsInTree(extendedTreeHeight());

    FLOG(FLog::Controller << "FFmmAlgorithmThreadProcPeriodic\n");
    FLOG(FLog::Controller << "Max threads = "  << MaxThreads << ", Procs = " << nbProcess << ", I am " << idProcess << ".\n");
    FLOG(FLog::Controller << "Chunck Size = " << userChunkSize << "\n");
  }

  /** Default destructor */
  virtual ~FFmmAlgorithmThreadProcPeriodic(){
    for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
188 189
        delete this->kernels[idxThread];
      }
190
    delete [] this->kernels;
191

192 193 194
    delete [] intervals;
    delete [] workingIntervalsPerLevel;
  }
195 196


197 198


199 200
  long long int theoricalRepetition() const {
    if( nbLevelsAboveRoot == -1 ){
201 202 203
        // we know it is 3 (-1;+1)
        return 3;
      }
204 205 206 207
    // Else we find the repetition in one dir and double it
    return 6 * (1<<(nbLevelsAboveRoot));
  }
  //
208
  //
209 210 211
  //
  void repetitionsIntervals(FTreeCoordinate*const min, FTreeCoordinate*const max) const {
    if( nbLevelsAboveRoot == -1 ){
212 213 214 215
        // We know it is (-1;1)
        min->setPosition(-1,-1,-1);
        max->setPosition(1,1,1);
      }
216
    else{
217 218 219 220 221
        const int halfRepeated = int(theoricalRepetition()/2);
        min->setPosition(-halfRepeated,-halfRepeated,-halfRepeated);
        // if we repeat the box 8 times, we go from [-4 to 3]
        max->setPosition(halfRepeated-1,halfRepeated-1,halfRepeated-1);
      }
222
  }
223 224


225 226
  FReal extendedBoxWidth() const {
    if( nbLevelsAboveRoot == -1 ){
227 228
        return tree->getBoxWidth()*2;
      }
229
    else{
230 231
        return tree->getBoxWidth() * FReal(4<<(nbLevelsAboveRoot));
      }
232
  }
233

234 235
  FReal extendedBoxWidthBoundary() const {
    if( nbLevelsAboveRoot == -1 ){
236 237
        return tree->getBoxWidth()*4;
      }
238
    else{
239 240
        return tree->getBoxWidth() * FReal(8<<(nbLevelsAboveRoot));
      }
241 242 243 244 245 246 247 248 249 250 251 252 253
  }

  /** This function has to be used to init the kernel with correct args
   * It returns the box center seen from a kernel point of view from the periodicity the user ask for
   * this is computed using the originalBoxWidth and originalBoxCenter given in parameter
   *
   * @param originalBoxCenter the real system center
   * @param originalBoxWidth the real system size
   *
   * @return the center the kernel should use
   */
  FPoint<FReal> extendedBoxCenter() const {
    if( nbLevelsAboveRoot == -1 ){
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        const FReal originalBoxWidth            = tree->getBoxWidth();
        const FPoint<FReal> originalBoxCenter   = tree->getBoxCenter();
        const FReal originalBoxWidthDiv2        = originalBoxWidth/2.0;
        return FPoint<FReal>( originalBoxCenter.getX() + originalBoxWidthDiv2,
                              originalBoxCenter.getY() + originalBoxWidthDiv2,
                              originalBoxCenter.getZ() + originalBoxWidthDiv2);
      } else {
        const FReal originalBoxWidth     = tree->getBoxWidth();
        const FReal originalBoxWidthDiv2 = originalBoxWidth/2.0;
        const FPoint<FReal> originalBoxCenter   = tree->getBoxCenter();

        const FReal offset = extendedBoxWidth()/FReal(2.0);
        return FPoint<FReal>( originalBoxCenter.getX() - originalBoxWidthDiv2 + offset,
                              originalBoxCenter.getY() - originalBoxWidthDiv2 + offset,
                              originalBoxCenter.getZ() - originalBoxWidthDiv2 + offset);
      }
270 271 272 273
  }

  FPoint<FReal> extendedBoxCenterBoundary() const {
    if( nbLevelsAboveRoot == -1 ){
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        const FReal originalBoxWidth            = tree->getBoxWidth();
        const FPoint<FReal> originalBoxCenter   = tree->getBoxCenter();
        const FReal originalBoxWidthDiv2        = originalBoxWidth/2.0;
        return FPoint<FReal>( originalBoxCenter.getX() + originalBoxWidthDiv2,
                              originalBoxCenter.getY() + originalBoxWidthDiv2,
                              originalBoxCenter.getZ() + originalBoxWidthDiv2);
      } else {
        const FReal originalBoxWidth     = tree->getBoxWidth();
        const FReal originalBoxWidthDiv2 = originalBoxWidth/2.0;
        const FPoint<FReal> originalBoxCenter   = tree->getBoxCenter();

        return FPoint<FReal>( originalBoxCenter.getX() + originalBoxWidthDiv2,
                              originalBoxCenter.getY() + originalBoxWidthDiv2,
                              originalBoxCenter.getZ() + originalBoxWidthDiv2);
      }
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  }

  /** This function has to be used to init the kernel with correct args
   * it returns the tree height seen from a kernel point of view from the periodicity the user ask for
   * this is computed using the originalTreeHeight given in parameter
   *
   * @param originalTreeHeight the real tree heigh
   *
   * @return the height the kernel should use
   */
  int extendedTreeHeight() const {
    // The real height
    return OctreeHeight + offsetRealTree;
  }

  int extendedTreeHeightBoundary() const {
    // The real height
    return OctreeHeight + offsetRealTree + 1;
  }
308

309 310

protected:
311 312 313 314 315 316
  /**
   * To execute the fmm algorithm
   * Call this function to run the complete algorithm
   */
  void executeCore(const unsigned operationsToProceed) override {
    // Count leaf
317
    // Build the data distribution
318 319 320 321
    this->numberOfLeafs = 0;
    {
      Interval myFullInterval;
      {//Building the interval with the first and last leaves (and count the number of leaves)
322 323 324 325 326 327 328
        typename OctreeClass::Iterator octreeIterator(tree);
        octreeIterator.gotoBottomLeft();
        myFullInterval.leftIndex = octreeIterator.getCurrentGlobalIndex();
        do{
            ++this->numberOfLeafs;
          } while(octreeIterator.moveRight());
        myFullInterval.rightIndex = octreeIterator.getCurrentGlobalIndex();
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
      }
      // Allocate a number to store the pointer of the cells at a level
      iterArray     = new typename OctreeClass::Iterator[numberOfLeafs];
      iterArrayComm = new typename OctreeClass::Iterator[numberOfLeafs];
      FAssertLF(iterArray,     "iterArray     bad alloc");
      FAssertLF(iterArrayComm, "iterArrayComm bad alloc");

      // We get the leftIndex/rightIndex indexes from each procs
      FMpi::MpiAssert( MPI_Allgather( &myFullInterval, sizeof(Interval), MPI_BYTE, intervals, sizeof(Interval), MPI_BYTE, comm.getComm()),  __LINE__ );

      // Build my intervals for all levels
      std::unique_ptr<Interval[]> myIntervals(new Interval[OctreeHeight]);
      // At leaf level we know it is the full interval
      myIntervals[OctreeHeight - 1] = myFullInterval;

      // We can estimate the interval for each level by using the parent/child relation
      for(int idxLevel = OctreeHeight - 2 ; idxLevel >= 0 ; --idxLevel){
346 347 348
          myIntervals[idxLevel].leftIndex = myIntervals[idxLevel+1].leftIndex >> 3;
          myIntervals[idxLevel].rightIndex = myIntervals[idxLevel+1].rightIndex >> 3;
        }
349 350 351 352

      // Process 0 uses the estimates as real intervals, but other processes
      // should remove cells that belong to others
      if(idProcess != 0){
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
          //We test for each level if process on left (idProcess-1) own cell I thought I owned
          typename OctreeClass::Iterator octreeIterator(tree);
          octreeIterator.gotoBottomLeft();
          octreeIterator.moveUp();

          // At h-1 the working limit is the parent of the right cell of the proc on the left
          MortonIndex workingLimitAtLevel = intervals[idProcess-1].rightIndex >> 3;

          // We check if we have no more work to do
          int nullIntervalFromLevel = 0;

          for(int idxLevel = OctreeHeight - 2 ; idxLevel >= 1 && nullIntervalFromLevel == 0 ; --idxLevel){
              while(octreeIterator.getCurrentGlobalIndex() <= workingLimitAtLevel){
                  if( !octreeIterator.moveRight() ){
                      // We cannot move right we are not owner of any more cell
                      nullIntervalFromLevel = idxLevel;
                      break;
                    }
                }
              // If we are responsible for some cells at this level keep the first index
              if(nullIntervalFromLevel == 0){
                  myIntervals[idxLevel].leftIndex = octreeIterator.getCurrentGlobalIndex();
                  octreeIterator.moveUp();
                  workingLimitAtLevel >>= 3;
                }
            }
          // In case we are not responsible for any cells we put the leftIndex = rightIndex+1
          for(int idxLevel = nullIntervalFromLevel ; idxLevel >= 1 ; --idxLevel){
              myIntervals[idxLevel].leftIndex = myIntervals[idxLevel].rightIndex + 1;
            }
        }
384 385 386

      // We get the leftIndex/rightIndex indexes from each procs
      FMpi::MpiAssert( MPI_Allgather( myIntervals.get(), int(sizeof(Interval)) * OctreeHeight, MPI_BYTE,
387
                                      workingIntervalsPerLevel, int(sizeof(Interval)) * OctreeHeight, MPI_BYTE, comm.getComm()),  __LINE__ );
388 389
    }

390
    tree->forEachCell([this](CellClass* node){
391 392
      node->setLevel(node->getLevel() + offsetRealTree);
    });
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
    //
    // run the FMM algoritm
    //
    Timers[P2MTimer].tic();
    if(operationsToProceed & FFmmP2M) bottomPass();
    Timers[P2MTimer].tac();


    Timers[M2MTimer].tic();
    if(operationsToProceed & FFmmM2M) upwardPass();
    Timers[M2MTimer].tac();

    Timers[M2LTimer].tic();
    if(operationsToProceed & FFmmM2L) transferPass();
    Timers[M2LTimer].tac();

    Timers[L2LTimer].tic();
    if(operationsToProceed & FFmmL2L) downardPass();
    Timers[L2LTimer].tac();

    Timers[NearTimer].tic();
    if((operationsToProceed & FFmmP2P) || (operationsToProceed & FFmmL2P)) directPass((operationsToProceed & FFmmP2P),(operationsToProceed & FFmmL2P));
    Timers[NearTimer].tac();

    tree->forEachCell([this](CellClass* node){
418 419
      node->setLevel(node->getLevel() - offsetRealTree);
    });
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

    // delete array
    delete []     iterArray;
    delete []     iterArrayComm;
    iterArray          = nullptr;
    iterArrayComm = nullptr;
  }

  /////////////////////////////////////////////////////////////////////////////
  // P2M
  /////////////////////////////////////////////////////////////////////////////

  /**
   * P2M Bottom Pass
   * No communication are involved in the P2M.
   * It is similar to multi threaded version.
   */
  void bottomPass(){
    FLOG( FLog::Controller.write("\tStart Bottom Pass\n").write(FLog::Flush) );
    FLOG(FTic counterTime);
    FLOG(FTic computationCounter);
    typename OctreeClass::Iterator octreeIterator(tree);

    // Copy the ptr to leaves in array
    octreeIterator.gotoBottomLeft();
    int leafs = 0;
    do{
447 448
        iterArray[leafs++] = octreeIterator;
      } while(octreeIterator.moveRight());
449 450

    FLOG(computationCounter.tic());
451
#pragma omp parallel num_threads(MaxThreads)
452 453 454 455
    {
      // Each thread get its own kernel
      KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
      // Parallel iteration on the leaves
456
#pragma omp for nowait schedule(dynamic, userChunkSize)
457
      for(int idxLeafs = 0 ; idxLeafs < leafs ; ++idxLeafs) {
458 459 460 461 462 463 464 465 466 467
          multipole_t* leaf_multipole
              = &(iterArray[idxLeafs].getCurrentCell()->getMultipoleData());
          const symbolic_data_t* leaf_symbolic
              = iterArray[idxLeafs].getCurrentCell();
          myThreadkernels->P2M(
                leaf_multipole,
                leaf_symbolic,
                iterArray[idxLeafs].getCurrentListSrc()
                );
        }
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
    FLOG(computationCounter.tac());
    FLOG( FLog::Controller << "\tFinished (@Bottom Pass (P2M) = "  << counterTime.tacAndElapsed() << " s)\n" );
    FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.elapsed() << " s\n" );
    FLOG( FLog::Controller.flush());
  }

  /////////////////////////////////////////////////////////////////////////////
  // Upward
  /////////////////////////////////////////////////////////////////////////////

  /** M2M */
  void upwardPass(){
    FLOG( FLog::Controller.write("\tStart Upward Pass\n").write(FLog::Flush); );
    FLOG(FTic counterTime);
    FLOG(FTic computationCounter);
    FLOG(FTic singleCounter);
    FLOG(FTic parallelCounter);

    // Start from leal level (height-1)
    typename OctreeClass::Iterator octreeIterator(tree);
    octreeIterator.gotoBottomLeft();
    octreeIterator.moveUp();
    typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

    // The proc to send the shared cells to
    // Starting to the proc on the left this variable will go to 0
    int currentProcIdToSendTo = (idProcess - 1);

    // There are a maximum of 1 sends and 8-1 receptions
    MPI_Request requests[8];
    MPI_Status status[8];

    MPI_Request requestsSize[8];
    MPI_Status statusSize[8];

    FSize bufferSize;
    FBufferWriter sendBuffer(1);// Max = 1 + sizeof(cell)*7
    std::unique_ptr<FBufferReader[]> recvBuffer(new FBufferReader[7]);
    FSize recvBufferSize[7];
    CellClass recvBufferCells[7];

    // The first proc that send to me a cell
    // This variable will go to nbProcess
    int firstProcThatSend = idProcess + 1;
    FLOG(computationCounter.tic());

    // We work from height-1 to 1
    for(int idxLevel = OctreeHeight - 2 ; idxLevel > 0 ; --idxLevel ){
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
        //            const int fakeLevel = idxLevel + offsetRealTree;
        // Does my cells are covered by my neighbors working interval and so I have no more work?
        const bool noMoreWorkForMe = (idProcess != 0 && !procHasWorkAtLevel(idxLevel+1, idProcess));
        if(noMoreWorkForMe){
            FAssertLF(procHasWorkAtLevel(idxLevel, idProcess) == false);
            break;
          }

        // Copy and count ALL the cells (even the ones outside the working interval)
        int totalNbCellsAtLevel = 0;
        do{
            iterArray[totalNbCellsAtLevel++] = octreeIterator;
          } while(octreeIterator.moveRight());
        avoidGotoLeftIterator.moveUp();
        octreeIterator = avoidGotoLeftIterator;

        int iterMpiRequests       = 0; // The iterator for send/recv requests
        int iterMpiRequestsSize   = 0; // The iterator for send/recv requests

        int nbCellsToSkip     = 0; // The number of cells to send
        // Skip all the cells that are out of my working interval
        while(nbCellsToSkip < totalNbCellsAtLevel && iterArray[nbCellsToSkip].getCurrentGlobalIndex() < getWorkingInterval(idxLevel, idProcess).leftIndex){
            ++nbCellsToSkip;
          }

        // We need to know if we will recv something in order to know if threads skip the last cell
        int nbCellsForThreads = totalNbCellsAtLevel; // totalNbCellsAtLevel or totalNbCellsAtLevel-1
        bool hasToReceive = false;
        if(idProcess != nbProcess-1 && procHasWorkAtLevel(idxLevel , idProcess)){
            // Find the first proc that may send to me
            while(firstProcThatSend < nbProcess && !procHasWorkAtLevel(idxLevel+1, firstProcThatSend) ){
                firstProcThatSend += 1;
              }
            // Do we have to receive?
            if(firstProcThatSend < nbProcess && procHasWorkAtLevel(idxLevel+1, firstProcThatSend) && procCoversMyRightBorderCell(idxLevel, firstProcThatSend) ){
                hasToReceive = true;
                // Threads do not compute the last cell, we will do it once data are received
                nbCellsForThreads -= 1;
              }
          }

        FLOG(parallelCounter.tic());
559 560
#pragma omp parallel num_threads(MaxThreads)
	{
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
	  KernelClass* myThreadkernels = (kernels[omp_get_thread_num()]);
	  //This single section post and receive the comms, and then do the M2M associated with it.
#pragma omp single nowait
	  {
	    FLOG(singleCounter.tic());
	    // Master proc never send
	    if(idProcess != 0){
		// Skip process that have no work at that level
		while( currentProcIdToSendTo && !procHasWorkAtLevel(idxLevel, currentProcIdToSendTo)  ){
		    --currentProcIdToSendTo;
		  }
		// Does the next proc that has work is sharing the parent of my left cell
		if(procHasWorkAtLevel(idxLevel, currentProcIdToSendTo) && procCoversMyLeftBorderCell(idxLevel, currentProcIdToSendTo)){
		    FAssertLF(nbCellsToSkip != 0);

		    char packageFlags = 0;
		    sendBuffer.write(packageFlags);

		    // Only the cell the most on the right out of my working interval should be taken in
		    // consideration (at pos nbCellsToSkip-1) other (x < nbCellsToSkip-1) have already been sent
		    const CellClass* const* const child = iterArray[nbCellsToSkip-1].getCurrentChild();
		    for(int idxChild = 0 ; idxChild < 8 ; ++idxChild){
			// Check if child exists and it was part of my working interval
			if( child[idxChild] && getWorkingInterval((idxLevel+1), idProcess).leftIndex <= child[idxChild]->getMortonIndex() ){
			    // Add the cell to the buffer
			    child[idxChild]->serializeUp(sendBuffer);
			    packageFlags = char(packageFlags | (0x1 << idxChild));
			  }
		      }
		    // Add the flag as first value
		    sendBuffer.writeAt(0,packageFlags);
		    // Post the message
		    bufferSize = sendBuffer.getSize();
		    MPI_Isend(&bufferSize, 1, FMpi::GetType(bufferSize), currentProcIdToSendTo,
			      FMpi::TagFmmM2MSize + idxLevel, comm.getComm(), &requestsSize[iterMpiRequestsSize++]);
		    FAssertLF(sendBuffer.getSize() < std::numeric_limits<int>::max());
		    MPI_Isend(sendBuffer.data(), int(sendBuffer.getSize()), MPI_BYTE, currentProcIdToSendTo,
			      FMpi::TagFmmM2M + idxLevel, comm.getComm(), &requests[iterMpiRequests++]);
		  }
600 601
	      }

602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
	    //Post receive, Datas needed in several parts of the section
	    int nbProcThatSendToMe = 0;

	    if(hasToReceive){
		//Test : if the firstProcThatSend father minimal value in interval is lesser than mine
		int idProcSource = firstProcThatSend;
		// Find the last proc that should send to me
		while( idProcSource < nbProcess
		       && ( !procHasWorkAtLevel(idxLevel+1, idProcSource) || procCoversMyRightBorderCell(idxLevel, idProcSource) )){
		    if(procHasWorkAtLevel(idxLevel+1, idProcSource) && procCoversMyRightBorderCell(idxLevel, idProcSource)){
			MPI_Irecv(&recvBufferSize[nbProcThatSendToMe], 1, FMpi::GetType(recvBufferSize[nbProcThatSendToMe]),
				  idProcSource, FMpi::TagFmmM2MSize + idxLevel, comm.getComm(), &requestsSize[iterMpiRequestsSize++]);
			nbProcThatSendToMe += 1;
			FAssertLF(nbProcThatSendToMe <= 7);
		      }
		    ++idProcSource;
		  }
619 620
	      }

621 622 623 624 625 626
	    //Wait For the comms, and do the work
	    // Are we sending or waiting anything?
	    if(iterMpiRequestsSize){
		FAssertLF(iterMpiRequestsSize <= 8);
		MPI_Waitall( iterMpiRequestsSize, requestsSize, statusSize);
	      }
627

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
	    if(hasToReceive){
		nbProcThatSendToMe = 0;
		//Test : if the firstProcThatSend father minimal value in interval is lesser than mine
		int idProcSource = firstProcThatSend;
		// Find the last proc that should send to me
		while( idProcSource < nbProcess
		       && ( !procHasWorkAtLevel(idxLevel+1, idProcSource) || procCoversMyRightBorderCell(idxLevel, idProcSource) )){
		    if(procHasWorkAtLevel(idxLevel+1, idProcSource) && procCoversMyRightBorderCell(idxLevel, idProcSource)){
			recvBuffer[nbProcThatSendToMe].cleanAndResize(recvBufferSize[nbProcThatSendToMe]);
			FAssertLF(recvBufferSize[nbProcThatSendToMe] < std::numeric_limits<int>::max());
			MPI_Irecv(recvBuffer[nbProcThatSendToMe].data(), int(recvBufferSize[nbProcThatSendToMe]), MPI_BYTE,
				  idProcSource, FMpi::TagFmmM2M + idxLevel, comm.getComm(), &requests[iterMpiRequests++]);
			nbProcThatSendToMe += 1;
			FAssertLF(nbProcThatSendToMe <= 7);
		      }
		    ++idProcSource;
		  }
645 646
	      }

647 648 649 650 651 652
	    //Wait For the comms, and do the work
	    // Are we sending or waiting anything?
	    if(iterMpiRequests){
		FAssertLF(iterMpiRequests <= 8);
		MPI_Waitall( iterMpiRequests, requests, status);
	      }
653

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
	    // We had received something so we need to proceed the last M2M
	    if( hasToReceive ){
		FAssertLF(iterMpiRequests != 0);
		CellClass* children[8];
		memcpy(children, iterArray[totalNbCellsAtLevel - 1].getCurrentChild(), 8 * sizeof(CellClass*));

		// Retreive data and merge my child and the child from others
		for(int idxProc = 0 ; idxProc < nbProcThatSendToMe ; ++idxProc){
		    unsigned packageFlags = unsigned(recvBuffer[idxProc].getValue<unsigned char>());

		    int position = 0;
		    int positionToInsert = 0;
		    while( packageFlags && position < 8){
			while(!(packageFlags & 0x1)){
			    packageFlags >>= 1;
			    ++position;
			  }
			FAssertLF(positionToInsert < 7);
			FAssertLF(position < 8);
			FAssertLF(!children[position], "Already has a cell here");
			recvBufferCells[positionToInsert].deserializeUp(recvBuffer[idxProc]);
			children[position] = (CellClass*) &recvBufferCells[positionToInsert];

			packageFlags >>= 1;
			position += 1;
			positionToInsert += 1;
		      }

		    recvBuffer[idxProc].seek(0);
		  }
		// Finally compute

		multipole_t* parent_multipole
		    = &(iterArray[totalNbCellsAtLevel - 1].getCurrentCell()->getMultipoleData());
		const symbolic_data_t* parent_symbolic
		    = iterArray[totalNbCellsAtLevel - 1].getCurrentCell();

		std::array<const multipole_t*, 8> child_multipoles {};
		std::transform(children, children+8, std::begin(child_multipoles),
			       [](CellClass* c) {
		  return (c == nullptr ? nullptr
				       : &(c->getMultipoleData()));
		});
		std::array<const symbolic_data_t*, 8> child_symbolics {};
		std::copy(children, children+8,
			  std::begin(child_symbolics));

		myThreadkernels->M2M(
		      parent_multipole,
		      parent_symbolic,
		      child_multipoles.data(),
		      child_symbolics.data()
		      );
		firstProcThatSend += nbProcThatSendToMe - 1;
708
	      }
709 710 711 712
	    // Reset buffer
	    sendBuffer.reset();
	    FLOG(singleCounter.tac());
	  }//End Of Single section
713

714 715 716
	  // All threads proceed the M2M
#pragma omp for nowait schedule(dynamic, userChunkSize)
	  for( int idxCell = nbCellsToSkip ; idxCell < nbCellsForThreads ; ++idxCell){
717

718
	      CellClass** children = iterArray[idxCell].getCurrentChild();
719

720 721 722 723
	      multipole_t* parent_multipole
		  = &(iterArray[idxCell].getCurrentCell()->getMultipoleData());
	      const symbolic_data_t* parent_symbolic
		  = iterArray[idxCell].getCurrentCell();
724

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
	      std::array<const multipole_t*, 8> child_multipoles {};
	      std::transform(children, children+8, std::begin(child_multipoles),
			     [](CellClass* c) {
		return (c == nullptr ? nullptr
				     : &(c->getMultipoleData()));
	      });
	      std::array<const symbolic_data_t*, 8> child_symbolics {};
	      std::copy(children, children+8,
			std::begin(child_symbolics));

	      myThreadkernels->M2M(
		    parent_multipole,
		    parent_symbolic,
		    child_multipoles.data(),
		    child_symbolics.data()
		    );
	    }
	}//End of parallel section
	FLOG(parallelCounter.tac());
      }
745

746 747 748 749 750 751
    FLOG(counterTime.tac());
    FLOG(computationCounter.tac());
    FLOG( FLog::Controller << "\tFinished (@Upward Pass (M2M) = "  << counterTime.elapsed() << " s)\n" );
    FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.elapsed() << " s\n" );
    FLOG( FLog::Controller << "\t\t Single : " << singleCounter.cumulated() << " s\n" );
    FLOG( FLog::Controller << "\t\t Parallel : " << parallelCounter.cumulated() << " s\n" );
752

753

754
    //////////////////////////////////////////////////////////////////
755
    //Periodicity
756
    //////////////////////////////////////////////////////////////////
757

758 759 760
    octreeIterator = typename OctreeClass::Iterator(tree);

    if( idProcess == 0){
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 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
        int iterRequestsSize = 0;

        for(int idxProc = 1 ; idxProc < nbProcess ; ++idxProc ){
            if( procHasWorkAtLevel(1,idxProc) ){
                MPI_Irecv(&recvBufferSize[iterRequestsSize], 1, FMpi::GetType(recvBufferSize[iterRequestsSize]), idxProc,
                          FMpi::TagFmmM2MSize, comm.getComm(), &requests[iterRequestsSize]);
                iterRequestsSize += 1;
                FAssertLF(iterRequestsSize <= 7);
              }
          }
        MPI_Waitall( iterRequestsSize, requests, MPI_STATUSES_IGNORE);

        int iterRequests = 0;

        for(int idxProc = 1 ; idxProc < nbProcess ; ++idxProc ){
            if( procHasWorkAtLevel(1,idxProc) ){
                recvBuffer[iterRequests].cleanAndResize(recvBufferSize[iterRequests]);
                FAssertLF(recvBufferSize[iterRequests] < std::numeric_limits<int>::max());
                MPI_Irecv(recvBuffer[iterRequests].data(), int(recvBufferSize[iterRequests]), MPI_BYTE, idxProc,
                          FMpi::TagFmmM2M, comm.getComm(), &requests[iterRequests]);
                iterRequests += 1;
                FAssertLF(iterRequests <= 7);
              }
          }

        MPI_Waitall( iterRequests, requests, MPI_STATUSES_IGNORE);

        CellClass* currentChild[8];
        memcpy(currentChild, octreeIterator.getCurrentBox(), 8 * sizeof(CellClass*));

        // retreive data and merge my child and the child from others
        int counterProc = 0;
        for(int idxProc = 1 ; idxProc < nbProcess ; ++idxProc){
            if( procHasWorkAtLevel(1,idxProc) ){
                recvBuffer[counterProc].seek(0);
                unsigned state = unsigned(recvBuffer[counterProc].getValue<unsigned char>());

                int position = 0;
                int positionToInsert = 0;
                while( state && position < 8){
                    while(!(state & 0x1)){
                        state >>= 1;
                        ++position;
                      }
                    FAssertLF(positionToInsert < 7);
                    FAssertLF(position < 8);
                    FAssertLF(!currentChild[position], "Already has a cell here");

                    recvBufferCells[positionToInsert].deserializeUp(recvBuffer[counterProc]);

                    currentChild[position] = (CellClass*) &recvBufferCells[positionToInsert];

                    state >>= 1;
                    position += 1;
                    positionToInsert += 1;
                  }

                FAssertLF(recvBuffer[counterProc].tell() == recvBufferSize[counterProc]);
                counterProc += 1;
              }
          }


        multipole_t* parent_multipole
            = &(rootCellFromProc.getMultipoleData());
        const symbolic_data_t* parent_symbolic
            = &(rootCellFromProc);

        std::array<const multipole_t*, 8> child_multipoles {};
        std::transform(currentChild, currentChild + 8,
                       std::begin(child_multipoles),
                       [](const CellClass* c) {
            return (c == nullptr)
                ? nullptr
                : &(c->getMultipoleData());
          });
        std::array<const symbolic_data_t*, 8> child_symbolics {};




        // (*kernels[0]).M2M( &rootCellFromProc , currentChild, offsetRealTree);
        (*kernels[0]).M2M(
              parent_multipole,
              parent_symbolic,
              child_multipoles.data(),
              child_symbolics.data()
              );

        processPeriodicLevels();
851 852
      }
    else {
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
        if( hasWorkAtLevel(1) ){
            const int firstChild = getWorkingInterval(1, idProcess).leftIndex & 7;
            const int lastChild  = getWorkingInterval(1, idProcess).rightIndex & 7;

            CellClass** child = octreeIterator.getCurrentBox();

            char state = 0;
            sendBuffer.write(state);

            for(int idxChild = firstChild ; idxChild <= lastChild ; ++idxChild){
                if( child[idxChild] ){
                    child[idxChild]->serializeUp(sendBuffer);
                    state = char( state | (0x1 << idxChild));
                  }
              }
            sendBuffer.writeAt(0,state);
            FSize sizeToSend = sendBuffer.getSize();
            MPI_Send(&sizeToSend, 1, MPI_LONG_LONG, 0, FMpi::TagFmmM2MSize, comm.getComm());
            MPI_Send(sendBuffer.data(), int(sendBuffer.getSize()), MPI_BYTE, 0, FMpi::TagFmmM2M, comm.getComm());
          }
873 874
      }
  }
875

876 877 878
  /////////////////////////////////////////////////////////////////////////////
  // Downard
  /////////////////////////////////////////////////////////////////////////////
879

880

881 882 883 884 885 886 887 888
  void transferPass(){
    FLOG( FLog::Controller.write("\tStart Downward Pass (M2L)\n").write(FLog::Flush); );
    FLOG(FTic counterTime);
    FLOG(FTic computationCounter);
    FLOG(FTic sendCounter);
    FLOG(FTic receiveCounter);
    FLOG(FTic prepareCounter);
    FLOG(FTic gatherCounter);
889

890 891 892
    //////////////////////////////////////////////////////////////////
    // First know what to send to who
    //////////////////////////////////////////////////////////////////
893

894 895 896 897 898 899 900 901
    // pointer to send
    std::unique_ptr<FVector<typename OctreeClass::Iterator>[]> toSend(new FVector<typename OctreeClass::Iterator>[nbProcess * OctreeHeight]);
    // index
    long long int*const indexToSend = new long long int[nbProcess * OctreeHeight];
    memset(indexToSend, 0, sizeof(long long int) * nbProcess * OctreeHeight);
    // To know which one has need someone
    FBoolArray** const leafsNeedOther = new FBoolArray*[OctreeHeight];
    memset(leafsNeedOther, 0, sizeof(FBoolArray*) * OctreeHeight);
902

903 904 905 906
    // All process say to each others
    // what the will send to who
    long long int*const globalReceiveMap = new long long  int[nbProcess * nbProcess * OctreeHeight];
    memset(globalReceiveMap, 0, sizeof(long long  int) * nbProcess * nbProcess * OctreeHeight);
907

908 909
    FBufferWriter**const sendBuffer = new FBufferWriter*[nbProcess * OctreeHeight];
    memset(sendBuffer, 0, sizeof(FBufferWriter*) * nbProcess * OctreeHeight);
910

911 912
    FBufferReader**const recvBuffer = new FBufferReader*[nbProcess * OctreeHeight];
    memset(recvBuffer, 0, sizeof(FBufferReader*) * nbProcess * OctreeHeight);
913

914 915 916 917
#pragma omp parallel num_threads(MaxThreads)
    {
#pragma omp master
      {
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        {
          FLOG(prepareCounter.tic());

          std::unique_ptr<typename OctreeClass::Iterator[]> iterArrayLocal(new typename OctreeClass::Iterator[numberOfLeafs]);

          // To know if a leaf has been already sent to a proc
          bool*const alreadySent = new bool[nbProcess];
          memset(alreadySent, 0, sizeof(bool) * nbProcess);

          typename OctreeClass::Iterator octreeIterator(tree);
          ////octreeIterator.moveDown();
          typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
          // for each levels
          for(int idxLevel = 1 ; idxLevel < OctreeHeight ; ++idxLevel ){

              if(!procHasWorkAtLevel(idxLevel, idProcess)){
                  avoidGotoLeftIterator.moveDown();
                  octreeIterator = avoidGotoLeftIterator;
                  continue;
                }

              int numberOfCells = 0;

              while(octreeIterator.getCurrentGlobalIndex() <  getWorkingInterval(idxLevel , idProcess).leftIndex){
                  octreeIterator.moveRight();
                }

              // for each cells
              do{
                  iterArrayLocal[numberOfCells] = octreeIterator;
                  ++numberOfCells;
                } while(octreeIterator.moveRight());
              avoidGotoLeftIterator.moveDown();
              octreeIterator = avoidGotoLeftIterator;

              leafsNeedOther[idxLevel] = new FBoolArray(numberOfCells);

              // Which cell potentialy needs other data and in the same time
              // are potentialy needed by other
              int neighborsPosition[/*189+26+1*/216];
              MortonIndex neighborsIndexes[/*189+26+1*/216];
              for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
                  // Find the M2L neigbors of a cell
                  const int counter = getPeriodicInteractionNeighbors(iterArray[idxCell].getCurrentGlobalCoordinate(),
                                                                      idxLevel,
                                                                      neighborsIndexes, neighborsPosition, AllDirs, leafLevelSeparationCriteria);

                  memset(alreadySent, false, sizeof(bool) * nbProcess);
                  bool needOther = false;
                  // Test each negibors to know which one do not belong to us
                  for(int idxNeigh = 0 ; idxNeigh < counter ; ++idxNeigh){
                      if(neighborsIndexes[idxNeigh] < getWorkingInterval(idxLevel , idProcess).leftIndex
                         || (getWorkingInterval(idxLevel , idProcess).rightIndex) < neighborsIndexes[idxNeigh]){
                          int procToReceive = idProcess;
                          while( 0 != procToReceive && neighborsIndexes[idxNeigh] < getWorkingInterval(idxLevel , procToReceive).leftIndex ){
                              --procToReceive;
                            }
                          while( procToReceive != nbProcess -1 && (getWorkingInterval(idxLevel , procToReceive).rightIndex) < neighborsIndexes[idxNeigh]){
                              ++procToReceive;
                            }
                          // Maybe already sent to that proc?
                          if( !alreadySent[procToReceive]
                              && getWorkingInterval(idxLevel , procToReceive).leftIndex <= neighborsIndexes[idxNeigh]
                              && neighborsIndexes[idxNeigh] <= getWorkingInterval(idxLevel , procToReceive).rightIndex){

                              alreadySent[procToReceive] = true;

                              needOther = true;

                              toSend[idxLevel * nbProcess + procToReceive].push(iterArrayLocal[idxCell]);
                              if(indexToSend[idxLevel * nbProcess + procToReceive] == 0){
                                  indexToSend[idxLevel * nbProcess + procToReceive] = sizeof(int);
                                }
                              indexToSend[idxLevel * nbProcess + procToReceive] += iterArrayLocal[idxCell].getCurrentCell()->getSavedSizeUp();
                              indexToSend[idxLevel * nbProcess + procToReceive] += sizeof(MortonIndex);
                              indexToSend[idxLevel * nbProcess + procToReceive] += sizeof(FSize);
                            }
                        }
                    }
                  if(needOther){
                      leafsNeedOther[idxLevel]->set(idxCell,true);
                    }
                }
            }
          FLOG(prepareCounter.tac());

          delete[] alreadySent;
        }

        //////////////////////////////////////////////////////////////////
        // Gather this information
        //////////////////////////////////////////////////////////////////

        FLOG(gatherCounter.tic());
        FMpi::MpiAssert( MPI_Allgather( indexToSend, nbProcess * OctreeHeight, MPI_LONG_LONG_INT, globalReceiveMap, nbProcess * OctreeHeight, MPI_LONG_LONG_INT, comm.getComm()),  __LINE__ );
        FLOG(gatherCounter.tac());

        //////////////////////////////////////////////////////////////////
        // Send and receive for real
        //////////////////////////////////////////////////////////////////

        FLOG(sendCounter.tic());
        // Then they can send and receive (because they know what they will receive)
        // To send in asynchrone way
        std::vector<MPI_Request> requests;
        requests.reserve(2 * nbProcess * OctreeHeight);

        for(int idxLevel = 1 ; idxLevel < OctreeHeight ; ++idxLevel ){
            for(int idxProc = 0 ; idxProc < nbProcess ; ++idxProc){
                const long long int toSendAtProcAtLevel = indexToSend[idxLevel * nbProcess + idxProc];
                if(toSendAtProcAtLevel != 0){
                    sendBuffer[idxLevel * nbProcess + idxProc] = new FBufferWriter(toSendAtProcAtLevel);

                    sendBuffer[idxLevel * nbProcess + idxProc]->write(int(toSend[idxLevel * nbProcess + idxProc].getSize()));

                    for(int idxLeaf = 0 ; idxLeaf < toSend[idxLevel * nbProcess + idxProc].getSize(); ++idxLeaf){
                        const FSize currentTell = sendBuffer[idxLevel * nbProcess + idxProc]->getSize();
                        sendBuffer[idxLevel * nbProcess + idxProc]->write(currentTell);
                        const MortonIndex cellIndex = toSend[idxLevel * nbProcess + idxProc][idxLeaf].getCurrentGlobalIndex();
                        sendBuffer[idxLevel * nbProcess + idxProc]->write(cellIndex);
                        toSend[idxLevel * nbProcess + idxProc][idxLeaf].getCurrentCell()->serializeUp(*sendBuffer[idxLevel * nbProcess + idxProc]);
                      }

                    FAssertLF(sendBuffer[idxLevel * nbProcess + idxProc]->getSize() == toSendAtProcAtLevel);

                    FAssertLF(sendBuffer[idxLevel * nbProcess + idxProc]->getSize() < std::numeric_limits<int>::max());
                    FMpi::ISendSplit(sendBuffer[idxLevel * nbProcess + idxProc]->data(),
                        sendBuffer[idxLevel * nbProcess + idxProc]->getSize(), idxProc,
                        FMpi::TagLast + idxLevel*100, comm, &requests);
                  }

                const long long int toReceiveFromProcAtLevel = globalReceiveMap[(idxProc * nbProcess * OctreeHeight) + idxLevel * nbProcess + idProcess];
                if(toReceiveFromProcAtLevel){
                    recvBuffer[idxLevel * nbProcess + idxProc] = new FBufferReader(toReceiveFromProcAtLevel);

                    FAssertLF(recvBuffer[idxLevel * nbProcess + idxProc]->getCapacity() < std::numeric_limits<int>::max());
                    FMpi::IRecvSplit(recvBuffer[idxLevel * nbProcess + idxProc]->data(),
                        recvBuffer[idxLevel * nbProcess + idxProc]->getCapacity(), idxProc,
                        FMpi::TagLast + idxLevel*100, comm, &requests);
                  }
              }
          }

        //////////////////////////////////////////////////////////////////
        // Wait received data and compute
        //////////////////////////////////////////////////////////////////

        // Wait to receive every things (and send every things)
        FMpi::MpiAssert(MPI_Waitall(int(requests.size()), requests.data(), MPI_STATUS_IGNORE), __LINE__);

        FLOG(sendCounter.tac());
1069 1070 1071 1072 1073
      }//End of Master region

      //////////////////////////////////////////////////////////////////
      // Do M2L
      //////////////////////////////////////////////////////////////////
1074

1075 1076
#pragma omp single nowait
      {
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
        typename OctreeClass::Iterator octreeIterator(tree);
        ////octreeIterator.moveDown();
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
        // Now we can compute all the data
        // for each levels
        for(int idxLevel = 1 ; idxLevel < OctreeHeight ; ++idxLevel ){
            const int fakeLevel = idxLevel + offsetRealTree;

            const int separationCriteria = (idxLevel != OctreeHeight-1 ? 1 : leafLevelSeparationCriteria);

            if(!procHasWorkAtLevel(idxLevel, idProcess)){
                avoidGotoLeftIterator.moveDown();
                octreeIterator = avoidGotoLeftIterator;
                continue;
              }

            int numberOfCells = 0;
            while(octreeIterator.getCurrentGlobalIndex() <  getWorkingInterval(idxLevel , idProcess).leftIndex){
                octreeIterator.moveRight();
              }
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
              } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

            FLOG(computationCounter.tic());
            {
              const int chunckSize = userChunkSize;
              for(int idxCell = 0 ; idxCell < numberOfCells ; idxCell += chunckSize){
1109
#pragma omp task default(none) shared(numberOfCells,idxLevel) firstprivate(idxCell) //+ shared(chunckSize)
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
		  {
		    KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
		    const CellClass* neighbors[342];
		    int neighborPositions[342];

		    const int nbCellToCompute = FMath::Min(chunckSize, numberOfCells-idxCell);
		    for(int idxCellToCompute = idxCell ; idxCellToCompute < idxCell+nbCellToCompute ; ++idxCellToCompute){
			const int counter = tree->getPeriodicInteractionNeighbors(neighbors, neighborPositions,
										  iterArray[idxCellToCompute].getCurrentGlobalCoordinate(),
										  idxLevel, AllDirs, separationCriteria);

			if(counter) {
			    local_expansion_t* target_local_expansion
				= &(iterArray[idxCellToCompute].getCurrentCell()
				    ->getLocalExpansionData());
			    const symbolic_data_t* target_symbolic
				= iterArray[idxCellToCompute].getCurrentCell();

			    std::array<const multipole_t*, 342> source_multipoles {};
			    std::transform(neighbors, neighbors + counter,
					   std::begin(source_multipoles),
					   [](const CellClass* c) {
				return c == nullptr
				    ? nullptr
				    : &(c->getMultipoleData());
			      });
			    std::array<const symbolic_data_t*, 342> source_symbolics  {};
			    std::copy(neighbors, neighbors + counter,
				      std::begin(source_symbolics));

			    myThreadkernels->M2L(
				  target_local_expansion,
				  target_symbolic,
				  source_multipoles.data(),
				  source_symbolics.data(),
				  neighborPositions,
				  counter
				  );
			  }

		      }
		  }
1152
		}
1153
	    }//End of task spawning
1154

1155
#pragma omp taskwait
1156

1157
	    for(int idxThread = 0 ; idxThread < omp_get_num_threads() ; ++idxThread){
1158
#pragma omp task  default(none) firstprivate(idxThread,idxLevel)
1159 1160 1161 1162
		{
		  kernels[idxThread]->finishedLevelM2L(fakeLevel);
		}
	      }
1163
#pragma omp taskwait
1164

1165
	    FLOG(computationCounter.tac());
1166 1167
	  }
      }
1168
    }
1169 1170


1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    {
      FLOG(receiveCounter.tic());
      typename OctreeClass::Iterator octreeIterator(tree);
      ////octreeIterator.moveDown();
      typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
      // compute the second time
      // for each levels
      for(int idxLevel = 1 ; idxLevel < OctreeHeight ; ++idxLevel ){
          const int fakeLevel = idxLevel + offsetRealTree;

          const int separationCriteria = (fakeLevel != OctreeHeight-1 ? 1 : leafLevelSeparationCriteria);

          if(!procHasWorkAtLevel(idxLevel, idProcess)){
              avoidGotoLeftIterator.moveDown();
              octreeIterator = avoidGotoLeftIterator;
              continue;
            }

          // put the received data into a temporary tree
          FLightOctree<CellClass> tempTree;
          for(int idxProc = 0 ; idxProc < nbProcess ; ++idxProc){
              if(recvBuffer[idxLevel * nbProcess + idxProc]){
                  const int toReceiveFromProcAtLevel = recvBuffer[idxLevel * nbProcess + idxProc]->template getValue<int>();

                  for(int idxCell = 0 ; idxCell < toReceiveFromProcAtLevel ; ++idxCell){
                      const FSize currentTell = recvBuffer[idxLevel * nbProcess + idxProc]->tell();
                      const FSize verifCurrentTell = recvBuffer[idxLevel * nbProcess + idxProc]->template getValue<FSize>();
                      FAssertLF(currentTell == verifCurrentTell, currentTell, " ", verifCurrentTell);

                      const MortonIndex cellIndex = recvBuffer[idxLevel * nbProcess + idxProc]->template getValue<MortonIndex>();

                      CellClass* const newCell = new CellClass;
                      newCell->setMortonIndex(cellIndex);
                      newCell->deserializeUp(*recvBuffer[idxLevel * nbProcess + idxProc]);

                      tempTree.insertCell(cellIndex, idxLevel, newCell);
                    }

                  FAssertLF(globalReceiveMap[(idxProc * nbProcess * OctreeHeight) + idxLevel * nbProcess + idProcess] ==
                      recvBuffer[idxLevel * nbProcess + idxProc]->tell());
                }
            }

          // take cells from our octree only if they are
          // linked to received data
          int numberOfCells = 0;
          int realCellId = 0;

          while(octreeIterator.getCurrentGlobalIndex() <  getWorkingInterval(idxLevel , idProcess).leftIndex){
              octreeIterator.moveRight();
            }
          // for each cells
          do{
              // copy cells that need data from others
              if(leafsNeedOther[idxLevel]->get(realCellId++)){
                  iterArray[numberOfCells++] = octreeIterator;
                }
            } while(octreeIterator.moveRight());
          avoidGotoLeftIterator.moveDown();
          octreeIterator = avoidGotoLeftIterator;

          delete leafsNeedOther[idxLevel];
          leafsNeedOther[idxLevel] = nullptr;

          // Compute this cells
          FLOG(computationCounter.tic());
1237
#pragma omp parallel num_threads(MaxThreads)
1238 1239 1240 1241 1242 1243
	  {
	    KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
	    MortonIndex neighborsIndex[/*189+26+1*/216];
	    int neighborsPosition[/*189+26+1*/216];
	    const CellClass* neighbors[342];
	    int neighborPositions[342];
1244 1245

#pragma omp for  schedule(dynamic, userChunkSize) nowait
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
	    for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
		const int counterNeighbors = getPeriodicInteractionNeighbors(iterArray[idxCell].getCurrentGlobalCoordinate(), idxLevel, neighborsIndex, neighborsPosition, AllDirs, separationCriteria);
		int counter = 0;
		// does we receive this index from someone?
		for(int idxNeig = 0 ;idxNeig < counterNeighbors ; ++idxNeig){
		    if(neighborsIndex[idxNeig] < (getWorkingInterval(idxLevel , idProcess).leftIndex)
		       || (getWorkingInterval(idxLevel , idProcess).rightIndex) < neighborsIndex[idxNeig]){

			CellClass*const otherCell = tempTree.getCell(neighborsIndex[idxNeig], idxLevel);

			if(otherCell){
			    neighbors[counter] = otherCell;
			    neighborPositions[counter] = neighborsPosition[idxNeig] ;
			    ++counter;
			  }
		      }
		  }
		// need to compute
		if(counter) {
		    local_expansion_t* target_local_expansion
			= &(iterArray[idxCell].getCurrentCell()->getLocalExpansionData());
		    const symbolic_data_t* target_symbolic
			= iterArray[idxCell].getCurrentCell();

		    std::array<const multipole_t*, 342> source_multipoles {};
		    std::transform(neighbors, neighbors + counter,
				   std::begin(source_multipoles),
				   [](const CellClass* c) {
			return c == nullptr
			    ? nullptr
			    : &(c->getMultipoleData());
		      });
		    std::array<const symbolic_data_t*, 342> source_symbolics  {};
		    std::copy(neighbors, neighbors + counter,
			      std::begin(source_symbolics));

		    myThreadkernels->M2L(
			  target_local_expansion,
			  target_symbolic,
			  source_multipoles.data(),
			  source_symbolics.data(),
			  neighborPositions,
			  counter
			  );
		  }
1291
	      }
1292 1293

	    myThreadkernels->finishedLevelM2L(fakeLevel);
1294
	  }
1295
	  FLOG(computationCounter.tac());
1296
	}
1297
      FLOG(receiveCounter.tac());
1298 1299
    }

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    for(int idxComm = 0 ; idxComm < nbProcess * OctreeHeight; ++idxComm){
        delete sendBuffer[idxComm];
        delete recvBuffer[idxComm];
      }
    for(int idxComm = 0 ; idxComm < OctreeHeight; ++idxComm){
        delete leafsNeedOther[idxComm];
      }
    delete[] sendBuffer;
    delete[] recvBuffer;
    delete[] indexToSend;
    delete[] leafsNeedOther;
    delete[] globalReceiveMap;
1312 1313


1314 1315 1316 1317 1318 1319 1320
    FLOG( FLog::Controller << "\tFinished (@Downward Pass (M2L) = "  << counterTime.tacAndElapsed() << " s)\n" );
    FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
    FLOG( FLog::Controller << "\t\t Send : " << sendCounter.cumulated() << " s\n" );
    FLOG( FLog::Controller << "\t\t Receive : " << receiveCounter.cumulated() << " s\n" );
    FLOG( FLog::Controller << "\t\t Gather : " << gatherCounter.cumulated() << " s\n" );
    FLOG( FLog::Controller << "\t\t Prepare : " << prepareCounter.cumulated() << " s\n" );
    FLOG( FLog::Controller.flush());
1321

1322
  }
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339