FFmmAlgorithmThread.hpp 17.4 KB
Newer Older
1
// ===================================================================================
2
// Copyright ScalFmm 2011 INRIA, Olivier Coulaud, Berenger Bramas, Matthias Messner
3 4 5 6 7 8 9 10 11 12 13 14
// olivier.coulaud@inria.fr, berenger.bramas@inria.fr
// This software is a computer program whose purpose is to compute the FMM.
//
// This software is governed by the CeCILL-C and LGPL licenses and
// abiding by the rules of distribution of free software.  
// 
// This program 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 and CeCILL-C Licenses for more details.
// "http://www.cecill.info". 
// "http://www.gnu.org/licenses".
15
// ===================================================================================
16 17
#ifndef FFMMALGORITHMTHREAD_HPP
#define FFMMALGORITHMTHREAD_HPP
18

19

BRAMAS Berenger's avatar
BRAMAS Berenger committed
20
#include "../Utils/FAssert.hpp"
BRAMAS Berenger's avatar
BRAMAS Berenger committed
21
#include "../Utils/FLog.hpp"
22

23 24 25 26 27
#include "../Utils/FTic.hpp"
#include "../Utils/FGlobal.hpp"

#include "../Containers/FOctree.hpp"

28
#include "FCoreCommon.hpp"
29 30 31 32 33 34 35 36 37 38 39 40 41 42

#include <omp.h>

/**
* @author Berenger Bramas (berenger.bramas@inria.fr)
* @class FFmmAlgorithmThread
* @brief
* Please read the license
*
* This class is a threaded FMM algorithm
* 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
*
COULAUD Olivier's avatar
COULAUD Olivier committed
43
* Of course this class does not deallocate pointer given in arguments.
44
*
berenger-bramas's avatar
berenger-bramas committed
45
* When using this algorithm the P2P is thread safe.
46
*/
47
template<class OctreeClass, class CellClass, class ContainerClass, class KernelClass, class LeafClass>
BRAMAS Berenger's avatar
BRAMAS Berenger committed
48
class FFmmAlgorithmThread : public FAbstractAlgorithm{
berenger-bramas's avatar
berenger-bramas committed
49 50
    OctreeClass* const tree;                  //< The octree to work on
    KernelClass** kernels;                    //< The kernels
51

berenger-bramas's avatar
berenger-bramas committed
52
    typename OctreeClass::Iterator* iterArray;
53
    int leafsNumber;
54 55

    static const int SizeShape = 3*3*3;
berenger-bramas's avatar
berenger-bramas committed
56 57 58
    int shapeLeaf[SizeShape];    

    const int MaxThreads;
59

60 61
    const int OctreeHeight;

62 63 64 65 66 67
public:
    /** 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
      */
berenger-bramas's avatar
berenger-bramas committed
68
    FFmmAlgorithmThread(OctreeClass* const inTree, KernelClass* const inKernels)
69
        : tree(inTree) , kernels(nullptr), iterArray(nullptr), leafsNumber(0),
70
          MaxThreads(omp_get_max_threads()), OctreeHeight(tree->getHeight()) {
71

BRAMAS Berenger's avatar
BRAMAS Berenger committed
72
        FAssertLF(tree, "tree cannot be null");
73

berenger-bramas's avatar
berenger-bramas committed
74
        this->kernels = new KernelClass*[MaxThreads];
75
        #pragma omp parallel for schedule(static)
berenger-bramas's avatar
berenger-bramas committed
76
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
77
            #pragma omp critical (InitFFmmAlgorithmThread)
78 79 80
            {
                this->kernels[idxThread] = new KernelClass(*inKernels);
            }
81 82
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
83
        FLOG(FLog::Controller << "FFmmAlgorithmThread (Max Thread " << omp_get_max_threads() << ")\n");
84 85 86 87
    }

    /** Default destructor */
    virtual ~FFmmAlgorithmThread(){
berenger-bramas's avatar
berenger-bramas committed
88
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
89 90
            delete this->kernels[idxThread];
        }
berenger-bramas's avatar
berenger-bramas committed
91
        delete [] this->kernels;
92 93 94 95 96 97
    }

    /**
      * To execute the fmm algorithm
      * Call this function to run the complete algorithm
      */
98
    void execute(const unsigned operationsToProceed = FFmmNearAndFarFields){
99 100 101 102 103 104

        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            this->shapeLeaf[idxShape] = 0;
        }

        // Count leaf
105
        leafsNumber = 0;
berenger-bramas's avatar
berenger-bramas committed
106
        typename OctreeClass::Iterator octreeIterator(tree);
107 108
        octreeIterator.gotoBottomLeft();
        do{
109
            ++leafsNumber;
110
            const FTreeCoordinate& coord = octreeIterator.getCurrentCell()->getCoordinate();
111 112 113
            ++this->shapeLeaf[(coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3)];

        } while(octreeIterator.moveRight());
