FFmmAlgorithmThread.hpp 16.9 KB
Newer Older
1
// ===================================================================================
2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright ScalFmm 2011 INRIA, Olivier Coulaud, Bérenger Bramas, Matthias Messner
// 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 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

#include "../Utils/FAssertable.hpp"
#include "../Utils/FDebug.hpp"
#include "../Utils/FTrace.hpp"
#include "../Utils/FTic.hpp"
#include "../Utils/FGlobal.hpp"

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


#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
*
* Of course this class does not deallocate pointer given in arguements.
*
berenger-bramas's avatar
berenger-bramas committed
44
* When using this algorithm the P2P is thread safe.
45
*/
46
template<class OctreeClass, class CellClass, class ContainerClass, class KernelClass, class LeafClass>
47
class FFmmAlgorithmThread : protected FAssertable{
berenger-bramas's avatar
berenger-bramas committed
48 49
    OctreeClass* const tree;                  //< The octree to work on
    KernelClass** kernels;                    //< The kernels
50

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

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

    const int MaxThreads;
58

59 60
    const int OctreeHeight;

61 62 63 64 65 66
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
67
    FFmmAlgorithmThread(OctreeClass* const inTree, KernelClass* const inKernels)
68 69
        : tree(inTree) , kernels(0), iterArray(0), leafsNumber(0),
          MaxThreads(omp_get_max_threads()), OctreeHeight(tree->getHeight()) {
70

71
        fassert(tree, "tree cannot be null", __LINE__, __FILE__);
72

berenger-bramas's avatar
berenger-bramas committed
73
        this->kernels = new KernelClass*[MaxThreads];
berenger-bramas's avatar
berenger-bramas committed
74
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
berenger-bramas's avatar
berenger-bramas committed
75
            this->kernels[idxThread] = new KernelClass(*inKernels);
76 77
        }

berenger-bramas's avatar
berenger-bramas committed
78
        FDEBUG(FDebug::Controller << "FFmmAlgorithmThread (Max Thread " << omp_get_max_threads() << ")\n");
79 80 81 82
    }

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

    /**
      * To execute the fmm algorithm
      * Call this function to run the complete algorithm
      */
    void execute(){
94
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
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];
111
        fassert(iterArray, "iterArray bad alloc", __LINE__, __FILE__);
112 113

        bottomPass();
114

115 116
        upwardPass();

117 118
        transferPass();

119 120 121 122 123
        downardPass();

        directPass();

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

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

132 133
    /** P2M */
    void bottomPass(){
134
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
135
        FDEBUG( FDebug::Controller.write("\tStart Bottom Pass\n").write(FDebug::Flush) );
berenger-bramas's avatar
berenger-bramas committed
136
        FDEBUG(FTic counterTime);
137

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

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

160
        FDEBUG( FDebug::Controller << "\tFinished (@Bottom Pass (P2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
161
        FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.elapsed() << " s\n" );
162

163 164
    }

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

