MPIInterpolationFMM.hpp 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
// See LICENCE file at project root

// ==== CMAKE =====
// @FUSE_MPI
// @FUSE_BLAS
// ================

#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>


#include "ScalFmmConfig.h"
#include "Containers/FOctree.hpp"
#include "Utils/FMpi.hpp"
#include "Core/FFmmAlgorithmThreadProc.hpp"
#include "Core/FFmmAlgorithmThreadProcPeriodic.hpp"

#include "Files/FFmaGenericLoader.hpp"
#include "Files/FMpiFmaGenericLoader.hpp"
#include "Files/FMpiTreeBuilder.hpp"

#include "Utils/FLeafBalance.hpp"

#include "Kernels/Interpolation/FInterpMatrixKernel.hpp"
#include "Kernels/Chebyshev/FChebSymKernel.hpp"
#include "Kernels/Chebyshev/FChebCell.hpp"

#include "Components/FSimpleLeaf.hpp"
#include "Kernels/P2P/FP2PParticleContainerIndexed.hpp"

#include "Utils/FParameters.hpp"
#include "Utils/FParameterNames.hpp"

//
// Order of the Interpolation approximation
static constexpr unsigned ORDER = 6 ;
using FReal                 = double;
//   1/r kernel
//
using MatrixKernelClass     = FInterpMatrixKernelR<FReal> ;
//
// Typedefs
using ContainerClass = FP2PParticleContainerIndexed<FReal>;
using LeafClass      = FSimpleLeaf<FReal, ContainerClass>;

using CellClass      = FInterpolationCell<FReal, ORDER>;


using OctreeClass    = FOctree<FReal,CellClass,ContainerClass,LeafClass>;

using MatrixKernelClass = FInterpMatrixKernelR<FReal>;
const MatrixKernelClass MatrixKernel;

using KernelClass    = FInterpolationKernel<FReal,CellClass,ContainerClass,MatrixKernelClass,ORDER> ;

using FmmClassProc     = FFmmAlgorithmThreadProc<OctreeClass,CellClass,ContainerClass,KernelClass,LeafClass>;
using FmmClassProcPER  = FFmmAlgorithmThreadProcPeriodic<FReal,OctreeClass,CellClass,ContainerClass,KernelClass,LeafClass>;

/// \file
//!
//! \brief This program runs the MPI FMM with Chebyshev/Lagrange interpolation of 1/r kernel
//!  \authors B. Bramas, O. Coulaud
//!
//!  This code is a short example to use the FMM Algorithm Proc with Chebyshev or equispaced grid points Interpolation for the 1/r kernel


