Пример #1
0
std::vector<vgsdkTestGtk::vgTest::Performance> getPerformance(const std::vector<int> level, 
										const std::vector<vgd::node::VertexShape::DeformableHintValueType> deformableHint, 
										const std::vector<vgd::node::VertexShape::BoundingBoxUpdatePolicyValueType> boundingBoxPolicy)
{
	std::vector<vgsdkTestGtk::vgTest::Performance> p;

	for( uint i = 0; i < level.size(); i++)
	{
		for( uint j = 0; j< deformableHint.size(); j++)
		{
			for( uint k = 0; k < boundingBoxPolicy.size(); k++)
			{
				p.push_back(Performance(level[i], deformableHint[j], boundingBoxPolicy[k]));
			}
		}
	}
	
	return p;
}
Пример #2
0
void
Crosstable::PrintPerformance (DString * dstr, playerDataT * pdata)
{
    if (!PrintRatings) { return; }
    if (!pdata->oppEloCount) { return; }

    int oppAvgRating = pdata->oppEloTotal / pdata->oppEloCount;
    int percentage = pdata->oppEloScore * 50 + pdata->oppEloCount/2;
    percentage = percentage / pdata->oppEloCount;
    int performance = Performance(oppAvgRating, percentage);
    if (performance > 0  &&  performance < 5000) {
        char stemp [20];
        if (pdata->elo) {
            int change = RatingChange (pdata->elo, oppAvgRating, 
                                       percentage, pdata->oppEloCount);
            sprintf (stemp, "%4d %+3d", performance, change);
        } else {
            sprintf (stemp, "%4d    ", performance);
        }
        dstr->Append ("   ", StartRightCol, stemp, EndRightCol);
    }
}
//--------------------------------------------------------------------------
int main(int argc, char **argv) {

  // Temporary variables
  long int i, j, k, ii, idx = 1;
  double ElapsedTime;

  // Arguments
  int NumThreads = atoi(argv[idx++]);
  char *FileTrain = argv[idx++];
  char *FileTest = argv[idx++];
  int NumClasses = atoi(argv[idx++]);
  int d = atoi(argv[idx++]);
  int r = atoi(argv[idx++]);
  int Num_lambda = atoi(argv[idx++]);
  double *List_lambda = (double *)malloc(Num_lambda*sizeof(double));
  for (ii = 0; ii < Num_lambda; ii++) {
    List_lambda[ii] = atof(argv[idx++]);
  }
  int Num_sigma = atoi(argv[idx++]);
  double *List_sigma = (double *)malloc(Num_sigma*sizeof(double));
  for (i = 0; i < Num_sigma; i++) {
    List_sigma[i] = atof(argv[idx++]);
  }
  int MAXIT = atoi(argv[idx++]);
  double TOL = atof(argv[idx++]);
  bool verbose = atoi(argv[idx++]);

  // Threading
#ifdef USE_OPENBLAS
  openblas_set_num_threads(NumThreads);
#elif USE_ESSL

#elif USE_OPENMP
  omp_set_num_threads(NumThreads);
#else
  NumThreads = 1; // To avoid compiler warining of unused variable
#endif

  PREPARE_CLOCK(1);
  START_CLOCK;

  // Read in X = Xtrain (n*d), y = ytrain (n*1),
  //     and X0 = Xtest (m*d), y0 = ytest (m*1)
  DPointArray Xtrain;        // read all data points from train
  DPointArray Xtest;        // read all data points from test
  DVector ytrain;           // Training labels
  DVector ytest;            // Testing labels (ground truth)
  DVector ytest_predict;    // Predictions

  if (ReadData(FileTrain, Xtrain, ytrain, d) == 0) {
    return -1;
  }
  if (ReadData(FileTest, Xtest, ytest, d) == 0) {
    return -1;
  }

  END_CLOCK;
  ElapsedTime = ELAPSED_TIME;
  printf("OneVsAll: time loading data = %g seconds\n", ElapsedTime); fflush(stdout);

  // For multiclass classification, need to convert a single vector
  // ytrain to a matrix Ytrain. The "predictions" are stored in the
  // corresponding matrix Ytest_predict. The vector ytest_predict is
  DMatrix Ytrain;
  ConvertYtrain(ytrain, Ytrain, NumClasses);

  int Seed = 0; // initialize seed as zero
  // Loop over List_lambda
  for (ii = 0; ii < Num_lambda; ii++) {
    double lambda = List_lambda[ii];
    // Loop over List_sigma
    for (k = 0; k < Num_sigma; k++) {
    double sigma = List_sigma[k];
    // Seed the RNG
    srandom(Seed);

    START_CLOCK;
    // Generate feature matrix Xdata_randbin given Xdata
    vector< vector< pair<int,double> > > instances_old, instances_new;
    long Xtrain_N = Xtrain.GetN();
    for(i=0;i<Xtrain_N;i++){
      instances_old.push_back(vector<pair<int,double> >());
      for(j=0;j<d;j++){
        int index = j+1;
        double *myXtrain = Xtrain.GetPointer();
        double  myXtrain_feature = myXtrain[j*Xtrain_N+i];
        if (myXtrain_feature != 0)
          instances_old.back().push_back(pair<int,double>(index, myXtrain_feature));
      }
    }
    long Xtest_N = Xtest.GetN();
    for(i=0;i<Xtest_N;i++){
      instances_old.push_back(vector<pair<int,double> >());
      for(j=0;j<d;j++){
        int index = j+1;
        double *myXtest = Xtest.GetPointer();
        double  myXtest_feature = myXtest[j*Xtest_N+i];
        if (myXtest_feature != 0)
          instances_old.back().push_back(pair<int,double>(index, myXtest_feature));
      }
    }
    END_CLOCK;
    printf("Train. RandBin: Time (in seconds) for converting data format: %g\n", ELAPSED_TIME);fflush(stdout);
     
     // add 0 feature for Enxu's code
    START_CLOCK;
    random_binning_feature(d+1, r, instances_old, instances_new, sigma);
    END_CLOCK;
    printf("Train. RandBin: Time (in seconds) for generating random binning features: %g\n", ELAPSED_TIME);fflush(stdout);

    START_CLOCK;
    SPointArray Xdata_randbin;  // Generate random binning features
    long int nnz = r*(Xtrain_N + Xtest_N);
    long int dd = 0;
    for(i = 0; i < instances_new.size(); i++){
      if(dd < instances_new[i][r-1].first)
        dd = instances_new[i][r-1].first;
    }
    Xdata_randbin.Init(Xtrain_N+Xtest_N, dd, nnz);
    long int ind = 0;
    long int *mystart = Xdata_randbin.GetPointerStart();
    int *myidx = Xdata_randbin.GetPointerIdx();
    double *myX = Xdata_randbin.GetPointerX();
    for(i = 0; i < instances_new.size(); i++){
      if (i == 0)
        mystart[i] = 0;
      else
        mystart[i] = mystart[i-1] + r;
      for(j = 0; j < instances_new[i].size(); j++){
        myidx[ind] = instances_new[i][j].first-1;
        myX[ind] = instances_new[i][j].second;
        ind++;
      }
    }
    mystart[i] = nnz; // mystart has a length N+1
    // generate random binning features for Xtrain and Xtest
    SPointArray Xtrain;         // Training points
    SPointArray Xtest;          // Testing points
    long Row_start = 0;
    Xdata_randbin.GetSubset(Row_start, Xtrain_N,Xtrain);
    Xdata_randbin.GetSubset(Xtrain_N,Xtest_N,Xtest);
    Xdata_randbin.ReleaseAllMemory();
    END_CLOCK;
    printf("Train. RandBin: Time (in seconds) for converting data format back: %g\n", ELAPSED_TIME);fflush(stdout);
    printf("OneVsAll: n train = %ld, m test = %ld, r = %d, D = %ld, Gamma = %f, num threads = %d\n", Xtrain_N, Xtest_N, r, dd, sigma, NumThreads); fflush(stdout);

    // solve (Z'Z + lambdaI)w = Z'y, note that we never explicitly form
    // Z'Z since Z is a large sparse matrix N*dd
    START_CLOCK;
    int m = Ytrain.GetN(); // number of classes
    long N = Xtrain.GetN(); // number of training points
    long NN = Xtest.GetN(); // number of training points
    long M = Xtrain.GetD(); // dimension of randome binning features
    DMatrix Ytest_predict(NN,m);
    DMatrix W(M,m);
    SPointArray EYE;
    EYE.Init(M,M,M);
    mystart = EYE.GetPointerStart();
    myidx = EYE.GetPointerIdx();
    myX = EYE.GetPointerX();
    for(i=0;i<M;i++){
      mystart[i] = i;
      myidx[i] = i;
      myX[i] = 1;
    }
    mystart[i] = M+1; // mystart has a length N+1
    for (i = 0; i < m; i++) {
      DVector w;
      w.Init(M);
      DVector ytrain, yy;
      Ytrain.GetColumn(i, ytrain);
      Xtrain.MatVec(ytrain, yy, TRANSPOSE);
      double NormRHS = yy.Norm2();
      PCG pcg_solver;
      pcg_solver.Solve<SPointArray, SPointArray>(Xtrain, yy, w, EYE, MAXIT, TOL, 1);
      if (verbose) {
        int Iter = 0;
        const double *ResHistory = pcg_solver.GetResHistory(Iter);
        printf("RLCM::Train, PCG. iteration = %d, Relative residual = %g\n",
          Iter, ResHistory[Iter-1]/NormRHS);fflush(stdout);
      }

      pcg_solver.GetSolution(w);
      W.SetColumn(i, w);
    }
    END_CLOCK;
    printf("Train. RandBin: Time (in seconds) for solving linear system solution: %g\n", ELAPSED_TIME);fflush(stdout);

    // y = Xtest*W = z(x)'*w
    START_CLOCK;
    Xtest.MatMat(W,Ytest_predict,NORMAL,NORMAL);
    double accuracy = Performance(ytest, Ytest_predict, NumClasses);
    END_CLOCK;
    ElapsedTime = ELAPSED_TIME;
    printf("Test. RandBin: param = %g %g, perf = %g, time = %g\n", sigma, lambda, accuracy, ElapsedTime); fflush(stdout);

  }// End loop over List_sigma
  }// End loop over List_lambda

  // Clean up
  free(List_sigma);
  free(List_lambda);

  return 0;
}
Пример #4
0
    void PoissonReconstruction::PoissonRecon(int argc , char* argv[], const MagicDGP::Point3DSet* pPC, std::vector< PlyValueVertex< float > >& vertices, std::vector< std::vector< int > >& polygons)
    {
        cmdLineString
            In( "in" ) ,
            Out( "out" ) ,
            VoxelGrid( "voxel" ) ,
            XForm( "xForm" );

        cmdLineReadable
            Performance( "performance" ) ,
            ShowResidual( "showResidual" ) ,
            NoComments( "noComments" ) ,
            PolygonMesh( "polygonMesh" ) ,
            Confidence( "confidence" ) ,
            NonManifold( "nonManifold" ) ,
            ASCII( "ascii" ) ,
            Density( "density" ) ,
            Verbose( "verbose" );

        cmdLineInt
            Depth( "depth" , 8 ) ,
            SolverDivide( "solverDivide" , 8 ) ,
            IsoDivide( "isoDivide" , 8 ) ,
            KernelDepth( "kernelDepth" ) ,
            AdaptiveExponent( "adaptiveExp" , 1 ) ,
            MinIters( "minIters" , 24 ) ,
            FixedIters( "iters" , -1 ) ,
            VoxelDepth( "voxelDepth" , -1 ) ,
            MinDepth( "minDepth" , 5 ) ,
            MaxSolveDepth( "maxSolveDepth" ) ,
            BoundaryType( "boundary" , 1 ) ,
            Threads( "threads" , omp_get_num_procs() );

        cmdLineFloat
            SamplesPerNode( "samplesPerNode" , 1.f ) ,
            Scale( "scale" , 1.1f ) ,
            SolverAccuracy( "accuracy" , float(1e-3) ) ,
            PointWeight( "pointWeight" , 4.f );

        cmdLineReadable* params[] =
        {
            &In , &Depth , &Out , &XForm ,
            &SolverDivide , &IsoDivide , &Scale , &Verbose , &SolverAccuracy , &NoComments ,
            &KernelDepth , &SamplesPerNode , &Confidence , &NonManifold , &PolygonMesh , &ASCII , &ShowResidual , &MinIters , &FixedIters , &VoxelDepth ,
            &PointWeight , &VoxelGrid , &Threads , &MinDepth , &MaxSolveDepth ,
            &AdaptiveExponent , &BoundaryType ,
            &Density
        };

        cmdLineParse( argc , argv , sizeof(params)/sizeof(cmdLineReadable*) , params , 1 );
        /*if( Density.set ) 
            return Execute< 2 , PlyValueVertex< Real > , true  >(argc , argv, pPC);
        else       
            return Execute< 2 ,      PlyVertex< Real > , false >(argc , argv, pPC);*/
        //Execute
        int i;
        int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
        int commentNum=0;
        char **comments;

        comments = new char*[paramNum + 7];
        for( i=0 ; i<paramNum+7 ; i++ ) comments[i] = new char[1024];

        //if( Verbose.set ) echoStdout=1;

        XForm4x4< Real > xForm , iXForm;
        if( XForm.set )
        {
            FILE* fp = fopen( XForm.value , "r" );
            if( !fp )
            {
                fprintf( stderr , "[WARNING] Could not read x-form from: %s\n" , XForm.value );
                xForm = XForm4x4< Real >::Identity();
            }
            else
            {
                for( int i=0 ; i<4 ; i++ ) for( int j=0 ; j<4 ; j++ ) fscanf( fp , " %f " , &xForm( i , j ) );
                fclose( fp );
            }
        }
        else xForm = XForm4x4< Real >::Identity();
        iXForm = xForm.inverse();

        //DumpOutput2( comments[commentNum++] , "Running Screened Poisson Reconstruction (Version 5.0)\n" , Degree );
        //char str[1024];
        //for( int i=0 ; i<paramNum ; i++ )
        //    if( params[i]->set )
        //    {
        //        params[i]->writeValue( str );
        //        if( strlen( str ) ) DumpOutput2( comments[commentNum++] , "\t--%s %s\n" , params[i]->name , str );
        //        else                DumpOutput2( comments[commentNum++] , "\t--%s\n" , params[i]->name );
        //    }

        double t;
        double tt=Time();
        Real isoValue = 0;

        //Octree< Degree , OutputDensity > tree;
        Octree< 2 , true > tree;
        tree.threads = Threads.value;
        //if( !In.set )
        //{
        //    ShowUsage(argv[0]);
        //    return 0;
        //}
        if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value;
        if( SolverDivide.value<MinDepth.value )
        {
            fprintf( stderr , "[WARNING] %s must be at least as large as %s: %d>=%d\n" , SolverDivide.name , MinDepth.name , SolverDivide.value , MinDepth.value );
            SolverDivide.value = MinDepth.value;
        }
        if( IsoDivide.value<MinDepth.value )
        {
	        fprintf( stderr , "[WARNING] %s must be at least as large as %s: %d>=%d\n" , IsoDivide.name , MinDepth.name , IsoDivide.value , IsoDivide.value );
	        IsoDivide.value = MinDepth.value;
        }
	
        OctNode< TreeNodeData< true > , Real >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE );

        t=Time();
        int kernelDepth = KernelDepth.set ?  KernelDepth.value : Depth.value-2;

        tree.setBSplineData( Depth.value , BoundaryType.value );
        //if( kernelDepth>Depth.value )
        //{
        //    fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value );
        //    return EXIT_FAILURE;
        //}
        //
        int pointNumber = pPC->GetPointNumber();
        std::vector<float> posList(pointNumber * 3);
        std::vector<float> norList(pointNumber * 3);
        for (int pIndex = 0; pIndex < pointNumber; pIndex++)
        {
            posList.at(3 * pIndex + 0) = pPC->GetPoint(pIndex)->GetPosition()[0];
            posList.at(3 * pIndex + 1) = pPC->GetPoint(pIndex)->GetPosition()[1];
            posList.at(3 * pIndex + 2) = pPC->GetPoint(pIndex)->GetPosition()[2];
            norList.at(3 * pIndex + 0) = pPC->GetPoint(pIndex)->GetNormal()[0];
            norList.at(3 * pIndex + 1) = pPC->GetPoint(pIndex)->GetNormal()[1];
            norList.at(3 * pIndex + 2) = pPC->GetPoint(pIndex)->GetNormal()[2];
        }
        //
        double maxMemoryUsage;
        t=Time() , tree.maxMemoryUsage=0;
        //int pointCount = tree.setTree( In.value , Depth.value , MinDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , PointWeight.value , AdaptiveExponent.value , xForm );
        int pointCount = tree.setTree( posList, norList, Depth.value , MinDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , PointWeight.value , AdaptiveExponent.value , xForm );
        tree.ClipTree();
        tree.finalize( IsoDivide.value );

        /*DumpOutput2( comments[commentNum++] , "#             Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
        DumpOutput( "Input Points: %d\n" , pointCount );
        DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() );
        DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );*/

        maxMemoryUsage = tree.maxMemoryUsage;
        t=Time() , tree.maxMemoryUsage=0;
        tree.SetLaplacianConstraints();
        /*DumpOutput2( comments[commentNum++] , "#      Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
        DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) );*/
        maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );

        t=Time() , tree.maxMemoryUsage=0;
        tree.LaplacianMatrixIteration( SolverDivide.value, ShowResidual.set , MinIters.value , SolverAccuracy.value , MaxSolveDepth.value , FixedIters.value );
        /*DumpOutput2( comments[commentNum++] , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
        DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );*/
        maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );

        CoredFileMeshData< PlyValueVertex< Real > > mesh;

        if( Verbose.set ) tree.maxMemoryUsage=0;
        t=Time();
        isoValue = tree.GetIsoValue();
        //DumpOutput( "Got average in: %f\n" , Time()-t );
        //DumpOutput( "Iso-Value: %e\n" , isoValue );

        if( VoxelGrid.set )
        {
            double t = Time();
            FILE* fp = fopen( VoxelGrid.value , "wb" );
            if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value );
            else
            {
                int res;
                Pointer( Real ) values = tree.GetSolutionGrid( res , isoValue , VoxelDepth.value );
                fwrite( &res , sizeof(int) , 1 , fp );
                if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp );
                else
                {
                    float *fValues = new float[res*res*res];
                    for( int i=0 ; i<res*res*res ; i++ ) fValues[i] = float( values[i] );
                    fwrite( fValues , sizeof(float) , res*res*res , fp );
                    delete[] fValues;
                }
                fclose( fp );
                DeletePointer( values );
            }
            //DumpOutput( "Got voxel grid in: %f\n" , Time()-t );
        }

        if( Out.set )
        {
            t = Time() , tree.maxMemoryUsage = 0;
            tree.GetMCIsoTriangles( isoValue , IsoDivide.value , &mesh , 0 , 1 , !NonManifold.set , PolygonMesh.set );
            //if( PolygonMesh.set ) DumpOutput2( comments[commentNum++] , "#         Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
            //else                  DumpOutput2( comments[commentNum++] , "#        Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
            maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
            //DumpOutput2( comments[commentNum++],"#             Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage );

            //if( NoComments.set )
            //{
            //    if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII         , NULL , 0 , iXForm );
            //    else            PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm );
            //}
            //else
            //{
            //    if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII         , comments , commentNum , iXForm );
            //    else            PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , comments , commentNum , iXForm );
            //}
            vertices.clear();
            polygons.clear();
            int incorePointNum = int( mesh.inCorePoints.size() );
            int outofcorePointNum = mesh.outOfCorePointCount();
            DebugLog << "incorePointNum: " << incorePointNum << std::endl;
            DebugLog << "outofcorePointNum: " << outofcorePointNum << std::endl;
            mesh.resetIterator();
            for(int pIndex = 0 ; pIndex < incorePointNum ; pIndex++ )
            {
                PlyValueVertex< Real > vertex = iXForm * mesh.inCorePoints[pIndex];
                vertices.push_back(vertex);
                //ply_put_element(ply, (void *) &vertex);
            }
            for(int pIndex = 0; pIndex < outofcorePointNum; pIndex++ )
            {
                PlyValueVertex< Real > vertex;
                mesh.nextOutOfCorePoint( vertex );
                vertex = iXForm * ( vertex );
                vertices.push_back(vertex);
                //ply_put_element(ply, (void *) &vertex);
            }
            int polyNum = mesh.polygonCount();
            DebugLog << "polyNum: " << polyNum << std::endl;
            for (int pIndex = 0; pIndex < polyNum; pIndex++)
            {
                std::vector< CoredVertexIndex > coreIndex;
                mesh.nextPolygon(coreIndex);
                std::vector< int > pureIndex;
                for (int ii = 0; ii < coreIndex.size(); ii++)
                {
                    if (coreIndex.at(ii).inCore)
                    {
                        pureIndex.push_back(coreIndex.at(ii).idx);
                    }
                    else
                    {
                        pureIndex.push_back(coreIndex.at(ii).idx + incorePointNum);
                    }
                }
                if (coreIndex.size() != 3)
                {
                    DebugLog << "Error: coreIndex.size: " << coreIndex.size() << std::endl;
                }
                polygons.push_back(pureIndex);
            }
            //just for test
            /*DebugLog << "Export inter object" << std::endl;
            std::ofstream fout("pc_inter.obj");
            for (int pIndex = 0; pIndex < vertices.size(); pIndex++)
            {
                PlyValueVertex< float > vert = vertices.at(pIndex);
                fout << "v " << vert.point[0] << " " << vert.point[1] << " " << vert.point[2] << std::endl;
            }
            for (int pIndex = 0; pIndex < polygons.size(); pIndex++)
            {
                fout << "f " << polygons.at(pIndex).at(0) + 1 << " " << polygons.at(pIndex).at(1) + 1 << " " << polygons.at(pIndex).at(2) + 1 << std::endl;
            }
            fout.close();*/
        }
    }
