MPIInterpolationFMM.hpp 13.8 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
// 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 "Components/FSimpleLeaf.hpp"
#include "Kernels/P2P/FP2PParticleContainerIndexed.hpp"

#include "Utils/FParameters.hpp"
#include "Utils/FParameterNames.hpp"
//
// Order of the Interpolation approximation
COULAUD Olivier's avatar
COULAUD Olivier committed
35
static constexpr unsigned ORDER = 7 ;
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
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 //////////////////////////////////////
70
  const FParameterNames  localIncreaseBox = { {"ratio","-L"}, "Increase teh Box size by a factor L:= ratio"};
71
  FHelpDescribeAndExit(argc, argv,
COULAUD Olivier's avatar
COULAUD Olivier committed
72
                       "Driver for Chebyshev Interpolation kernel using MPI  (1/r kernel).\n "
73 74 75 76 77 78
                       "Usully run using : mpirun -np nb_proc_needed ./ChebyshevInterpolationAlgorithm [params].",
                       FParameterDefinitions::OctreeHeight,
                       FParameterDefinitions::OctreeSubHeight,
                       FParameterDefinitions::InputFile,
                       FParameterDefinitions::OutputFile,
                       FParameterDefinitions::NbThreads,
79
                       FParameterDefinitions::PeriodicityNbLevels,
80
                       localIncreaseBox
COULAUD Olivier's avatar
COULAUD Olivier committed
81
                       ) ;
82

COULAUD Olivier's avatar
COULAUD Olivier committed
83 84 85 86
  // Initialize values for MPI
  FMpi app(argc,argv);
  const bool masterIO = ( app.global().processId() == 0 );
  //
87 88 89 90 91 92 93 94 95 96 97 98
  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);
COULAUD Olivier's avatar
COULAUD Olivier committed
99 100 101 102 103 104 105 106
  if(masterIO){
    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){
107
      std::cout << "      AboveTree    "<< aboveTree <<std::endl;
COULAUD Olivier's avatar
COULAUD Olivier committed
108
      
109
    }
COULAUD Olivier's avatar
COULAUD Olivier committed
110 111 112 113
    std::cout    << "      Input file  name: " << filename      << std::endl
		 << "      Thread count :    " << NbThreads     << std::endl
		 << std::endl;
  }
114 115 116

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

COULAUD Olivier's avatar
COULAUD Olivier committed
117

118 119 120 121 122 123 124 125
  // 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!") ;
    }
126 127 128
  auto boxWidth = loader.getBoxWidth() ;
  //
  if(FParameters::existParameter(argc, argv, localIncreaseBox.options)){
129 130 131 132
      FReal ratio=  FParameters::getValue(argc, argv, localIncreaseBox.options, 1.0);
      boxWidth *= ratio;
    }

133
  // Initialize empty oct-tree
134
  OctreeClass tree(TreeHeight, SubTreeHeight, boxWidth, loader.getCenterOfBox());
135 136 137

  FSize localParticlesNumber = 0 ;

COULAUD Olivier's avatar
COULAUD Olivier committed
138
  // -----------------------------------------------------
COULAUD Olivier's avatar
COULAUD Olivier committed
139
  if(masterIO){
140 141 142 143 144 145 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
      std::cout << "Loading & Inserting " << loader.getNumberOfParticles()
                << " particles ..." << std::endl
                <<" Box: "<< std::endl
               << "    width  " << boxWidth << std::endl
               << "    Centre " << loader.getCenterOfBox()<< std::endl;
      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);
    }
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
  // 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);
    }
201

202
  time.tac();
203

204
  localParticlesNumber = finalParticles.getSize() ;
205

206 207 208 209 210 211 212
  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;
213

214 215
  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());
COULAUD Olivier's avatar
COULAUD Olivier committed
216
  if(masterIO){
217 218 219 220
      std::cout << "readinsert-time-min:" << minTime
                << " readinsert-time-max:" << maxTime
                << std::endl;
    }
COULAUD Olivier's avatar
COULAUD Olivier committed
221
  
222 223
  // -----------------------------------------------------
  FAbstractAlgorithm * algorithm  = nullptr;
224
  FAlgorithmTimers   * timer      = nullptr;
COULAUD Olivier's avatar
COULAUD Olivier committed
225
   // -----------------------------------------------------
COULAUD Olivier's avatar
COULAUD Olivier committed
226 227 228
    if(masterIO) {
        std::cout << "\n"<<interpolationType<<" FMM Proc (ORDER="<< ORDER << ") ... " << std::endl;
    }
229 230 231 232

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

    // non periodic FMM algorithm
233
    std::unique_ptr<KernelClass> kernelsNoPer(new KernelClass(TreeHeight, boxWidth,
COULAUD Olivier's avatar
COULAUD Olivier committed
234 235
                                                              loader.getCenterOfBox(),
							      &MatrixKernel));
