FFmmAlgorithmThread.hpp 16.5 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];
berenger-bramas's avatar
berenger-bramas committed
75
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
berenger-bramas's avatar
berenger-bramas committed
76
            this->kernels[idxThread] = new KernelClass(*inKernels);
77 78
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
79
        FLOG(FLog::Controller << "FFmmAlgorithmThread (Max Thread " << omp_get_max_threads() << ")\n");
80 81 82 83
    }

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

    /**
      * To execute the fmm algorithm
      * Call this function to run the complete algorithm
      */
94
    void execute(const unsigned operationsToProceed = FFmmNearAndFarFields){
95 96 97 98 99 100

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

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

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

113
        if(operationsToProceed & FFmmP2M) bottomPass();
114

115
        if(operationsToProceed & FFmmM2M) upwardPass();
116

117
        if(operationsToProceed & FFmmM2L) transferPass();
118

119
        if(operationsToProceed & FFmmL2L) downardPass();
120

BRAMAS Berenger's avatar
BRAMAS Berenger committed
121
        if((operationsToProceed & FFmmP2P) || (operationsToProceed & FFmmL2P)) directPass();
122 123

        delete [] iterArray;
124
        iterArray = nullptr;
125 126
    }

127
private:
berenger-bramas's avatar
berenger-bramas committed
128 129 130 131
    /////////////////////////////////////////////////////////////////////////////
    // P2M
    /////////////////////////////////////////////////////////////////////////////

132 133
    /** P2M */
    void bottomPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
134
        FLOG( FLog::Controller.write("\tStart Bottom Pass\n").write(FLog::Flush) );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
135
        FLOG(FTic counterTime);
136

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

BRAMAS Berenger's avatar
BRAMAS Berenger committed
146
        FLOG(FTic computationCounter);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
147
        #pragma omp parallel
148
        {
berenger-bramas's avatar
berenger-bramas committed
149
            KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
BRAMAS Berenger's avatar
BRAMAS Berenger committed
150
            #pragma omp for nowait schedule(dynamic, 50)
151 152 153 154 155 156
            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
157
        FLOG(computationCounter.tac() );
158

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

162 163
    }

berenger-bramas's avatar
berenger-bramas committed
164 165 166 167
    /////////////////////////////////////////////////////////////////////////////
    // Upward
    /////////////////////////////////////////////////////////////////////////////

168 169
    /** M2M */
    void upwardPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