169 170
    /** M2M */
    void upwardPass(){
171
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
172
        FDEBUG( FDebug::Controller.write("\tStart Upward Pass\n").write(FDebug::Flush); );
berenger-bramas's avatar
berenger-bramas committed
173 174
        FDEBUG(FTic counterTime);
        FDEBUG(FTic computationCounter);
175 176

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

        // for each levels
        for(int idxLevel = OctreeHeight - 2 ; idxLevel > 1 ; --idxLevel ){
184
            FDEBUG(FTic counterTimeLevel);
185
            int numberOfCells = 0;
186 187
            // for each cells
            do{
188 189
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
190 191 192 193 194
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveUp();
            octreeIterator = avoidGotoLeftIterator;// equal octreeIterator.moveUp(); octreeIterator.gotoLeft();

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

206
            FDEBUG(computationCounter.tac());
207
            FDEBUG( FDebug::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
208 209
        }

berenger-bramas's avatar
berenger-bramas committed
210

211
        FDEBUG( FDebug::Controller << "\tFinished (@Upward Pass (M2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
berenger-bramas's avatar
berenger-bramas committed
212
        FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
213

214 215
    }

berenger-bramas's avatar
berenger-bramas committed
216
    /////////////////////////////////////////////////////////////////////////////
217
    // Transfer
berenger-bramas's avatar
berenger-bramas committed
218 219
    /////////////////////////////////////////////////////////////////////////////

220
    /** M2L L2L */
221
    void transferPass(){
222
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
223

224 225 226
        FDEBUG( FDebug::Controller.write("\tStart Downward Pass (M2L)\n").write(FDebug::Flush); );
        FDEBUG(FTic counterTime);
        FDEBUG(FTic computationCounter);
berenger-bramas's avatar
berenger-bramas committed
227

228 229 230 231 232 233
        typename OctreeClass::Iterator octreeIterator(tree);
        octreeIterator.moveDown();
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        // for each levels
        for(int idxLevel = 2 ; idxLevel < OctreeHeight ; ++idxLevel ){
234
            FDEBUG(FTic counterTimeLevel);
235 236 237 238 239 240 241 242 243 244
            int numberOfCells = 0;
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

            FDEBUG(computationCounter.tic());
245
            #pragma omp parallel
246 247
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
248
                const CellClass* neighbors[343];
249

250
                #pragma omp for  schedule(dynamic) nowait
251
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
252
                    const int counter = tree->getInteractionNeighbors(neighbors,  iterArray[idxCell].getCurrentGlobalCoordinate(),idxLevel);
253
                    if(counter) myThreadkernels->M2L( iterArray[idxCell].getCurrentCell() , neighbors, counter, idxLevel);
254
                }
255 256 257 258

                FDEBUG(computationCounter.tic());
                myThreadkernels->finishedLevelM2L(idxLevel);
                FDEBUG(computationCounter.tac());
259
            }
260
            FDEBUG(computationCounter.tac());
261
            FDEBUG( FDebug::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
262 263
        }

264 265 266
        FDEBUG( FDebug::Controller << "\tFinished (@Downward Pass (M2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
    }
berenger-bramas's avatar
berenger-bramas committed
267

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    /////////////////////////////////////////////////////////////////////////////
    // Downard
    /////////////////////////////////////////////////////////////////////////////

    void downardPass(){ // second L2L
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );

        FDEBUG( FDebug::Controller.write("\tStart Downward Pass (L2L)\n").write(FDebug::Flush); );
        FDEBUG(FTic counterTime);
        FDEBUG(FTic computationCounter);

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

        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        const int heightMinusOne = OctreeHeight - 1;
        // for each levels exepted leaf level
        for(int idxLevel = 2 ; idxLevel < heightMinusOne ; ++idxLevel ){
287
            FDEBUG(FTic counterTimeLevel);
288 289 290 291 292 293 294 295 296 297
            int numberOfCells = 0;
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

            FDEBUG(computationCounter.tic());
298
            #pragma omp parallel
299 300
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
301
                #pragma omp for nowait
302 303
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
                    myThreadkernels->L2L( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
304 305
                }
            }
306
            FDEBUG(computationCounter.tac());
307
            FDEBUG( FDebug::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
308 309
        }

310 311
        FDEBUG( FDebug::Controller << "\tFinished (@Downward Pass (L2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
312 313
    }

314 315


berenger-bramas's avatar
berenger-bramas committed
316 317 318 319
    /////////////////////////////////////////////////////////////////////////////
    // Direct
    /////////////////////////////////////////////////////////////////////////////

320 321
    /** P2P */
    void directPass(){
322
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
323
        FDEBUG( FDebug::Controller.write("\tStart Direct Pass\n").write(FDebug::Flush); );
berenger-bramas's avatar
berenger-bramas committed
324 325
        FDEBUG(FTic counterTime);
        FDEBUG(FTic computationCounter);
326
        FDEBUG(FTic computationCounterP2P);
327

328
        omp_lock_t lockShape[SizeShape];
329
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
330
            omp_init_lock(&lockShape[idxShape]);
331 332
        }

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

341
        const int LeafIndex = OctreeHeight - 1;
342 343 344 345 346 347 348

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

349
        #pragma omp parallel
350
        {
351

352 353 354
            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)));
355
            const int end = (tempEnd > this->leafsNumber ? this->leafsNumber : tempEnd);
356

berenger-bramas's avatar
berenger-bramas committed
357
            typename OctreeClass::Iterator octreeIterator(tree);
358
            octreeIterator.gotoBottomLeft();
359 360 361 362 363

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

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

371 372 373
                omp_set_lock(&lockShape[shapePosition]);
                const int positionToWork = startPosAtShape[shapePosition]++;
                omp_unset_lock(&lockShape[shapePosition]);
374

375 376 377 378
                leafsDataArray[positionToWork].index = octreeIterator.getCurrentGlobalIndex();
                leafsDataArray[positionToWork].cell = octreeIterator.getCurrentCell();
                leafsDataArray[positionToWork].targets = octreeIterator.getCurrentListTargets();
                leafsDataArray[positionToWork].sources = octreeIterator.getCurrentListSrc();
379

380 381
                octreeIterator.moveRight();
            }
382

383
            #pragma omp barrier
384

berenger-bramas's avatar
berenger-bramas committed
385
            FDEBUG(if(!omp_get_thread_num()) computationCounter.tic());
386

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

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

395
                #pragma omp for schedule(dynamic)
396 397 398
                for(int idxLeafs = previous ; idxLeafs < endAtThisShape ; ++idxLeafs){
                    LeafData& currentIter = leafsDataArray[idxLeafs];
                    myThreadkernels.L2P(currentIter.cell, currentIter.targets);
399
                    // need the current particles and neighbors particles
400
                    FDEBUG(if(!omp_get_thread_num()) computationCounterP2P.tic());
401
                    const int counter = tree->getLeafsNeighbors(neighbors, currentIter.cell->getCoordinate(), LeafIndex);
402 403
                    myThreadkernels.P2P(currentIter.cell->getCoordinate(), currentIter.targets,
                                        currentIter.sources, neighbors, counter);
404
                    FDEBUG(if(!omp_get_thread_num()) computationCounterP2P.tac());
405
                }
406 407

                previous = endAtThisShape;
408 409
            }
        }
410

411 412
        FDEBUG(computationCounter.tac());

413
        delete [] leafsDataArray;
414 415 416 417
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            omp_destroy_lock(&lockShape[idxShape]);
        }

418

419 420
        FDEBUG( FDebug::Controller << "\tFinished (@Direct Pass (L2P + P2P) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FDEBUG( FDebug::Controller << "\t\t Computation L2P + P2P : " << computationCounter.cumulated() << " s\n" );
421
        FDEBUG( FDebug::Controller << "\t\t Computation P2P : " << computationCounterP2P.cumulated() << " s\n" );
422

423 424 425 426 427 428 429
    }

};


#endif //FFMMALGORITHMTHREAD_HPP

430