FChebSymCostKernel.hpp 18.4 KB
Newer Older
Quentin Khan's avatar
Quentin Khan committed
1
// ===================================================================================
2 3 4 5
// Copyright ScalFmm 2016 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.
6
//
7
// This software is governed by the CeCILL-C and LGPL licenses and
8
// abiding by the rules of distribution of free software.
9 10 11
// An extension to the license is given to allow static linking of scalfmm
// inside a proprietary application (no matter its license).
// See the main license file for more details.
12
//
Quentin Khan's avatar
Quentin Khan committed
13 14 15
// 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
16 17 18
// GNU General Public and CeCILL-C Licenses for more details.
// "http://www.cecill.info".
// "http://www.gnu.org/licenses".
Quentin Khan's avatar
Quentin Khan committed
19
// ===================================================================================
20 21 22 23 24 25

// ==== CMAKE ====
// Keep in private GIT
// @SCALFMM_PRIVATE


Quentin Khan's avatar
Quentin Khan committed
26 27 28 29 30 31 32 33 34 35 36 37
#ifndef FCHEBFLOPSSYMKERNEL_HPP
#define FCHEBFLOPSSYMKERNEL_HPP

#include <stdexcept>

#include "Utils/FGlobal.hpp"

#include "Utils/FSmartPointer.hpp"

#include "Components/FAbstractKernels.hpp"

#include "Kernels/Chebyshev/FChebInterpolator.hpp"
38
#include "Kernels/Chebyshev/FChebCell.hpp"
Quentin Khan's avatar
Quentin Khan committed
39 40 41 42 43
#include "Kernels/Interpolation/FInterpSymmetries.hpp"

class FTreeCoordinate;

/**
44
 * \author Quentin Khan, Matthias Messner (original file: FChebFlopsSymKernel)
Quentin Khan's avatar
Quentin Khan committed
45 46 47 48 49 50 51 52 53
 * \brief Cost computation of Chebyshev interpolation based FMM.
 *
 * Please read the license
 *
 * This kernel implements the cost computation of the Chebyshev interpolation
 * based FMM operators exploiting the symmetries in the far-field. It implements
 * all interfaces (P2P, P2M, M2M, M2L, L2L, L2P) which are required by the
 * FFmmAlgorithm and FFmmAlgorithmThread.
 *
54
 * \tparam Freal Type of real number representation
Quentin Khan's avatar
Quentin Khan committed
55 56 57 58
 * \tparam CellClass Type of cell
 * \tparam ContainerClass Type of container to store particles
 * \tparam MatrixKernelClass Type of matrix kernel function
 * \tparam ORDER Chebyshev interpolation order
59
 * \tparam OctreeClass Class of the octree to work on.
Quentin Khan's avatar
Quentin Khan committed
60
 */