170
        FLOG( FLog::Controller.write("\tStart Upward Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
171 172
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
173 174

        // Start from leal level - 1
berenger-bramas's avatar
berenger-bramas committed
175
        typename OctreeClass::Iterator octreeIterator(tree);
176 177
        octreeIterator.gotoBottomLeft();
        octreeIterator.moveUp();
berenger-bramas's avatar
berenger-bramas committed
178
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
179 180 181

        // for each levels
        for(int idxLevel = OctreeHeight - 2 ; idxLevel > 1 ; --idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
182
            FLOG(FTic counterTimeLevel);
183
            int numberOfCells = 0;
184 185
            // for each cells
            do{
186 187
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
188 189 190 191
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveUp();
            octreeIterator = avoidGotoLeftIterator;// equal octreeIterator.moveUp(); octreeIterator.gotoLeft();

BRAMAS Berenger's avatar
BRAMAS Berenger committed
192
            FLOG(computationCounter.tic());
193
            #pragma omp parallel
194
            {
berenger-bramas's avatar
berenger-bramas committed
195
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
BRAMAS Berenger's avatar
BRAMAS Berenger committed
196
                #pragma omp for nowait  schedule(dynamic, 50)
197
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
198 199
                    // We need the current cell and the child
                    // child is an array (of 8 child) that may be null
200
                    myThreadkernels->M2M( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
201 202
                }
            }
berenger-bramas's avatar
berenger-bramas committed
203

BRAMAS Berenger's avatar
BRAMAS Berenger committed
204
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
205
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
206 207
        }

berenger-bramas's avatar
berenger-bramas committed
208

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

212 213
    }

berenger-bramas's avatar
berenger-bramas committed
214
    /////////////////////////////////////////////////////////////////////////////
215
    // Transfer
berenger-bramas's avatar
berenger-bramas committed
216 217
    /////////////////////////////////////////////////////////////////////////////

218
    /** M2L L2L */
219
    void transferPass(){
220

BRAMAS Berenger's avatar
BRAMAS Berenger committed
221
        FLOG( FLog::Controller.write("\tStart Downward Pass (M2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
222 223
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
berenger-bramas's avatar
berenger-bramas committed
224

225 226 227 228 229 230
        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
231
            FLOG(FTic counterTimeLevel);
232 233 234 235 236 237 238 239 240
            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
241
            FLOG(computationCounter.tic());
242
            #pragma omp parallel
243 244
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
245
                const CellClass* neighbors[343];
246

BRAMAS Berenger's avatar
BRAMAS Berenger committed
247
                #pragma omp for  schedule(dynamic, 50) nowait
248
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
249
                    const int counter = tree->getInteractionNeighbors(neighbors,  iterArray[idxCell].getCurrentGlobalCoordinate(),idxLevel);
250
                    if(counter) myThreadkernels->M2L( iterArray[idxCell].getCurrentCell() , neighbors, counter, idxLevel);
251
                }
252 253

                myThreadkernels->finishedLevelM2L(idxLevel);
254
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
255
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
256
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
257 258
        }

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

263
    /////////////////////////////////////////////////////////////////////////////
COULAUD Olivier's avatar
COULAUD Olivier committed
264
    // Downward
265 266 267 268
    /////////////////////////////////////////////////////////////////////////////

    void downardPass(){ // second L2L

BRAMAS Berenger's avatar
BRAMAS Berenger committed
269
        FLOG( FLog::Controller.write("\tStart Downward Pass (L2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
270 271
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
272 273 274 275 276 277 278

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

        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        const int heightMinusOne = OctreeHeight - 1;
COULAUD Olivier's avatar
COULAUD Olivier committed
279
        // for each levels excepted leaf level
280
        for(int idxLevel = 2 ; idxLevel < heightMinusOne ; ++idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
281
            FLOG(FTic counterTimeLevel);
282 283 284 285 286 287 288 289 290
            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
291
            FLOG(computationCounter.tic());
292
            #pragma omp parallel
293 294
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
BRAMAS Berenger's avatar
BRAMAS Berenger committed
295
                #pragma omp for nowait schedule(dynamic, 50)
296 297
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
                    myThreadkernels->L2L( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
298 299
                }
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
300
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
301
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
302 303
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
304 305
        FLOG( FLog::Controller << "\tFinished (@Downward Pass (L2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
306 307
    }

308 309


berenger-bramas's avatar
berenger-bramas committed
310 311 312 313
    /////////////////////////////////////////////////////////////////////////////
    // Direct
    /////////////////////////////////////////////////////////////////////////////

314 315
    /** P2P */
    void directPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
316
        FLOG( FLog::Controller.write("\tStart Direct Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
317 318 319
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
        FLOG(FTic computationCounterP2P);
320

321
        omp_lock_t lockShape[SizeShape];
322
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
323
            omp_init_lock(&lockShape[idxShape]);
324 325
        }

326 327 328
        struct LeafData{
            MortonIndex index;
            CellClass* cell;
berenger-bramas's avatar
berenger-bramas committed
329 330
            ContainerClass* targets;
            ContainerClass* sources;
331 332 333
        };
        LeafData* const leafsDataArray = new LeafData[this->leafsNumber];

334
        const int LeafIndex = OctreeHeight - 1;
335 336 337 338 339 340 341

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

342
        #pragma omp parallel
343
        {
344

345 346 347
            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)));
348
            const int end = (tempEnd > this->leafsNumber ? this->leafsNumber : tempEnd);
349

berenger-bramas's avatar
berenger-bramas committed
350
            typename OctreeClass::Iterator octreeIterator(tree);
351
            octreeIterator.gotoBottomLeft();
352 353 354 355 356

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

357
            // for each leafs
358
            for(int idxMyLeafs = start ; idxMyLeafs < end ; ++idxMyLeafs){
359
                //iterArray[leafs] = octreeIterator;
360
                //++leafs;
361
                const FTreeCoordinate& coord = octreeIterator.getCurrentGlobalCoordinate();
362
                const int shapePosition = (coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3);
363

364 365 366
                omp_set_lock(&lockShape[shapePosition]);
                const int positionToWork = startPosAtShape[shapePosition]++;
                omp_unset_lock(&lockShape[shapePosition]);
367

COULAUD Olivier's avatar
COULAUD Olivier committed
368 369
                leafsDataArray[positionToWork].index   = octreeIterator.getCurrentGlobalIndex();
                leafsDataArray[positionToWork].cell    = octreeIterator.getCurrentCell();
370 371
                leafsDataArray[positionToWork].targets = octreeIterator.getCurrentListTargets();
                leafsDataArray[positionToWork].sources = octreeIterator.getCurrentListSrc();
372

373 374
                octreeIterator.moveRight();
            }
375

376
            #pragma omp barrier
377

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

berenger-bramas's avatar
berenger-bramas committed
380
            KernelClass& myThreadkernels = (*kernels[omp_get_thread_num()]);
381
            // There is a maximum of 26 neighbors
berenger-bramas's avatar
berenger-bramas committed
382
            ContainerClass* neighbors[27];
383
            int previous = 0;
384 385

            for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
386
                const int endAtThisShape = this->shapeLeaf[idxShape] + previous;
387

BRAMAS Berenger's avatar
BRAMAS Berenger committed
388
                #pragma omp for schedule(dynamic, 50)
389 390 391
                for(int idxLeafs = previous ; idxLeafs < endAtThisShape ; ++idxLeafs){
                    LeafData& currentIter = leafsDataArray[idxLeafs];
                    myThreadkernels.L2P(currentIter.cell, currentIter.targets);
392
                    // need the current particles and neighbors particles
BRAMAS Berenger's avatar
BRAMAS Berenger committed
393
                    FLOG(if(!omp_get_thread_num()) computationCounterP2P.tic());
394
                    const int counter = tree->getLeafsNeighbors(neighbors, currentIter.cell->getCoordinate(), LeafIndex);
395 396
                    myThreadkernels.P2P(currentIter.cell->getCoordinate(), currentIter.targets,
                                        currentIter.sources, neighbors, counter);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
397
                    FLOG(if(!omp_get_thread_num()) computationCounterP2P.tac());
398
                }
399 400

                previous = endAtThisShape;
401 402
            }
        }
403

BRAMAS Berenger's avatar
BRAMAS Berenger committed
404
        FLOG(computationCounter.tac());
405

406
        delete [] leafsDataArray;
407 408 409 410
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            omp_destroy_lock(&lockShape[idxShape]);
        }

411

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

416 417 418 419 420 421 422
    }

};


#endif //FFMMALGORITHMTHREAD_HPP

423