236 237 238 239
    FmmClassProc    algoNoPer(app.global(),&tree, kernelsNoPer.get());
    //
    // periodic FMM algorithm
    FmmClassProcPER algoPer(app.global(),&tree, aboveTree);
COULAUD Olivier's avatar
COULAUD Olivier committed
240

241 242
    KernelClass kernelsPer(algoPer.extendedTreeHeight(), algoPer.extendedBoxWidth(),
                           algoPer.extendedBoxCenter(),&MatrixKernel);
COULAUD Olivier's avatar
COULAUD Olivier committed
243

244 245 246 247
    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
    // FMM exectution  FFmmFarField FFmmNearField  FFmmP2M|FFmmM2M|FFmmM2L|FFmmL2L
COULAUD Olivier's avatar
COULAUD Olivier committed
256
    time.tic();
257
    algorithm->execute();
COULAUD Olivier's avatar
COULAUD Olivier committed
258
    time.tac();
259 260
    //

COULAUD Olivier's avatar
COULAUD Olivier committed
261 262 263 264 265
   // if(masterIO)
   //  {
   //    std::cout << app.global().processId()  <<"  Morton distribution "<< std::endl ;
   //    for(auto v : mortonLeafDistribution)
   //      std::cout << v << " ";
266

COULAUD Olivier's avatar
COULAUD Olivier committed
267 268 269
   //    std::cout <<  std::endl;
   //  }
    //    app.global().barrier();
COULAUD Olivier's avatar
COULAUD Olivier committed
270
    timeUsed = time.elapsed();
271 272
    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());
COULAUD Olivier's avatar
COULAUD Olivier committed
273 274
    if(masterIO){
        std::cout << "Done  " << "(@Algorithm = " << time.elapsed() << " s)." << std::endl;
275 276 277
        std::cout << "exec-time-min:" << minTime
                  << " exec-time-max:" << maxTime
                  << std::endl;
278 279 280 281 282 283 284 285
    std::cout << "Timers Far Field \n"
              << "P2M " << timer->getTime(FAlgorithmTimers::P2MTimer) << " seconds\n"
              << "M2M " << timer->getTime(FAlgorithmTimers::M2MTimer) << " seconds\n"
              << "M2L " << timer->getTime(FAlgorithmTimers::M2LTimer) << " seconds\n"
              << "L2L " << timer->getTime(FAlgorithmTimers::L2LTimer) << " seconds\n"
              << "P2P and L2P " << timer->getTime(FAlgorithmTimers::NearTimer) << " seconds\n"
	      << std::endl;

286
      }
COULAUD Olivier's avatar
COULAUD Olivier committed
287
  
288

289
  // -----------------------------------------------------
290
  //
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  // 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;
    std::cout.precision(15) ;

    FReal locTotalPhysicalValue=0.0 ;

    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){
COULAUD Olivier's avatar
COULAUD Olivier committed
321 322 323 324 325 326 327 328 329 330 331
	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;
	  }
	energy += potentials[idxPart]*physicalValues[idxPart] ;
	locTotalPhysicalValue += physicalValues[idxPart]  ;
      }
      });
332 333
    FReal gloEnergy          = app.global().reduceSum(energy);
    FReal TotalPhysicalValue = app.global().reduceSum(locTotalPhysicalValue);
COULAUD Olivier's avatar
COULAUD Olivier committed
334
    if(masterIO){
COULAUD Olivier's avatar
COULAUD Olivier committed
335 336 337
      std::cout <<std::endl<<"aboveRoot: " << aboveTree << " Energy: "<< gloEnergy <<"  TotalPhysicalValue: " << TotalPhysicalValue<< std::endl; 
      std::cout <<std::endl <<" &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& "<<std::endl<<std::endl;
    }
338
  }
339 340 341



342 343
  // -----------------------------------------------------
  if(FParameters::existParameter(argc, argv, FParameterDefinitions::OutputFile.options)){
COULAUD Olivier's avatar
COULAUD Olivier committed
344 345 346 347 348 349
    std::vector<MortonIndex> mortonLeafDistribution(2*app.global().processCount());
    algorithm->getMortonLeafDistribution(mortonLeafDistribution);
    std::string name(FParameters::getStr(argc,argv,FParameterDefinitions::OutputFile.options, "output.fma"));
    FMpiFmaGenericWriter<FReal> paraWriter(name,app);
    paraWriter.writeDistributionOfParticlesFromOctree(tree,loader.getNumberOfParticles(),localParticlesNumber,
						      mortonLeafDistribution);
350

COULAUD Olivier's avatar
COULAUD Olivier committed
351
  }
352
  return 0;
353
}