61
template < typename FReal, class CellClass, class ContainerClass, class MatrixKernelClass, int ORDER, class OctreeClass>
62
class FChebSymCostKernel : public FAbstractKernels<CellClass, ContainerClass>
Quentin Khan's avatar
Quentin Khan committed
63 64 65
{
    enum {nnodes = TensorTraits<ORDER>::nnodes};
public:
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    // Class types available to the rest of the world
    /// Type of real number representation
    using _FReal = FReal;
    /// Type of cell
    using _CellClass = CellClass;
    /// Type of container to store particles
    using _ContainerClass = ContainerClass;
    /// Type of matrix kernel function
    using _MatrixKernelClass = MatrixKernelClass;
    /// Chebyshev interpolation order
    constexpr static const int order = ORDER; 
    /// Class of the octree to work on
    using _OctreeClass = OctreeClass;


Quentin Khan's avatar
Quentin Khan committed
81 82 83 84 85 86 87 88
    /// Handler to deal with all symmetries: Stores permutation indices and
    /// vectors to reduce 343 different interactions to 16 only.
    struct SymmetryHandler;

    /// Needed for handling all symmetries
    const FSmartPointer<MatrixKernelClass,FSmartPointerMemory> MatrixKernel;
    const FSmartPointer<SymmetryHandler,  FSmartPointerMemory> SymHandler;

89 90
    /// The tree the kernel is working on. Needed to attain cells in the P2P
    /// operator (we only get the particles containers otherwise)
91
    const OctreeClass* const _tree;
Quentin Khan's avatar
Quentin Khan committed
92

93
    /// The tree height
Quentin Khan's avatar
Quentin Khan committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    const unsigned int _treeHeight;

    /// count permuted local and multipole expansions
    unsigned int* countExp;

    /// Flops count for each operator of the FMM. 
    unsigned long long flopsP2M = 0,
        flopsM2M = 0,
        flopsM2L = 0,
        flopsL2L = 0,
        flopsL2P = 0,
        flopsP2P = 0;

    /// Operators count.
    unsigned long long countP2M = 0,
        countM2M = 0,
        countM2L = 0,
        countL2L = 0,
        countL2P = 0,
        countP2P = 0;



    /// start flop counters 
118
    FSize countFlopsM2MorL2L() const
Quentin Khan's avatar
Quentin Khan committed
119
        { return 3 * nnodes * (2*ORDER-1); }
120 121

    FSize countFlopsM2L(const unsigned int nexp, const unsigned int rank) const
Quentin Khan's avatar
Quentin Khan committed
122
        { return nexp * (4*nnodes*rank - rank - nnodes); }
123 124

    FSize countFlopsP2P() const
Quentin Khan's avatar
Quentin Khan committed
125
        { return 34; }
126 127

    FSize countFlopsP2Pmutual() const
Quentin Khan's avatar
Quentin Khan committed
128
        { return 39; }
129 130 131 132 133 134

    FSize countFlopsP2M(const FSize N) const    {
        const FSize first  = N * (18 + (ORDER-2) * 6 + (ORDER-1) * (6 + (ORDER-1) * (6 + (ORDER-1) * 2)));
        const FSize W2 = 3 * ORDER*(2*(ORDER-1)-1);
        const FSize W4 = 3 * (ORDER*(ORDER-1)*(2*(ORDER-1)-1) + ORDER*ORDER*(2*(ORDER-1)-1));
        const FSize W8 = 3 * (2*(ORDER-1)-1) * (ORDER*(ORDER-1)*(ORDER-1) + ORDER*ORDER*(ORDER-1) + nnodes);
Quentin Khan's avatar
Quentin Khan committed
135 136
        return first + W2 + W4 + W8 + nnodes*11;
    }
137 138

    FSize countFlopsL2PTotal(const FSize N) const    {
Quentin Khan's avatar
Quentin Khan committed
139 140 141 142
        const unsigned W0 = nnodes;
        const unsigned W2 = 3 * (ORDER-1)*ORDER*ORDER * 2*ORDER;
        const unsigned W4 = 3 * ORDER*(ORDER-1)*(ORDER-1) * 2*ORDER;
        const unsigned W8 = (ORDER-1)*(ORDER-1)*(ORDER-1) * (2*ORDER-1);
143
        const FSize second = N * (38 + (ORDER-2)*15 + (ORDER-1)*((ORDER-1) * (27 + (ORDER-1) * 16))) + 6;
Quentin Khan's avatar
Quentin Khan committed
144 145 146 147 148 149 150 151 152 153
        return W0 + W2 + W4 + W8 + second;
    }
    // end flop counters

public:
    /**
     * The constructor initializes all constant attributes and it reads the
     * precomputed and compressed M2L operators from a binary file (an
     * runtime_error is thrown if the required file is not valid).
     */
154
    FChebSymCostKernel(OctreeClass* tree,
Quentin Khan's avatar
Quentin Khan committed
155 156 157 158 159 160 161 162 163 164 165 166
                          const FReal Epsilon)
        : MatrixKernel(new MatrixKernelClass()),
          SymHandler(new SymmetryHandler(MatrixKernel.getPtr(), Epsilon)),
          _tree(tree),
          _treeHeight(_tree->getHeight())
        {
            countExp = new unsigned int [343];
        }
    


    /** Copy constructor */
167
    FChebSymCostKernel(const FChebSymCostKernel& other) :
168 169 170 171
        SymHandler(other.SymHandler),
        _tree(other._tree),
        _treeHeight(other._treeHeight)
        {
Quentin Khan's avatar
Quentin Khan committed
172 173 174 175
        countExp = new unsigned int [343];
    }

    /** Destructor */
176
    ~FChebSymCostKernel() {
Quentin Khan's avatar
Quentin Khan committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        delete [] countExp;

    }
    
    void printResults(std::ostream& os) const {
        os << "\n==================================================" 
           << "\n- P2M Flops:" << flopsP2M 
           << "\n- M2M Flops:" << flopsM2M
           << "\n- M2L Flops:" << flopsM2L
           << "\n- L2L Flops:" << flopsL2L
           << "\n- L2P Flops:" << flopsL2P
           << "\n- P2P Flops:" << flopsP2P
           << "\n- Overall Flops = " << flopsP2M + flopsM2M + flopsM2L
            + flopsL2L + flopsL2P + flopsP2P
           << "\n==================================================\n"
           << std::endl;

        os << "P2P count: " << countP2P << std::endl;
        os << "P2M count: " << countP2M << std::endl;
        os << "M2M count: " << countM2M << std::endl;
        os << "M2L count: " << countM2L << std::endl;
        os << "L2L count: " << countL2L << std::endl;
        os << "L2P count: " << countL2P << std::endl;
        
    }
    
    
204
    void P2M(CellClass* const cell, const ContainerClass* const SourceParticles) override {
205
        FSize tmpCost = countFlopsP2M(SourceParticles->getNbParticles());
Quentin Khan's avatar
Quentin Khan committed
206 207 208 209 210 211 212 213 214
        flopsP2M += tmpCost;
        cell->addCost(tmpCost);
        countP2M++;
    }



    void M2M(CellClass* const FRestrict cell,
             const CellClass*const FRestrict *const FRestrict ChildCells,
215
             const int /*TreeLevel*/) override {
216
        FSize flops = 0;
Quentin Khan's avatar
Quentin Khan committed
217 218 219 220 221 222 223 224 225 226 227
        for (unsigned int ChildIndex=0; ChildIndex < 8; ++ChildIndex)
            if (ChildCells[ChildIndex])    flops += countFlopsM2MorL2L();
        flopsM2M += flops;
        cell->addCost(flops);
        countM2M++;
    }




    void M2L(CellClass* const FRestrict cell,
228 229 230 231
             const CellClass* /*SourceCells*/[],
             const int positions[],
             const int size,
             const int /* TreeLevel */) override
Quentin Khan's avatar
Quentin Khan committed
232
        {
233
            FSize flops = 0;
Quentin Khan's avatar
Quentin Khan committed
234 235
            // count how ofter each of the 16 interactions is used
            memset(countExp, 0, sizeof(int) * 343);
236 237
            for (int idx=0; idx<size; ++idx)
                  countExp[SymHandler->pindices[positions[idx]]]++;
Quentin Khan's avatar
Quentin Khan committed
238
            // multiply (mat-mat-mul)
239
            for (int pidx=0; pidx<343; ++pidx)
Quentin Khan's avatar
Quentin Khan committed
240
                if (countExp[pidx])
241 242
                    flops += countFlopsM2L(countExp[pidx], SymHandler->LowRank[pidx])
                        + countExp[pidx]*nnodes;
Quentin Khan's avatar
Quentin Khan committed
243 244 245 246 247 248 249 250
            flopsM2L += flops;
            cell->addCost(flops);
            countM2L++;
        }


    void L2L(const CellClass* const FRestrict /* not needed */,
             CellClass* FRestrict *const FRestrict ChildCells,
251
             const int /* TreeLevel*/) override {
252 253
        FSize flops = 0;
        FSize tmpCost = 0;
Quentin Khan's avatar
Quentin Khan committed
254 255 256 257
        for (unsigned int ChildIndex=0; ChildIndex < 8; ++ChildIndex)
            if (ChildCells[ChildIndex]) {
                tmpCost = countFlopsM2MorL2L() + nnodes;
                flops += tmpCost;
258
                ChildCells[ChildIndex]->addCost(tmpCost);
Quentin Khan's avatar
Quentin Khan committed
259 260
            }

261
        flopsL2L += flops;
Quentin Khan's avatar
Quentin Khan committed
262 263 264 265 266 267
        countL2L++;
    }



    void L2P(const CellClass* const cell,
268
             ContainerClass* const TargetParticles) override {
Quentin Khan's avatar
Quentin Khan committed
269 270 271 272 273 274 275 276
        //// 1.a) apply Sx
        //flopsL2P += countFlopsP2MorL2P(TargetParticlesParticles->getNbParticles()) + TargetParticles->getNbParticles();
        //// 1.b) apply Px (grad Sx)
        //flopsL2P += countFlopsL2PGradient(TargetParticlesParticles->getNbParticles()) + 3 * TargetParticles->getNbParticles();
        
        // or
        
        // 2) apply Sx and Px (grad Sx)
277
        FSize tmpCost = 0;
Quentin Khan's avatar
Quentin Khan committed
278 279 280 281 282 283 284 285 286 287 288
        tmpCost =  countFlopsL2PTotal(TargetParticles->getNbParticles()) + 4 * TargetParticles->getNbParticles();
        flopsL2P += tmpCost;
        cell->addCost(tmpCost);
        countL2P++;
    }

    

    void P2P(const FTreeCoordinate& LeafCellCoordinate, // needed for periodic boundary conditions
             ContainerClass* const FRestrict TargetParticles,
             const ContainerClass* const FRestrict SourceParticles,
289 290 291
             ContainerClass* const NeighborSourceParticles[],
             const int positions[],
             const int size) override {
292 293 294
        FSize tmpCost = 0;
        FSize srcPartCount = SourceParticles->getNbParticles();
        FSize tgtPartCount = TargetParticles->getNbParticles();
Quentin Khan's avatar
Quentin Khan committed
295 296 297 298

        if ( TargetParticles != SourceParticles ) {
            tmpCost +=  countFlopsP2P() * tgtPartCount * srcPartCount;

299
            for ( int idx = 0; idx < size; ++idx ) {
Quentin Khan's avatar
Quentin Khan committed
300 301 302
                    tmpCost += 
                        countFlopsP2P() 
                        * tgtPartCount
303
                        * NeighborSourceParticles[idx]->getNbParticles();
Quentin Khan's avatar
Quentin Khan committed
304 305 306 307 308 309 310
            }
        } else {
            tmpCost +=
                countFlopsP2Pmutual()
                * ((tgtPartCount * tgtPartCount
                    + tgtPartCount)
                   / 2);
311
            for (int idx=0; idx < size && positions[idx]<=13; ++idx)
Quentin Khan's avatar
Quentin Khan committed
312 313 314 315 316 317 318 319 320 321 322
            {
                    tmpCost += 
                        countFlopsP2Pmutual()
                        * tgtPartCount
                        * NeighborSourceParticles[idx]->getNbParticles();                    
                }
        }

        flopsP2P += tmpCost;

        CellClass* cell = _tree->getCell(
323
            LeafCellCoordinate.getMortonIndex(),
Quentin Khan's avatar
Quentin Khan committed
324 325
            _treeHeight - 1);

326
        cell->addNearCost(tmpCost);
Quentin Khan's avatar
Quentin Khan committed
327 328
        countP2P++;
    }
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

    void P2POuter(const FTreeCoordinate& LeafCellCoordinate, // needed for periodic boundary conditions
             ContainerClass* const FRestrict TargetParticles,
             ContainerClass* const NeighborSourceParticles[],
             const int positions[],
             const int size) override {
        FSize tmpCost = 0;
        FSize tgtPartCount = TargetParticles->getNbParticles();

        {
            for (int idx=0; idx < size && positions[idx]<=13; ++idx)
            {
                    tmpCost +=
                        countFlopsP2Pmutual()
                        * tgtPartCount
                        * NeighborSourceParticles[idx]->getNbParticles();
                }
        }

        flopsP2P += tmpCost;

        CellClass* cell = _tree->getCell(
351
            LeafCellCoordinate.getMortonIndex(),
352 353 354 355 356
            _treeHeight - 1);

        cell->addNearCost(tmpCost);
        countP2P++;
    }
Quentin Khan's avatar
Quentin Khan committed
357 358 359 360 361 362 363 364
};