berenger-bramas's avatar
berenger-bramas committed
114
        iterArray = new typename OctreeClass::Iterator[leafsNumber];
BRAMAS Berenger's avatar
BRAMAS Berenger committed
115
        FAssertLF(iterArray, "iterArray bad alloc");
116

117
        if(operationsToProceed & FFmmP2M) bottomPass();
118

119
        if(operationsToProceed & FFmmM2M) upwardPass();
120

121
        if(operationsToProceed & FFmmM2L) transferPass();
122

123
        if(operationsToProceed & FFmmL2L) downardPass();
124

125
        if((operationsToProceed & FFmmP2P) || (operationsToProceed & FFmmL2P)) directPass((operationsToProceed & FFmmP2P),(operationsToProceed & FFmmL2P));
126 127

        delete [] iterArray;
128
        iterArray = nullptr;
129 130
    }

131
private:
berenger-bramas's avatar
berenger-bramas committed
132 133 134 135
    /////////////////////////////////////////////////////////////////////////////
    // P2M
    /////////////////////////////////////////////////////////////////////////////

136 137
    /** P2M */
    void bottomPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
138
        FLOG( FLog::Controller.write("\tStart Bottom Pass\n").write(FLog::Flush) );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
139
        FLOG(FTic counterTime);
140

berenger-bramas's avatar
berenger-bramas committed
141
        typename OctreeClass::Iterator octreeIterator(tree);
142 143 144 145 146 147 148 149
        int leafs = 0;
        // Iterate on leafs
        octreeIterator.gotoBottomLeft();
        do{
            iterArray[leafs] = octreeIterator;
            ++leafs;
        } while(octreeIterator.moveRight());

150 151
        const int chunkSize = FMath::Max(1 , leafs/(omp_get_max_threads()*omp_get_max_threads()));

BRAMAS Berenger's avatar
BRAMAS Berenger committed
152
        FLOG(FTic computationCounter);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
153
        #pragma omp parallel
154
        {
berenger-bramas's avatar
berenger-bramas committed
155
            KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
156
            #pragma omp for nowait schedule(dynamic, chunkSize)
157 158 159 160 161 162
            for(int idxLeafs = 0 ; idxLeafs < leafs ; ++idxLeafs){
                // We need the current cell that represent the leaf
                // and the list of particles
                myThreadkernels->P2M( iterArray[idxLeafs].getCurrentCell() , iterArray[idxLeafs].getCurrentListSrc());
            }
        }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
163
        FLOG(computationCounter.tac() );
164

BRAMAS Berenger's avatar
BRAMAS Berenger committed
165 166
        FLOG( FLog::Controller << "\tFinished (@Bottom Pass (P2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.elapsed() << " s\n" );
167

168 169
    }

berenger-bramas's avatar
berenger-bramas committed
170 171 172 173
    /////////////////////////////////////////////////////////////////////////////
    // Upward
    /////////////////////////////////////////////////////////////////////////////

174 175
    /** M2M */
    void upwardPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