// Simply create particles and try the kernels
int main(int argc, char* argv[])
{
  ///////// PARAMETERS HANDLING //////////////////////////////////////
COULAUD Olivier's avatar
COULAUD Olivier committed
73
  const FParameterNames  localIncreaseBox = { {"ratio","-L"}, "Increase teh Box size by a factor L:= ratio"};
74 75 76 77 78 79 80 81
  FHelpDescribeAndExit(argc, argv,
                       "Driver for Chebyshev Interpolation kernel using MPI  (1/r kernel). "
                       "Usully run using : mpirun -np nb_proc_needed ./ChebyshevInterpolationAlgorithm [params].",
                       FParameterDefinitions::OctreeHeight,
                       FParameterDefinitions::OctreeSubHeight,
                       FParameterDefinitions::InputFile,
                       FParameterDefinitions::OutputFile,
                       FParameterDefinitions::NbThreads,
COULAUD Olivier's avatar
COULAUD Olivier committed
82 83 84 85
                       FParameterDefinitions::PeriodicityNbLevels,
		       localIncreaseBox
		       )
;
86 87 88 89 90 91 92 93 94 95 96 97 98 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 124 125 126

  const std::string defaultFile("../Data/test20k.fma");
  const std::string  filename      = FParameters::getStr(argc,argv,    FParameterDefinitions::InputFile.options, defaultFile.c_str());
  const unsigned int TreeHeight    = FParameters::getValue(argc, argv, FParameterDefinitions::OctreeHeight.options, 5);
  const unsigned int SubTreeHeight = FParameters::getValue(argc, argv, FParameterDefinitions::OctreeSubHeight.options, 2);
  const unsigned int NbThreads     = FParameters::getValue(argc, argv, FParameterDefinitions::NbThreads.options, 1);
  bool periodicCondition = false ;
  if(FParameters::existParameter(argc, argv, FParameterDefinitions::PeriodicityNbLevels.options)){
      periodicCondition = true;
    }
  const unsigned int aboveTree = FParameters::getValue(argc, argv, FParameterDefinitions::PeriodicityNbLevels.options, 5);

  omp_set_num_threads(NbThreads);
  std::cout << "\n>> Using " << omp_get_max_threads() << " threads.\n" << std::endl;

  //
  std::cout << "Parameters"<< std::endl
            << "      Octree Depth      " << TreeHeight    << std::endl
            << "      SubOctree depth   " << SubTreeHeight << std::endl;
  if(periodicCondition){
      std::cout << "      AboveTree    "<< aboveTree <<std::endl;

    }
  std::cout    << "      Input file  name: " << filename      << std::endl
               << "      Thread count :    " << NbThreads     << std::endl
               << std::endl;


  ///////// VAR INIT /////////////////////////////////////////////////

  // Initialize values for MPI
  FMpi app(argc,argv);
  //
  // Initialize timer
  FTic time;

  // Creation of the particle loader
  FMpiFmaGenericLoader<FReal> loader(filename,app.global());
  if(!loader.isOpen()) {
      throw std::runtime_error("Particle file couldn't be opened!") ;
    }
COULAUD Olivier's avatar
COULAUD Olivier committed
127 128 129 130 131 132 133
  auto boxWidth = loader.getBoxWidth() ;
  //
  if(FParameters::existParameter(argc, argv, localIncreaseBox.options)){
    FReal ratio=  FParameters::getValue(argc, argv, localIncreaseBox.options, 1.0);
    boxWidth *= ratio;
  }
 
134
  // Initialize empty oct-tree
COULAUD Olivier's avatar
COULAUD Olivier committed
135
  OctreeClass tree(TreeHeight, SubTreeHeight, boxWidth, loader.getCenterOfBox());
136 137 138 139 140 141

  FSize localParticlesNumber = 0 ;

  { // -----------------------------------------------------
    if(app.global().processId() == 0){
        std::cout << "Loading & Inserting " << loader.getNumberOfParticles()
COULAUD Olivier's avatar
COULAUD Olivier committed
142 143 144 145
                  << " particles ..." << std::endl
		  <<" Box: "<< std::endl
		  << "    width  " << boxWidth << std::endl
		  << "    Centre " << loader.getCenterOfBox()<< std::endl;
146 147 148 149 150 151 152 153 154 155 156 157 158 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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        std::cout << "\tHeight : " << TreeHeight << " \t sub-height : " << SubTreeHeight << std::endl;
      }
    time.tic();

    /* Mock particle structure to balance the tree over the processes. */
    struct TestParticle{
      FSize index;             // Index of the particle in the original file.
      FPoint<FReal> position;  // Spatial position of the particle.
      FReal physicalValue;     // Physical value of the particle.
      /* Returns the particle position. */
      const FPoint<FReal>& getPosition(){
        return position;
      }
    };

    // Temporary array of particles read by this process.
    TestParticle* particles = new TestParticle[loader.getMyNumberOfParticles()];
    memset(particles, 0, (sizeof(TestParticle) * loader.getMyNumberOfParticles()));

    // Index (in file) of the first particle that will be read by this process.
    FSize idxStart = loader.getStart();
    std::cout << "Proc:" << app.global().processId() << " start-index: " << idxStart << std::endl;

    // Read particles from parts.
    for(FSize idxPart = 0 ; idxPart < loader.getMyNumberOfParticles() ; ++idxPart){
        // Store the index (in the original file) the particle.
        particles[idxPart].index = idxPart + idxStart;
        // Read particle from file
        loader.fillParticle(&particles[idxPart].position,
                            &particles[idxPart].physicalValue);
      }

    // Final vector of particles
    FVector<TestParticle> finalParticles;
    FLeafBalance balancer;
    // Redistribute particules between processes
    FMpiTreeBuilder< FReal, TestParticle >::
        DistributeArrayToContainer(app.global(),
                                   particles,
                                   loader.getMyNumberOfParticles(),
                                   tree.getBoxCenter(),
                                   tree.getBoxWidth(),
                                   tree.getHeight(),
                                   &finalParticles,
                                   &balancer);

    // Free temporary array memory.
    delete[] particles;

    // Insert final particles into tree.

    for(FSize idx = 0 ; idx < finalParticles.getSize(); ++idx){
        tree.insert(finalParticles[idx].position,
                    finalParticles[idx].index,
                    finalParticles[idx].physicalValue);
      }

    time.tac();

    localParticlesNumber = finalParticles.getSize() ;

    double timeUsed = time.elapsed();
    double minTime,maxTime;
    std::cout << "Proc:" << app.global().processId()
              << " "     << finalParticles.getSize()
              << " particles have been inserted in the tree. (@Reading and Inserting Particles = "
              << time.elapsed() << " s)."
              << std::endl;

    MPI_Reduce(&timeUsed,&minTime,1,MPI_DOUBLE,MPI_MIN,0,app.global().getComm());
    MPI_Reduce(&timeUsed,&maxTime,1,MPI_DOUBLE,MPI_MAX,0,app.global().getComm());
    if(app.global().processId() == 0){
        std::cout << "readinsert-time-min:" << minTime
                  << " readinsert-time-max:" << maxTime
                  << std::endl;
      }
COULAUD Olivier's avatar
COULAUD Olivier committed
222 223
  }
  // -----------------------------------------------------
224
  std::vector<MortonIndex> mortonLeafDistribution(2*app.global().processCount());
COULAUD Olivier's avatar
COULAUD Olivier committed
225
  FAbstractAlgorithm * algorithm  = nullptr;
226
  //FAlgorithmTimers   * timer      = nullptr;
227 228 229 230 231 232 233
  { // -----------------------------------------------------
    std::cout << "\n"<<interpolationType<<" FMM Proc (ORDER="<< ORDER << ") ... " << std::endl;

    time.tic();

    // Kernels to use (pointer because of the limited size of the stack)

COULAUD Olivier's avatar
COULAUD Olivier committed
234

235
    // non periodic FMM algorithm
COULAUD Olivier's avatar
COULAUD Olivier committed
236
    std::unique_ptr<KernelClass> kernelsNoPer(new KernelClass(TreeHeight, boxWidth,
237 238 239 240 241 242 243 244 245 246 247
                                                              loader.getCenterOfBox(),&MatrixKernel));
    FmmClassProc    algoNoPer(app.global(),&tree, kernelsNoPer.get());
    //
    // periodic FMM algorithm
    FmmClassProcPER algoPer(app.global(),&tree, aboveTree);
    KernelClass kernelsPer(algoPer.extendedTreeHeight(), algoPer.extendedBoxWidth(),
                           algoPer.extendedBoxCenter(),&MatrixKernel);
    algoPer.setKernel(&kernelsPer);
    ///////////////////////////////////////////////////////////////////////////////////////////////////
    if(! periodicCondition) {// Non periodic case
        algorithm  = &algoNoPer ;
248
        //timer      = &algoNoPer ;
249 250 251
      }
    else {  // Periodic case
        algorithm  = &algoPer ;
252
        //timer      = &algoPer ;
253 254
      }
    //
COULAUD Olivier's avatar
COULAUD Olivier committed
255 256
    // FMM exectution  FFmmFarField FFmmNearField
    algorithm->execute(FFmmNearField);
257 258 259 260 261 262 263 264 265 266 267 268 269 270
    //

    time.tac();
    double timeUsed = time.elapsed();
    double minTime,maxTime;
    std::cout << "Done  " << "(@Algorithm = " << time.elapsed() << " s)." << std::endl;
    MPI_Reduce(&timeUsed,&minTime,1,MPI_DOUBLE,MPI_MIN,0,app.global().getComm());
    MPI_Reduce(&timeUsed,&maxTime,1,MPI_DOUBLE,MPI_MAX,0,app.global().getComm());
    if(app.global().processId() == 0){
        std::cout << "exec-time-min:" << minTime
                  << " exec-time-max:" << maxTime
                  << std::endl;
      }
  }
COULAUD Olivier's avatar
COULAUD Olivier committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284

// -----------------------------------------------------
//
// Some output
//
//
{ // -----------------------------------------------------
FSize N1=0, N2= loader.getNumberOfParticles()/2, N3= (loader.getNumberOfParticles()-1); ;
FReal energy =0.0 ;
//
//   Loop over all leaves
//
std::cout <<std::endl<<" &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& "<<std::endl;
std::cout << std::scientific;
COULAUD Olivier's avatar
COULAUD Olivier committed
285 286 287
std::cout.precision(15) ;
 
 FReal TotalPhysicalValue=0.0 ;
COULAUD Olivier's avatar
COULAUD Olivier committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

tree.forEachLeaf([&](LeafClass* leaf){
  const FReal*const posX = leaf->getTargets()->getPositions()[0];
  const FReal*const posY = leaf->getTargets()->getPositions()[1];
  const FReal*const posZ = leaf->getTargets()->getPositions()[2];

  const FReal*const potentials = leaf->getTargets()->getPotentials();
  const FReal*const forcesX = leaf->getTargets()->getForcesX();
  const FReal*const forcesY = leaf->getTargets()->getForcesY();
  const FReal*const forcesZ = leaf->getTargets()->getForcesZ();
  const FSize nbParticlesInLeaf = leaf->getTargets()->getNbParticles();
  const FReal*const physicalValues = leaf->getTargets()->getPhysicalValues();

  const FVector<FSize>& indexes = leaf->getTargets()->getIndexes();

  for(FSize idxPart = 0 ; idxPart < nbParticlesInLeaf ; ++idxPart){
      const FSize indexPartOrig = indexes[idxPart];
      if ((indexPartOrig == N1) || (indexPartOrig == N2) || (indexPartOrig == N3)  ) {
          std::cout << "Proc "<< app.global().processId() << " Index "<< indexPartOrig <<"  potential  " << potentials[idxPart]
                       << " Pos "<<posX[idxPart]<<" "<<posY[idxPart]<<" "<<posZ[idxPart]
                          << "   Forces: " << forcesX[idxPart] << " " << forcesY[idxPart] << " "<< forcesZ[idxPart] <<std::endl;
309
        }
COULAUD Olivier's avatar
COULAUD Olivier committed
310
      energy += potentials[idxPart]*physicalValues[idxPart] ;
COULAUD Olivier's avatar
COULAUD Olivier committed
311
      TotalPhysicalValue += physicalValues[idxPart]  ;
COULAUD Olivier's avatar
COULAUD Olivier committed
312 313 314 315
    }
});
FReal gloEnergy = app.global().reduceSum(energy);
if(0 == app.global().processId()){
COULAUD Olivier's avatar
COULAUD Olivier committed
316
     std::cout <<std::endl<<"aboveRoot: " << aboveTree << "  Energy: "<< energy<<"  TotalPhysicalValue: " << TotalPhysicalValue<< std::endl; std::cout <<std::endl << "Proc "<< app.global().processId() << " Energy: "<< gloEnergy <<std::endl;
COULAUD Olivier's avatar
COULAUD Olivier committed
317 318 319 320 321 322 323 324 325 326 327 328
  std::cout <<std::endl <<" &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& "<<std::endl<<std::endl;
}
}
// -----------------------------------------------------
if(FParameters::existParameter(argc, argv, FParameterDefinitions::OutputFile.options)){
  algorithm->getAndBuildMortonIndexAtLeaf(mortonLeafDistribution);
  //
  if(app.global().processId() == 0)
    {
      std::cout << " Morton distribution "<< std::endl ;
      for(auto v : mortonLeafDistribution)
        std::cout << v << " ";
329

COULAUD Olivier's avatar
COULAUD Olivier committed
330
      std::cout <<  std::endl;
331
    }
COULAUD Olivier's avatar
COULAUD Olivier committed
332 333 334 335 336 337
  std::string name(FParameters::getStr(argc,argv,FParameterDefinitions::OutputFile.options, "output.fma"));
  FMpiFmaGenericWriter<FReal> paraWriter(name,app);
  paraWriter.writeDistributionOfParticlesFromOctree(tree,loader.getNumberOfParticles(),localParticlesNumber,mortonLeafDistribution);

}
return 0;
338
}