Пример #5
0
/*
______________________________________________________________________________________________

Main
______________________________________________________________________________________________

*/
int main(int argc, char *argv[])
{
	// --- Init Cluster variable ---------------------------------------------------------

	// carmen 0 => local execution i.e. show time on screen
	// carmen 1 => cluster execution i.e. refresh Performance.dat (default)

#if defined PARMPI
	// --- MPI Runtime system initialization
	// size - total number of processors
	// rnak - current CPU
	MPI_Init(&argc,&argv);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
  	size=1;
	rank=0;
#endif
  
	if (argc == 2)
		Cluster = atoi(argv[1]);

	// --- Print messages on screen- -----------------------------------------------------

	cout << "carmen: begin execution.\n\n";
	printf("Carmen %4.2f \n",CarmenVersion);
	cout << "Copyright (C) 2000-2005 by Olivier Roussel.\n";
	cout << "All rights reserved.\n\n";
	
#if defined PARMPI
	//Synchronize all parallel branches
  	MPI_Barrier(MPI_COMM_WORLD);
#endif

  	CPUTime.start();
  
  // --- Create first node of the tree structure ---------------------------------------

	Node 	*Mesh=0;
	FineMesh *FMesh=0;

	
	// --- Init global values (See Parameters.h and Parameters.cpp) ----------------------------

	cout << "carmen: init computation ...\n";
	InitParameters();

  // --- Debug output information for parallel execution -------------------------------------
  
#if defined PARMPI                                                                            
  	if (Multiresolution) 
  	{
		printf("\nParallel Multiresolution solver not implemented yet!\n");
		exit(0);
	}
	
  	printf("My Rank=%d\n",rank);
  
  	// --- Each CPU print his coordinates in the virtual processor cart ------------------------
	printf("Cart_i = %d;     Cart_j = %d;     Cart_k = %d;\n",coords[0],coords[1],coords[2]);
	
  	// --- Each CPU print his computation domain
  	printf("Xmin = %lf;     XMax = %lf;\n",XMin[1],XMax[1]);
	printf("Ymin = %lf;     YMax = %lf;\n",XMin[2],XMax[2]);
	printf("Zmin = %lf;     ZMax = %lf;\n",XMin[3],XMax[3]);
	
  	// --- And the local scale number ----------------------------------------------------------
  	printf("ScaleNb = %d\n",ScaleNb);
#endif
  
	// --- Allocate ----------------------------------------------------------------------------

	if (Multiresolution)
		Mesh = new Node;
	else
		FMesh = new FineMesh;

	// --- Init tree structure -----------------------------------------------------------------

	if (Multiresolution)
	{
		InitTree(Mesh);
		RefreshTree(Mesh);
	}

	// --- Compute initial integral values and init time step ----------------------------------

	if (Multiresolution)
		Mesh->computeIntegral();
	else
		FMesh->computeIntegral();
	
	// -- Write integral values --
	
	
			
	// -- Compute initial time step --
	InitTimeStep();

	if (rank==0) PrintIntegral("Integral.dat");

	// --- Save initial values into files ------------------------------------------------------

	if (PrintEvery == 0)
	{
		if (Multiresolution)
			View(Mesh, "Tree_0.dat", "Mesh_0.dat", "Average_0.dat");
		else
			View(FMesh,"Average_0.dat");
	}
	
	// --- When PrintEvery != 0, save initial values into specific name format ---

	if (PrintEvery != 0)
	{
		if (Multiresolution)
			ViewEvery(Mesh, 0);
		else
			ViewEvery(FMesh, 0);
	}

  	// --- Parallel execution only --------------------------------------------
  	// --- Save to disk DX header for ouput files -----------------------------
  	// --- This file is needed for the external postprocessing (merging files from the different processors)

#if defined PARMPI

	real 	tempXMin[4];
	real	tempXMax[4];
	
  	// --- Save original task parameters for the parallel execution
  	int tempScaleNb=ScaleNb;

  	// --- Simulate sequantial running
  	ScaleNb=AllTaskScaleNb;

  	for (int i=0;i<4;i++) 
  	{
  		tempXMin[i]=XMin[i];
		tempXMax[i]=XMax[i];
		// --- Simulate sequantial running
		XMin[i]=AllXMin[i];
		XMax[i]=AllXMax[i];
  	}

  	// --- Write header with parameters, as we have run sequantial code
  	if (rank==0) FMesh->writeHeader("header.txt");

  	// Restore variables
  	for (int i=0;i<4;i++) 
  	{
		XMin[i]=tempXMin[i];
   		XMax[i]=tempXMax[i];
	}
	
  	ScaleNb=tempScaleNb;

#endif  
  
  	// --- Done ---

	cout << "carmen: done.\n";

	// --- Write solver type ---

	if (Multiresolution)
		cout << "carmen: multiresolution (MR) solver.\n";
	else
		cout << "carmen: finite volume (FV) solver.\n";

	// --- Write number of iterations ---

	if (IterationNb == 1)
		cout << "carmen: compute 1 iteration ...\n";
  	else
		cout << "carmen: compute " << IterationNb << " iterations ...\n";
	
	printf("\n\n\n");

	// --- Begin time iteration ----------------------------------------------------------------

	for (IterationNo = 1; IterationNo <= IterationNb; IterationNo++)
	{

		// --- Time evolution procedure ---
		if (Multiresolution)
			TimeEvolution(Mesh);
		else
			TimeEvolution(FMesh);

		// --- Remesh ---
		 if (Multiresolution) Remesh(Mesh);

		// --- Check CPU Time ---
	  	CPUTime.check();

		// --- Write information every (Refresh) iteration ---
		if ((IterationNo-1)%Refresh == 0)
		{                                          
			// - Write integral values -
			if (rank==0) PrintIntegral("Integral.dat");

			if (Cluster == 0)
				ShowTime(CPUTime);  // Show time on screen
		  //else
			if (rank==0) Performance("carmen.prf"); // Refresh file "carmen.prf"
    		}

		// --- Backup data every (10*Refresh) iteration ---
		if ((IterationNo-1)%(10*Refresh) == 0 && UseBackup)
		{
			if (Multiresolution)
				Backup(Mesh);
			else
				Backup(FMesh);
    		}

		// --- Print solution if IterationNo = PrintIt1 to PrintIt6 ---
		if (Multiresolution)
			ViewIteration(Mesh);
		else
			ViewIteration(FMesh);

		// --- Print solution if IterationNo is a multiple of PrintEvery ---

		if (PrintEvery != 0)
		{
     			if (IterationNo%PrintEvery == 0)
			{
				if (Multiresolution)
					ViewEvery(Mesh, IterationNo);
				else
					ViewEvery(FMesh, IterationNo);
			}
		}

	// --- End time iteration ------------------------------------------------------------------
	}	

	// --- Backup final data  ------------------------------------------------------------------

	IterationNo--;

	if (UseBackup)
  {
		if (Multiresolution)
			Backup(Mesh);
		else
			Backup(FMesh);
	}

	// --- Write integral values ---------------------------------------------------------------
	
	if (rank==0) PrintIntegral("Integral.dat");
	
	IterationNo++;

	// --- Save values into file ---------------------------------------------------------------

	if (Multiresolution)
		View(Mesh, "Tree.dat", "Mesh.dat", "Average.dat");
	else
		View(FMesh, "Average.dat");

	cout << "\ncarmen: done.\n";
	
	// --- Analyse performance and save it into file -------------------------------------------
				
	if (rank==0) Performance("carmen.prf");	

	// --- End ---------------------------------------------------------------------------------

	if (Multiresolution)
		delete Mesh;
	else
		delete FMesh;


#if defined PARMPI

  	//free memory for the MPI runtime variables
	delete[] disp;
	delete[] blocklen;
	int sz;
	MPI_Buffer_detach(&MPIbuffer,&sz);
	// for (int i = 0; i < 4*Dimension; i++)	MPI_Request_free(&req[i]);
	MPI_Finalize();
	
#endif
    
  	cout <<"carmen: end execution.\n";
	return EXIT_SUCCESS;
}