/**
 * Handler to deal with all symmetries: Stores permutation indices and vectors
 * to reduce 343 different interactions to 16 only.
 */
365 366
template < typename FReal, class CellClass, class ContainerClass,
           class MatrixKernelClass, int ORDER, class OctreeClass>
367
struct FChebSymCostKernel<FReal, CellClass, ContainerClass, MatrixKernelClass, ORDER, OctreeClass>
Quentin Khan's avatar
Quentin Khan committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
::SymmetryHandler
{
    // M2L operators
    FReal*    K[343];
    int LowRank[343];
        
    // permutation vectors and permutated indices
    unsigned int pvectors[343][nnodes];
    unsigned int pindices[343];


    // compute rank
    unsigned int getRank(const FReal singular_values[], const double eps)
        {
            FReal nrm2(0.);
            for (unsigned int k=0; k<nnodes; ++k)
                nrm2 += singular_values[k] * singular_values[k];
        
            FReal nrm2k(0.);
            for (unsigned int k=nnodes; k>0; --k) {
                nrm2k += singular_values[k-1] * singular_values[k-1];
                if (nrm2k > eps*eps * nrm2)    return k;
            }
            throw std::runtime_error("rank cannot be larger than nnodes");
            return 0;
        }
    

    /** Constructor */
    SymmetryHandler(const MatrixKernelClass *const MatrixKernel, const double Epsilon)
        {
            // init all 343 item to zero, because effectively only 16 exist
            for (unsigned int t=0; t<343; ++t) {
                K[t] = nullptr;
                LowRank[t] = 0;
            }
            
            // set permutation vector and indices
            const FInterpSymmetries<ORDER> Symmetries;
            for (int i=-3; i<=3; ++i)
                for (int j=-3; j<=3; ++j)
                    for (int k=-3; k<=3; ++k)
                        if (abs(i)>1 || abs(j)>1 || abs(k)>1) {
                            const unsigned int idx = ((i+3) * 7 + (j+3)) * 7 + (k+3);
                            pindices[idx] = Symmetries.getPermutationArrayAndIndex(i,j,k, pvectors[idx]);
                        }

            // precompute 16 M2L operators
            this->precomputeSVD(MatrixKernel, Epsilon);
        }



    /** Destructor */
    ~SymmetryHandler()
        {
            for (unsigned int t=0; t<343; ++t)
                if (K[  t]!=nullptr) delete [] K[  t];
        }



private:
    void precomputeSVD(const MatrixKernelClass *const MatrixKernel, const double Epsilon)
        {
            // interpolation points of source (Y) and target (X) cell
Quentin Khan's avatar
Quentin Khan committed
434
            FPoint<FReal> X[nnodes], Y[nnodes];
Quentin Khan's avatar
Quentin Khan committed
435
            // set roots of target cell (X)
Quentin Khan's avatar
Quentin Khan committed
436
            FChebTensor<FReal, ORDER>::setRoots(FPoint<FReal>(0.,0.,0.), FReal(2.), X);
Quentin Khan's avatar
Quentin Khan committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
            // temporary matrix
            FReal* U = new FReal [nnodes*nnodes];

            // needed for the SVD
            const unsigned int LWORK = 2 * (3*nnodes + nnodes);
            FReal *const WORK = new FReal [LWORK];
            FReal *const VT = new FReal [nnodes*nnodes];
            FReal *const S = new FReal [nnodes];
        
            unsigned int counter = 0;
            for (int i=2; i<=3; ++i) {
                for (int j=0; j<=i; ++j) {
                    for (int k=0; k<=j; ++k) {

                        // assemble matrix
Quentin Khan's avatar
Quentin Khan committed
452 453
                        const FPoint<FReal> cy(FReal(2.*i), FReal(2.*j), FReal(2.*k));
                        FChebTensor<FReal, ORDER>::setRoots(cy, FReal(2.), Y);
Quentin Khan's avatar
Quentin Khan committed
454 455 456 457 458 459
                        for (unsigned int n=0; n<nnodes; ++n)
                            for (unsigned int m=0; m<nnodes; ++m)
                                U[n*nnodes + m] = MatrixKernel->evaluate(X[m], Y[n]);

                        // applying weights ////////////////////////////////////////
                        FReal weights[nnodes];
Quentin Khan's avatar
Quentin Khan committed
460
                        FChebTensor<FReal,ORDER>::setRootOfWeights(weights);
Quentin Khan's avatar
Quentin Khan committed
461 462 463 464 465 466 467 468
                        for (unsigned int n=0; n<nnodes; ++n) {
                            FBlas::scal(nnodes, weights[n], U + n,  nnodes); // scale rows
                            FBlas::scal(nnodes, weights[n], U + n * nnodes); // scale cols
                        }
                        //////////////////////////////////////////////////////////        

                        // truncated singular value decomposition of matrix
                        const unsigned int info    = FBlas::gesvd(nnodes, nnodes, U, S, VT, nnodes, LWORK, WORK);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
469
                        if (info!=0) throw std::runtime_error("SVD did not converge with " + std::to_string(info));
Quentin Khan's avatar
Quentin Khan committed
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
                        const unsigned int rank = this->getRank(S, Epsilon);

                        // store 
                        const unsigned int idx = (i+3)*7*7 + (j+3)*7 + (k+3);
                        assert(K[idx]==nullptr);
                        K[idx] = new FReal [2*rank*nnodes];
                        LowRank[idx] = rank;
                        for (unsigned int r=0; r<rank; ++r)
                            FBlas::scal(nnodes, S[r], U + r*nnodes);
                        FBlas::copy(rank*nnodes, U,  K[idx]);
                        for (unsigned int r=0; r<rank; ++r)
                            FBlas::copy(nnodes, VT + r, nnodes, K[idx] + rank*nnodes + r*nnodes, 1);

                        // un-weighting ////////////////////////////////////////////
                        for (unsigned int n=0; n<nnodes; ++n) {
                            // scale rows
                            FBlas::scal(rank, FReal(1.) / weights[n], K[idx] + n,               nnodes);
                            // scale rows
                            FBlas::scal(rank, FReal(1.) / weights[n], K[idx] + rank*nnodes + n, nnodes);
                        }
                        //////////////////////////////////////////////////////////        

                        //std::cout << "(" << i << "," << j << "," << k << ") " << idx <<
                        //    ", low rank = " << rank << std::endl;

                        counter++;
                    }
                }
            }
            std::cout << "num interactions = " << counter << std::endl;
            delete [] U;
            delete [] WORK;
            delete [] VT;
            delete [] S;
        }

};


#endif 

// [--END--]