176
        FLOG( FLog::Controller.write("\tStart Upward Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
177 178
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
179 180

        // Start from leal level - 1
berenger-bramas's avatar
berenger-bramas committed
181
        typename OctreeClass::Iterator octreeIterator(tree);
182 183
        octreeIterator.gotoBottomLeft();
        octreeIterator.moveUp();
berenger-bramas's avatar
berenger-bramas committed
184
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
185 186 187

        // for each levels
        for(int idxLevel = OctreeHeight - 2 ; idxLevel > 1 ; --idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
188
            FLOG(FTic counterTimeLevel);
189
            int numberOfCells = 0;
190 191
            // for each cells
            do{
192 193
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
194 195 196 197
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveUp();
            octreeIterator = avoidGotoLeftIterator;// equal octreeIterator.moveUp(); octreeIterator.gotoLeft();

198 199
            const int chunkSize = FMath::Max(1 , numberOfCells/(omp_get_max_threads()*omp_get_max_threads()));

BRAMAS Berenger's avatar
BRAMAS Berenger committed
200
            FLOG(computationCounter.tic());
201
            #pragma omp parallel
202
            {
berenger-bramas's avatar
berenger-bramas committed
203
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
204
                #pragma omp for nowait  schedule(dynamic, chunkSize)
205
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
206 207
                    // We need the current cell and the child
                    // child is an array (of 8 child) that may be null
208
                    myThreadkernels->M2M( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
209 210
                }
            }
berenger-bramas's avatar
berenger-bramas committed
211

BRAMAS Berenger's avatar
BRAMAS Berenger committed
212
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
213
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
214 215
        }

berenger-bramas's avatar
berenger-bramas committed
216

BRAMAS Berenger's avatar
BRAMAS Berenger committed
217 218
        FLOG( FLog::Controller << "\tFinished (@Upward Pass (M2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
219

220 221
    }

berenger-bramas's avatar
berenger-bramas committed
222
    /////////////////////////////////////////////////////////////////////////////
223
    // Transfer
berenger-bramas's avatar
berenger-bramas committed
224 225
    /////////////////////////////////////////////////////////////////////////////

226
    /** M2L L2L */
227
    void transferPass(){
228

BRAMAS Berenger's avatar
BRAMAS Berenger committed
229
        FLOG( FLog::Controller.write("\tStart Downward Pass (M2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
230 231
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
berenger-bramas's avatar
berenger-bramas committed
232

233 234 235 236 237 238
        typename OctreeClass::Iterator octreeIterator(tree);
        octreeIterator.moveDown();
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        // for each levels
        for(int idxLevel = 2 ; idxLevel < OctreeHeight ; ++idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
239
            FLOG(FTic counterTimeLevel);
240 241 242 243 244 245 246 247 248
            int numberOfCells = 0;
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

249 250
            const int chunkSize = FMath::Max(1 , numberOfCells/(omp_get_max_threads()*omp_get_max_threads()));

BRAMAS Berenger's avatar
BRAMAS Berenger committed
251
            FLOG(computationCounter.tic());
252
            #pragma omp parallel
253 254
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
255
                const CellClass* neighbors[343];
256

257
                #pragma omp for  schedule(dynamic, chunkSize) nowait
258
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
259
                    const int counter = tree->getInteractionNeighbors(neighbors,  iterArray[idxCell].getCurrentGlobalCoordinate(),idxLevel);
260
                    if(counter) myThreadkernels->M2L( iterArray[idxCell].getCurrentCell() , neighbors, counter, idxLevel);
261
                }
262 263

                myThreadkernels->finishedLevelM2L(idxLevel);
264
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
265
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
266
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
267 268
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
269 270
        FLOG( FLog::Controller << "\tFinished (@Downward Pass (M2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
271
    }
berenger-bramas's avatar
berenger-bramas committed
272

273
    /////////////////////////////////////////////////////////////////////////////
COULAUD Olivier's avatar
COULAUD Olivier committed
274
    // Downward
275 276 277 278
    /////////////////////////////////////////////////////////////////////////////

    void downardPass(){ // second L2L

BRAMAS Berenger's avatar
BRAMAS Berenger committed
279
        FLOG( FLog::Controller.write("\tStart Downward Pass (L2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
280 281
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
282 283 284 285 286 287 288

        typename OctreeClass::Iterator octreeIterator(tree);
        octreeIterator.moveDown();

        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        const int heightMinusOne = OctreeHeight - 1;
COULAUD Olivier's avatar
COULAUD Olivier committed
289
        // for each levels excepted leaf level
290
        for(int idxLevel = 2 ; idxLevel < heightMinusOne ; ++idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
291
            FLOG(FTic counterTimeLevel);
292 293 294 295 296 297 298 299 300
            int numberOfCells = 0;
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

BRAMAS Berenger's avatar
BRAMAS Berenger committed
301
            FLOG(computationCounter.tic());
302
            const int chunkSize = FMath::Max(1 , numberOfCells/(omp_get_max_threads()*omp_get_max_threads()));
303
            #pragma omp parallel
304 305
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
306
                #pragma omp for nowait schedule(dynamic, chunkSize)
307 308
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
                    myThreadkernels->L2L( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
309 310
                }
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
311
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
312
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
313 314
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
315 316
        FLOG( FLog::Controller << "\tFinished (@Downward Pass (L2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
317 318
    }

319 320


berenger-bramas's avatar
berenger-bramas committed
321 322 323 324
    /////////////////////////////////////////////////////////////////////////////
    // Direct
    /////////////////////////////////////////////////////////////////////////////

325
    /** P2P */
326
    void directPass(const bool p2pEnabled, const bool l2pEnabled){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
327
        FLOG( FLog::Controller.write("\tStart Direct Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
328 329 330
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
        FLOG(FTic computationCounterP2P);
331

332
        omp_lock_t lockShape[SizeShape];
333
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
334
            omp_init_lock(&lockShape[idxShape]);
335 336
        }

337 338 339
        struct LeafData{
            MortonIndex index;
            CellClass* cell;
berenger-bramas's avatar
berenger-bramas committed
340 341
            ContainerClass* targets;
            ContainerClass* sources;
342 343 344
        };
        LeafData* const leafsDataArray = new LeafData[this->leafsNumber];

345
        const int LeafIndex = OctreeHeight - 1;
346 347 348 349 350 351 352

        int startPosAtShape[SizeShape];
        startPosAtShape[0] = 0;
        for(int idxShape = 1 ; idxShape < SizeShape ; ++idxShape){
            startPosAtShape[idxShape] = startPosAtShape[idxShape-1] + this->shapeLeaf[idxShape-1];
        }

353
        #pragma omp parallel
354
        {
355

356 357 358
            const float step = float(this->leafsNumber) / float(omp_get_num_threads());
            const int start = int(FMath::Ceil(step * float(omp_get_thread_num())));
            const int tempEnd = int(FMath::Ceil(step * float(omp_get_thread_num()+1)));
359
            const int end = (tempEnd > this->leafsNumber ? this->leafsNumber : tempEnd);
360

berenger-bramas's avatar
berenger-bramas committed
361
            typename OctreeClass::Iterator octreeIterator(tree);
362
            octreeIterator.gotoBottomLeft();
363 364 365 366 367

            for(int idxPreLeaf = 0 ; idxPreLeaf < start ; ++idxPreLeaf){
                octreeIterator.moveRight();
            }

368
            // for each leafs
369
            for(int idxMyLeafs = start ; idxMyLeafs < end ; ++idxMyLeafs){
370
                //iterArray[leafs] = octreeIterator;
371
                //++leafs;
372
                const FTreeCoordinate& coord = octreeIterator.getCurrentGlobalCoordinate();
373
                const int shapePosition = (coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3);
374

375 376 377
                omp_set_lock(&lockShape[shapePosition]);
                const int positionToWork = startPosAtShape[shapePosition]++;
                omp_unset_lock(&lockShape[shapePosition]);
378

COULAUD Olivier's avatar
COULAUD Olivier committed
379 380
                leafsDataArray[positionToWork].index   = octreeIterator.getCurrentGlobalIndex();
                leafsDataArray[positionToWork].cell    = octreeIterator.getCurrentCell();
381 382
                leafsDataArray[positionToWork].targets = octreeIterator.getCurrentListTargets();
                leafsDataArray[positionToWork].sources = octreeIterator.getCurrentListSrc();
383

384 385
                octreeIterator.moveRight();
            }
386

387
            #pragma omp barrier
388

BRAMAS Berenger's avatar
BRAMAS Berenger committed
389
            FLOG(if(!omp_get_thread_num()) computationCounter.tic());
390

berenger-bramas's avatar
berenger-bramas committed
391
            KernelClass& myThreadkernels = (*kernels[omp_get_thread_num()]);
392
            // There is a maximum of 26 neighbors
berenger-bramas's avatar
berenger-bramas committed
393
            ContainerClass* neighbors[27];
394
            int previous = 0;
395 396

            for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
397
                const int endAtThisShape = this->shapeLeaf[idxShape] + previous;
398 399
                const int chunkSize = FMath::Max(1 , endAtThisShape/(omp_get_num_threads()*omp_get_num_threads()));
                #pragma omp for schedule(dynamic, chunkSize)
400 401
                for(int idxLeafs = previous ; idxLeafs < endAtThisShape ; ++idxLeafs){
                    LeafData& currentIter = leafsDataArray[idxLeafs];
402 403 404 405 406 407 408 409 410 411 412
                    if(l2pEnabled){
                        myThreadkernels.L2P(currentIter.cell, currentIter.targets);
                    }
                    if(p2pEnabled){
                        // need the current particles and neighbors particles
                        FLOG(if(!omp_get_thread_num()) computationCounterP2P.tic());
                        const int counter = tree->getLeafsNeighbors(neighbors, currentIter.cell->getCoordinate(), LeafIndex);
                        myThreadkernels.P2P(currentIter.cell->getCoordinate(), currentIter.targets,
                                            currentIter.sources, neighbors, counter);
                        FLOG(if(!omp_get_thread_num()) computationCounterP2P.tac());
                    }
413
                }
414 415

                previous = endAtThisShape;
416 417
            }
        }
418

BRAMAS Berenger's avatar
BRAMAS Berenger committed
419
        FLOG(computationCounter.tac());
420

421
        delete [] leafsDataArray;
422 423 424 425
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            omp_destroy_lock(&lockShape[idxShape]);
        }

426

BRAMAS Berenger's avatar
BRAMAS Berenger committed
427
        FLOG( FLog::Controller << "\tFinished (@Direct Pass (L2P + P2P) = "  << counterTime.tacAndElapsed() << "s)\n" );
COULAUD Olivier's avatar
COULAUD Olivier committed
428 429
        FLOG( FLog::Controller << "\t\t Computation L2P + P2P : " << computationCounter.cumulated()    << " s\n" );
        FLOG( FLog::Controller << "\t\t Computation P2P :       " << computationCounterP2P.cumulated() << " s\n" );
430

431 432 433 434 435 436 437
    }

};


#endif //FFMMALGORITHMTHREAD_HPP

438