示例#1
0
int main()
{
	// search_space();
	solve(112, true);
	return 0;
}
int main()  
{  
    while(EOF!=scanf("%d",&N) && 0!=N)  
        solve();  
    return 0;  
}  
int main()
{
    printf("%d\n", solve());
    return 0;
}
	int maxDamage(vector <int> level, vector <int> damage) 
	{

		memset(dp,-1,sizeof dp);
		return solve(level,damage,0,0);
	}
示例#5
0
 vector<vector<int>> permute(vector<int>& nums) {
     if (nums.size() <= 1)
         return {nums};
     solve(0, nums);
     return permutations;
 }
示例#6
0
int main( int argc, char *argv[] )
{
    if ( (argc == 2) &&
         (   (GF2::console::find_switch(argc,argv,"--help"))
          || (GF2::console::find_switch(argc,argv,"-h"    ))
         )
       )
    {
        std::cout << "[Usage]:\n"
                  << "\t--generate\n"
                  << "\t--generate3D\n"
                  << "\t--formulate\n"
                  << "\t--formulate3D\n"
                  << "\t--solver mosek|bonmin|gurobi\n"
                  << "\t--solver3D mosek|bonmin|gurobi\n"
                  << "\t--merge\n"
                  << "\t--merge3D\n"
                  << "\t--datafit\n"
                  << "\t--corresp\n"
                  //<< "\t--show\n"
                  << std::endl;

        return EXIT_SUCCESS;
    }
    else if ( GF2::console::find_switch(argc,argv,"--segment") || GF2::console::find_switch(argc,argv,"--segment3D") )
    {
       return segment( argc, argv );
    }
    else if ( GF2::console::find_switch(argc,argv,"--generate") || GF2::console::find_switch(argc,argv,"--generate3D") )
    {
        return generate(argc,argv);
    }
    else if ( GF2::console::find_switch(argc,argv,"--formulate") || GF2::console::find_switch(argc,argv,"--formulate3D"))
    {
        return formulate( argc, argv );
        //return GF2::ProblemSetup::formulateCli<GF2::Solver::PrimitiveContainerT, GF2::Solver::PointContainerT>( argc, argv );
    }
    else if ( GF2::console::find_switch(argc,argv,"--solver") || GF2::console::find_switch(argc,argv,"--solver3D") ) // Note: "solver", not "solve" :-S
    {
        return solve( argc, argv );
        //return GF2::Solver::solve( argc, argv );
    }
    else if ( GF2::console::find_switch(argc,argv,"--datafit") || GF2::console::find_switch(argc,argv,"--datafit3D") )
    {
        return datafit( argc, argv );
        //return GF2::Solver::datafit( argc, argv );
    }
    else if ( GF2::console::find_switch(argc,argv,"--merge") || GF2::console::find_switch(argc,argv,"--merge3D") )
    {
        return merge(argc, argv);
    }
    else if ( GF2::console::find_switch(argc,argv,"--show") )
    {
        std::cerr << "[" << __func__ << "]: " << "the show option has been moved to a separate executable, please use thatt one" << std::endl;
        return 1;
        //return GF2::Solver::show( argc, argv );
    }
    else if ( GF2::console::find_switch(argc,argv,"--subsample") )
    {
        return subsample( argc, argv );
    }
//    else if ( GF2::console::find_switch(argc,argv,"--corresp") || GF2::console::find_switch(argc,argv,"--corresp3D") )
//    {
//        return corresp( argc, argv );
//    }

    std::cerr << "[" << __func__ << "]: " << "unrecognized option" << std::endl;
    return 1;

    // --show --dir . --cloud cloud.ply --scale 0.05f --assoc points_primitives.txt --use-tags --no-clusters --prims primitives.bonmin.txt

//    std::string img_path( "input2.png" );
//    pcl::console::parse_argument( argc, argv, "--img", img_path );
//    float scale = 0.1f;
//    pcl::console::parse_argument( argc, argv, "--scale", scale );

//    return GF2::Solver::run( img_path, scale, {0, M_PI_2, M_PI}, argc, argv );
}
示例#7
0
void SampleSAT::islearn(int datasize, char* outfilename)
{
  int iteration = 0;  // iteration counter
  double drand;       // double  type random variable
  int irand;          // integer type random variable
  double lik;         // likelihood
  double stSec1;
  double stSec2;
  double stSec3;
  int step = 1;       // length of Markov chain
  cdsdSec = 0;
  cdddSec = 0;
  cntSec  = 0;
  double pF = 0;
  double adlogmax;
  double logsum;
  int admaxidx;
  double hl_ss;
  double temp;
  bool flag;
  FILE* helFile = fopen(outfilename, "w");

  while(iteration < lparams_->maxiter){
    iteration++;

    if(iteration == 1){
      for(int j = 0; j < numAtom; j++){
        sd[j] = 0;
      }
    }
    stSec1 = timer.time();

    /////  sampling routine ////
    for(int i = 0; i < lparams_->numsample; i++){
      drand = sat_->getGrand()*datasize;
      irand = drand; // get random integers in (0~datasize)
      for(int j = 0; j < numAtom; j++){
        xx[j] = tdata[irand][j];
      } // get random one training data (one model)
      for(int j = 0; j < step; j++){
        solve(sat_, xx);
      }
      for(int j = 0; j < numAtom; j++){
        sbuf[i][j] = xx[j];
      }
      for(int j = 0; j < numAtom; j++){
        if(xx[j] == 1){
          weight[i] += log(sat_->getTheta(j));
        }else{
          weight[i] += log(1-sat_->getTheta(j));
        }
      }
    }
    normalize(weight, lparams_->numsample);

    for(int j = 0; j < numAtom; j++){
      sd[j] += weight[j]*(xx[j])/(sat_->getTheta(j)) - weight[j]*(1 - xx[j])/(1 - sat_->getTheta(j));
    } //sum sample counts
    cdsdSec += timer.time() - stSec1;

    ///  calc. q(\x|F) from local samples ///
    for(int j = 0; j < datasize_t; j++){
      counts[j] = 0;
    }

    stSec3 = timer.time();

    for(int i = 0; i < datasize_t; i++){
      for(int j = 0; j < numAtom; j++){
        if(sdata[i][j] == 1){
          q_xF[i] += log(sat_->getRealProb(j));
        }else{
          q_xF[i] += log(1-sat_->getRealProb(j));
        }
      }
    }
    normalize(q_xF, datasize_t);
    cntSec += timer.time() - stSec3;

    stSec2 = timer.time();
    for(int i = 0; i < datasize; i++){
      for(int j = 0; j < numAtom; j++){
        dd[j] += (tdata[i][j])/(sat_->getTheta(j)) - (1 - tdata[i][j])/(1 - sat_->getTheta(j));
      }
    } //calc dd
    for(int j = 0; j < numAtom; j++){
      dd[j] /= datasize;
    }
    cdddSec += timer.time() - stSec2;

    for(int j = 0; j < numAtom; j++){
      ex[j] = lparams_->ita*(dd[j] - sd[j]);
    } // calc ex

    sat_->updateTheta(ex); //update theta
    pF=0;
    logsum = 0;
    adlogmax = -100000;
    admaxidx = 0;
    lik=0;

    // calc approximated p(x|F) from "samples"
    stSec3 = timer.time();
    for(int j = 0; j < datasize_t; j++){
      ad[j] = 0;
    }

    for(int i = 0; i < datasize_t; i++){
      for(int j = 0; j < numAtom; j++){
        if(sdata[i][j] == 1){
          ad[i] += log(sat_->getTheta(j));
        }else{
          ad[i] += log(1-sat_->getTheta(j));
        }
      }
    }
    normalize(ad,datasize_t);

    /// calc HL[ad,q_xF] ///
    hl_ss = 0;
    for(int i = 0; i < datasize_t; i++){
      flag = false;
      temp = sqrt(ad[i]) - sqrt(q_xF[i]);
      if(temp > 1.0e-6){
        hl_ss += temp*temp;
      }
      temp = sqrt(1-ad[i]) - sqrt(1-q_xF[i]);
      if(temp > 1.0e-6){
        hl_ss += temp*temp;
      }
    }
    hl_ss = sqrt(hl_ss);
    fprintf(helFile,"%11.5e\n",hl_ss);
    cntSec += timer.time() - stSec3;

    //lik = calclik(ad); //calcurate log-likelihood
    //printf("lik=%.15f\n",lik);
    for(int j = 0; j < numAtom; j++){
      sd[j] = 0;
      dd[j] = 0;
    }
  }
  cout << "calc exp. time(sample) : ";
  Timer::printTime(cout, cdsdSec);
  cout << endl;
  cout << "calc exp. time(data)   : ";
  Timer::printTime(cout, cdddSec);
  cout << endl;
  cout << "calc q(x|F) & HD time  : ";
  Timer::printTime(cout, cntSec);
  cout << endl;
}
示例#8
0
void timeStepper::timeStep(int &numReads, int &numWrites)
{
  af::timer timeStepTimer = af::timer::start();
  PetscPrintf(PETSC_COMM_WORLD, "  Time = %f, dt = %f\n\n", time, dt);
  int numReadsDt, numWritesDt;
  computeDt(numReadsDt, numWritesDt);

  /* First take a half step */
  PetscPrintf(PETSC_COMM_WORLD, "  ---Half step--- \n");
  af::timer halfStepTimer = af::timer::start();

  currentStep = timeStepperSwitches::HALF_STEP;
  /* Apply boundary conditions on primOld */
  af::timer boundaryTimer = af::timer::start();
  boundaries::applyBoundaryConditions(boundaryLeft, boundaryRight,
                                      boundaryTop,  boundaryBottom,
                                      boundaryFront, boundaryBack,
                                      *primOld
                                     );
  setProblemSpecificBCs(numReads,numWrites);
  double boundaryTime = af::timer::stop(boundaryTimer);

  int numReadsElemSet, numWritesElemSet;
  int numReadsComputeFluxes, numWritesComputeFluxes;
  af::timer elemOldTimer = af::timer::start();
  elemOld->set(*primOld, *geomCenter,
               numReadsElemSet, numWritesElemSet
              );
  double elemOldTime = af::timer::stop(elemOldTimer);

  af::timer consOldTimer = af::timer::start();
  elemOld->computeFluxes(0, *consOld, 
                         numReadsComputeFluxes, numWritesComputeFluxes
                        );
  numReads  = numReadsElemSet  + numReadsComputeFluxes;
  numWrites = numWritesElemSet + numWritesComputeFluxes; 
  double consOldTime = af::timer::stop(consOldTimer);

  int numReadsExplicitSouces, numWritesExplicitSouces;
  af::timer explicitSourcesTimer = af::timer::start();
  double dX[3];
  dX[0] = XCoords->dX1;
  dX[1] = XCoords->dX2;
  dX[2] = XCoords->dX3;
  elemOld->computeExplicitSources(dX, *sourcesExplicit,
                                  numReadsExplicitSouces,
                                  numWritesExplicitSouces
                                 );
  numReads  += numReadsExplicitSouces;
  numWrites += numWritesExplicitSouces;
  double explicitSourcesTime = af::timer::stop(explicitSourcesTimer);

  int numReadsImplicitSources, numWritesImplicitSources;
  elemOld->computeImplicitSources(*sourcesImplicitOld,
                                  elemOld->tau,
                                  numReadsImplicitSources,
                                  numWritesImplicitSources
                                 );
  numReads  += numReadsImplicitSources;
  numWrites += numWritesImplicitSources;

  af::timer divFluxTimer = af::timer::start();
  int numReadsDivFluxes, numWritesDivFluxes;
  computeDivOfFluxes(*primOld, numReadsDivFluxes, numWritesDivFluxes);
  numReads  += numReadsDivFluxes;
  numWrites += numWritesDivFluxes;
  double divFluxTime = af::timer::stop(divFluxTimer);

  /* Set a guess for prim */
  for (int var=0; var < vars::numFluidVars; var++)
  {
    prim->vars[var] = primOld->vars[var];
    numReads  += 1;
    numWrites += 1;
  }

  af::timer inductionEqnTimer = af::timer::start();
  cons->vars[vars::B1] = 
    consOld->vars[vars::B1] - 0.5*dt*divFluxes->vars[vars::B1];
  cons->vars[vars::B2] = 
    consOld->vars[vars::B2] - 0.5*dt*divFluxes->vars[vars::B2];
  cons->vars[vars::B3] = 
    consOld->vars[vars::B3] - 0.5*dt*divFluxes->vars[vars::B3];

  prim->vars[vars::B1] = cons->vars[vars::B1]/geomCenter->g;
  prim->vars[vars::B1].eval();
  prim->vars[vars::B2] = cons->vars[vars::B2]/geomCenter->g;
  prim->vars[vars::B2].eval();
  prim->vars[vars::B3] = cons->vars[vars::B3]/geomCenter->g;
  prim->vars[vars::B3].eval();
  double inductionEqnTime = af::timer::stop(inductionEqnTimer);

  primGuessPlusEps->vars[vars::B1] = prim->vars[vars::B1];
  primGuessPlusEps->vars[vars::B2] = prim->vars[vars::B2];
  primGuessPlusEps->vars[vars::B3] = prim->vars[vars::B3];

  primGuessLineSearchTrial->vars[vars::B1] = prim->vars[vars::B1];
  primGuessLineSearchTrial->vars[vars::B2] = prim->vars[vars::B2];
  primGuessLineSearchTrial->vars[vars::B3] = prim->vars[vars::B3];

  /* Solve dU/dt + div.F - S = 0 to get prim at n+1/2 */
  jacobianAssemblyTime = 0.;
  lineSearchTime       = 0.;
  linearSolverTime     = 0.;
  af::timer solverTimer = af::timer::start();
  solve(*prim);
  double solverTime = af::timer::stop(solverTimer);

  /* Copy solution to primHalfStepGhosted. WARNING: Right now
   * primHalfStep->vars[var] points to prim->vars[var]. Might need to do a deep
   * copy. */
  for (int var=0; var < prim->numVars; var++)
  {
    primHalfStep->vars[var] = prim->vars[var];
    numReads  += 1;
    numWrites += 1;
  }
  af::timer halfStepCommTimer = af::timer::start();
  primHalfStep->communicate();
  double halfStepCommTime = af::timer::stop(halfStepCommTimer);

  af::timer halfStepDiagTimer = af::timer::start();
  halfStepDiagnostics(numReads,numWrites);
  double halfStepDiagTime = af::timer::stop(halfStepDiagTimer);
  /* Half step complete */

  double halfStepTime = af::timer::stop(halfStepTimer);

  PetscPrintf(PETSC_COMM_WORLD, "\n");
  PetscPrintf(PETSC_COMM_WORLD, "    ---Performance report--- \n");
  PetscPrintf(PETSC_COMM_WORLD, "     Boundary Conditions : %g secs, %g %\n",
                                 boundaryTime, boundaryTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Setting elemOld     : %g secs, %g %\n",
                                 elemOldTime, 
                                 elemOldTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Conserved vars Old  : %g secs, %g %\n",
                                 consOldTime, consOldTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Explicit sources    : %g secs, %g %\n",
                               explicitSourcesTime, 
                               explicitSourcesTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Divergence of fluxes: %g secs, %g %\n",
                                 divFluxTime, divFluxTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Nonlinear solver    : %g secs, %g %\n",
                                 solverTime, solverTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     |- Jacobian assembly: %g secs, %g %\n",
                                 jacobianAssemblyTime,
                                 jacobianAssemblyTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     |- Linear solver    : %g secs, %g %\n",
                                 linearSolverTime, 
                                 linearSolverTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     |- Linesearch       : %g secs, %g %\n",
                                 lineSearchTime,
                                 lineSearchTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Induction equation  : %g secs, %g %\n",
                                 inductionEqnTime,
                                 inductionEqnTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Communication       : %g secs, %g %\n",
                                 halfStepCommTime,
                                 halfStepCommTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Diagnostics         : %g secs, %g %\n",
                                 halfStepDiagTime,
                                 halfStepDiagTime/halfStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Half step time      : %g secs\n\n",
                                 halfStepTime
             );

  /* Now take the full step */
  PetscPrintf(PETSC_COMM_WORLD, "  ---Full step--- \n");
  af::timer fullStepTimer = af::timer::start();

  currentStep = timeStepperSwitches::FULL_STEP;
  /* apply boundary conditions on primHalfStep */
  boundaryTimer = af::timer::start();
  boundaries::applyBoundaryConditions(boundaryLeft, boundaryRight,
                                      boundaryTop,  boundaryBottom,
                                      boundaryFront, boundaryBack,
                                      *primHalfStep
                                     );
  setProblemSpecificBCs(numReads,numWrites);
  boundaryTime = af::timer::stop(boundaryTimer);

  af::timer elemHalfStepTimer = af::timer::start();
  elemHalfStep->set(*primHalfStep, *geomCenter,
                    numReadsElemSet, numWritesElemSet
                   );
  numReads  += numReadsElemSet;
  numWrites += numWritesElemSet; 
  double elemHalfStepTime = af::timer::stop(elemHalfStepTimer);

  explicitSourcesTimer = af::timer::start();
  elemHalfStep->computeExplicitSources(dX, *sourcesExplicit,
                                       numReadsExplicitSouces,
                                       numWritesExplicitSouces
                                      );
  numReads  += numReadsExplicitSouces;
  numWrites += numWritesExplicitSouces;
  explicitSourcesTime = af::timer::stop(explicitSourcesTimer);

  elemOld->computeImplicitSources(*sourcesImplicitOld,
                                  elemHalfStep->tau,
                                  numReadsImplicitSources,
                                  numWritesImplicitSources
                                 );
  numReads  += numReadsImplicitSources;
  numWrites += numWritesImplicitSources;

  divFluxTimer = af::timer::start();
  computeDivOfFluxes(*primHalfStep, numReadsDivFluxes, numWritesDivFluxes);
  numReads  += numReadsDivFluxes;
  numWrites += numWritesDivFluxes;
  divFluxTime = af::timer::stop(divFluxTimer);

  inductionEqnTimer = af::timer::start();
  cons->vars[vars::B1] = 
    consOld->vars[vars::B1] - dt*divFluxes->vars[vars::B1];
  cons->vars[vars::B2] = 
    consOld->vars[vars::B2] - dt*divFluxes->vars[vars::B2];
  cons->vars[vars::B3] = 
    consOld->vars[vars::B3] - dt*divFluxes->vars[vars::B3];

  prim->vars[vars::B1] = cons->vars[vars::B1]/geomCenter->g;
  prim->vars[vars::B1].eval();
  prim->vars[vars::B2] = cons->vars[vars::B2]/geomCenter->g;
  prim->vars[vars::B2].eval();
  prim->vars[vars::B3] = cons->vars[vars::B3]/geomCenter->g;
  prim->vars[vars::B3].eval();
  inductionEqnTime = af::timer::stop(inductionEqnTimer);

  primGuessPlusEps->vars[vars::B1] = prim->vars[vars::B1];
  primGuessPlusEps->vars[vars::B2] = prim->vars[vars::B2];
  primGuessPlusEps->vars[vars::B3] = prim->vars[vars::B3];

  primGuessLineSearchTrial->vars[vars::B1] = prim->vars[vars::B1];
  primGuessLineSearchTrial->vars[vars::B2] = prim->vars[vars::B2];
  primGuessLineSearchTrial->vars[vars::B3] = prim->vars[vars::B3];

  /* Solve dU/dt + div.F - S = 0 to get prim at n+1/2. NOTE: prim already has
   * primHalfStep as a guess */
  jacobianAssemblyTime = 0.;
  lineSearchTime       = 0.;
  linearSolverTime     = 0.;
  solverTimer = af::timer::start();
  solve(*prim);
  solverTime = af::timer::stop(solverTimer);

  /* Copy solution to primOldGhosted */
  for (int var=0; var < prim->numVars; var++)
  {
    primOld->vars[var] = prim->vars[var];
    numReads  += 1;
    numWrites += 1;
  }
  /* Compute diagnostics */
  af::timer fullStepCommTimer = af::timer::start();
  primOld->communicate();
  double fullStepCommTime = af::timer::stop(fullStepCommTimer);

  time += dt;
  af::timer fullStepDiagTimer = af::timer::start();
  fullStepDiagnostics(numReads,numWrites);
  double fullStepDiagTime = af::timer::stop(fullStepDiagTimer);

  /* done */
  double fullStepTime = af::timer::stop(fullStepTimer);
  double timeStepTime = af::timer::stop(timeStepTimer);

  PetscPrintf(PETSC_COMM_WORLD, "\n");
  PetscPrintf(PETSC_COMM_WORLD, "    ---Performance report--- \n");
  PetscPrintf(PETSC_COMM_WORLD, "     Boundary Conditions : %g secs, %g %\n",
                                 boundaryTime, boundaryTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Setting elemHalfStep: %g secs, %g %\n",
                                 elemHalfStepTime, 
                                 elemHalfStepTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Explicit sources    : %g secs, %g %\n",
                               explicitSourcesTime, 
                               explicitSourcesTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Divergence of fluxes: %g secs, %g %\n",
                                 divFluxTime, divFluxTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Nonlinear solver    : %g secs, %g %\n",
                                 solverTime, solverTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     |- Jacobian assembly: %g secs, %g %\n",
                                 jacobianAssemblyTime,
                                 jacobianAssemblyTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     |- Linear solver    : %g secs, %g %\n",
                                 linearSolverTime, 
                                 linearSolverTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     |- Linesearch       : %g secs, %g %\n",
                                 lineSearchTime,
                                 lineSearchTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Induction equation  : %g secs, %g %\n",
                                 inductionEqnTime,
                                 inductionEqnTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Communication       : %g secs, %g %\n",
                                 fullStepCommTime,
                                 fullStepCommTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Diagnostics         : %g secs, %g %\n",
                                 fullStepDiagTime,
                                 fullStepDiagTime/fullStepTime * 100
             );
  PetscPrintf(PETSC_COMM_WORLD, "     Full step time      : %g secs\n\n",
                                 fullStepTime
             );
  PetscPrintf(PETSC_COMM_WORLD, "   ---Performance / proc : %g Zone cycles/sec/proc\n",
                                 prim->N1Local
                               * prim->N2Local
                               * prim->N3Local / timeStepTime
             );
  PetscPrintf(PETSC_COMM_WORLD, "   ---Total Performance  : %g Zone cycles/sec\n",
                                 N1 * N2 * N3 
                               / timeStepTime
             );
}
示例#9
0
cv::RotatedRect cv::fitEllipse( InputArray _points )
{
    Mat points = _points.getMat();
    int i, n = points.checkVector(2);
    int depth = points.depth();
    CV_Assert( n >= 0 && (depth == CV_32F || depth == CV_32S));

    RotatedRect box;

    if( n < 5 )
        CV_Error( CV_StsBadSize, "There should be at least 5 points to fit the ellipse" );

    // New fitellipse algorithm, contributed by Dr. Daniel Weiss
    Point2f c(0,0);
    double gfp[5], rp[5], t;
    const double min_eps = 1e-8;
    bool is_float = depth == CV_32F;
    const Point* ptsi = points.ptr<Point>();
    const Point2f* ptsf = points.ptr<Point2f>();

    AutoBuffer<double> _Ad(n*5), _bd(n);
    double *Ad = _Ad, *bd = _bd;

    // first fit for parameters A - E
    Mat A( n, 5, CV_64F, Ad );
    Mat b( n, 1, CV_64F, bd );
    Mat x( 5, 1, CV_64F, gfp );

    for( i = 0; i < n; i++ )
    {
        Point2f p = is_float ? ptsf[i] : Point2f((float)ptsi[i].x, (float)ptsi[i].y);
        c += p;
    }
    c.x /= n;
    c.y /= n;

    for( i = 0; i < n; i++ )
    {
        Point2f p = is_float ? ptsf[i] : Point2f((float)ptsi[i].x, (float)ptsi[i].y);
        p -= c;

        bd[i] = 10000.0; // 1.0?
        Ad[i*5] = -(double)p.x * p.x; // A - C signs inverted as proposed by APP
        Ad[i*5 + 1] = -(double)p.y * p.y;
        Ad[i*5 + 2] = -(double)p.x * p.y;
        Ad[i*5 + 3] = p.x;
        Ad[i*5 + 4] = p.y;
    }

    solve(A, b, x, DECOMP_SVD);

    // now use general-form parameters A - E to find the ellipse center:
    // differentiate general form wrt x/y to get two equations for cx and cy
    A = Mat( 2, 2, CV_64F, Ad );
    b = Mat( 2, 1, CV_64F, bd );
    x = Mat( 2, 1, CV_64F, rp );
    Ad[0] = 2 * gfp[0];
    Ad[1] = Ad[2] = gfp[2];
    Ad[3] = 2 * gfp[1];
    bd[0] = gfp[3];
    bd[1] = gfp[4];
    solve( A, b, x, DECOMP_SVD );

    // re-fit for parameters A - C with those center coordinates
    A = Mat( n, 3, CV_64F, Ad );
    b = Mat( n, 1, CV_64F, bd );
    x = Mat( 3, 1, CV_64F, gfp );
    for( i = 0; i < n; i++ )
    {
        Point2f p = is_float ? ptsf[i] : Point2f((float)ptsi[i].x, (float)ptsi[i].y);
        p -= c;
        bd[i] = 1.0;
        Ad[i * 3] = (p.x - rp[0]) * (p.x - rp[0]);
        Ad[i * 3 + 1] = (p.y - rp[1]) * (p.y - rp[1]);
        Ad[i * 3 + 2] = (p.x - rp[0]) * (p.y - rp[1]);
    }
    solve(A, b, x, DECOMP_SVD);

    // store angle and radii
    rp[4] = -0.5 * atan2(gfp[2], gfp[1] - gfp[0]); // convert from APP angle usage
    if( fabs(gfp[2]) > min_eps )
        t = gfp[2]/sin(-2.0 * rp[4]);
    else // ellipse is rotated by an integer multiple of pi/2
        t = gfp[1] - gfp[0];
    rp[2] = fabs(gfp[0] + gfp[1] - t);
    if( rp[2] > min_eps )
        rp[2] = std::sqrt(2.0 / rp[2]);
    rp[3] = fabs(gfp[0] + gfp[1] + t);
    if( rp[3] > min_eps )
        rp[3] = std::sqrt(2.0 / rp[3]);

    box.center.x = (float)rp[0] + c.x;
    box.center.y = (float)rp[1] + c.y;
    box.size.width = (float)(rp[2]*2);
    box.size.height = (float)(rp[3]*2);
    if( box.size.width > box.size.height )
    {
        float tmp;
        CV_SWAP( box.size.width, box.size.height, tmp );
        box.angle = (float)(90 + rp[4]*180/CV_PI);
    }
    if( box.angle < -180 )
        box.angle += 360;
    if( box.angle > 360 )
        box.angle -= 360;

    return box;
}
示例#10
0
int main(){
  scanf("%d %d", &N, &M);
  solve();
  return 0;
}
示例#11
0
void kEpsilon::correct()
{
    if (!turbulence_)
    {
        // Re-calculate viscosity
        mut_ = rho_*Cmu_*sqr(k_)/(epsilon_ + epsilonSmall_);
        mut_.correctBoundaryConditions();

        // Re-calculate thermal diffusivity
        alphat_ = mut_/Prt_;
        alphat_.correctBoundaryConditions();

        return;
    }

    RASModel::correct();

    volScalarField divU = fvc::div(phi_/fvc::interpolate(rho_));

    if (mesh_.moving())
    {
        divU += fvc::div(mesh_.phi());
    }

    tmp<volTensorField> tgradU = fvc::grad(U_);
    volScalarField G("RASModel::G", mut_*(tgradU() && dev(twoSymm(tgradU()))));
    tgradU.clear();

    // Update espsilon and G at the wall
    epsilon_.boundaryField().updateCoeffs();

    // Dissipation equation
    tmp<fvScalarMatrix> epsEqn
    (
        fvm::ddt(rho_, epsilon_)
      + fvm::div(phi_, epsilon_)
      - fvm::laplacian(DepsilonEff(), epsilon_)
     ==
        C1_*G*epsilon_/k_
      - fvm::SuSp(((2.0/3.0)*C1_ + C3_)*rho_*divU, epsilon_)
      - fvm::Sp(C2_*rho_*epsilon_/k_, epsilon_)
    );

    epsEqn().relax();

    epsEqn().boundaryManipulate(epsilon_.boundaryField());

    solve(epsEqn);
    bound(epsilon_, epsilon0_);


    // Turbulent kinetic energy equation

    tmp<fvScalarMatrix> kEqn
    (
        fvm::ddt(rho_, k_)
      + fvm::div(phi_, k_)
      - fvm::laplacian(DkEff(), k_)
     ==
        G
      - fvm::SuSp((2.0/3.0)*rho_*divU, k_)
      - fvm::Sp(rho_*epsilon_/k_, k_)
    );

    kEqn().relax();
    solve(kEqn);
    bound(k_, k0_);


    // Re-calculate viscosity
    mut_ = rho_*Cmu_*sqr(k_)/epsilon_;
    mut_.correctBoundaryConditions();

    // Re-calculate thermal diffusivity
    alphat_ = mut_/Prt_;
    alphat_.correctBoundaryConditions();
}
示例#12
0
int main()
{
    
   
    solve();
}
示例#13
0
/* entry point */
int main(int argc, char** argv){
    solve();
    return 0;
}
示例#14
0
ompl::base::PlannerStatus ompl::tools::Lightning::solve(double time)
{
    ob::PlannerTerminationCondition ptc = ob::timedPlannerTerminationCondition(time);
    return solve(ptc);
}
示例#15
0
 int depthSum(std::vector<NestedInteger>& V) {
   return solve(V, 1);
 }
示例#16
0
int main () {
  int p;
  scanf("%d", &p);
  printf("%d\n", solve(p));
  return 0;
}
示例#17
0
int
full_solve (hid_t fid, hid_t dataset, hid_t* routeDatasets, hid_t dataspace, hid_t routeDataspace, hid_t datatype, hid_t routeDatatype, int cell_index, const inp_t * input_params, SOURCE_MODE mode,
            const cell_table_t * cell, const net_t * network, const time_steps_t * ts,
            int verbose)
{

  double *abundances = NULL;
  alloc_abundances( network, &abundances ); // Allocate the abundances array; it contains all species.

  rout_t* routes = NULL;
  if (( routes =
        malloc (sizeof (rout_t) *  input_params->output.n_output_species * N_OUTPUT_ROUTES)) == NULL)
    {
      fprintf (stderr, "astrochem: %s:%d: routes allocation failed.\n",
               __FILE__, __LINE__);
      return EXIT_SUCCESS;
    }

  double* output_abundances = NULL;
  if (( output_abundances =
        malloc (sizeof (double) * input_params->output.n_output_species )) == NULL)
    {
      fprintf (stderr, "astrochem: %s:%d: array allocation failed.\n",
               __FILE__, __LINE__);
      return EXIT_FAILURE;
    }

#ifdef HAVE_OPENMP
              omp_set_lock(&lock);
#endif


  // Create the memory dataspace, selecting all output abundances
  hsize_t size = input_params->output.n_output_species;
  hid_t memDataspace = H5Screate_simple(1, &size, NULL);

  // Create the file dataspace, and prepare selection of a chunk of the file
  hid_t fileDataspace = H5Scopy(dataspace);
  hsize_t     count[3]={  1, 1,  input_params->output.n_output_species };

  hsize_t routeSize[2] = { input_params->output.n_output_species, N_OUTPUT_ROUTES };
  hsize_t     routeCount[4]={  1, 1,  input_params->output.n_output_species, N_OUTPUT_ROUTES };
  hid_t routeFileDataspace, routeMemDataspace;
  if (input_params->output.trace_routes)
    {
      // Create the route memory dataspace, selecting all output routes
      routeMemDataspace = H5Screate_simple(2, routeSize, NULL);
      // Create the route file dataspace, and prepare selection of a chunk of the file
      routeFileDataspace = H5Scopy(routeDataspace);
    }

#ifdef HAVE_OPENMP
              omp_unset_lock(&lock);
#endif


  // Initializing abundance
#if 0 //Ultra complicated code
  const species_name_t* species = malloc( input_params->abundances.n_initial_abundances * sizeof(*species));
  double *initial_abundances = malloc( input_params->abundances.n_initial_abundances * sizeof(double) );

  int i;
  for( i = 0; i <  input_params->abundances.n_initial_abundances ; i++ )
    {
      strcpy( network->species_names[input_params->abundances.initial_abundances[i].species_idx ] , species[i] );
      initial_abundances[i] = input_params->abundances.initial_abundances[i].abundance;
    }
  set_initial_abundances( species, 3, initial_abundances, &network, abundances); // Set initial abundances
#else // same thing , without using api
  int i;
  for( i = 0; i <  input_params->abundances.n_initial_abundances ; i++ )
    {
      abundances[ input_params->abundances.initial_abundances[i].species_idx ] = input_params->abundances.initial_abundances[i].abundance;
    }
    
    // Add grain abundances
    int g, gm, gp;
    double gabs;
    g = find_species ("grain", network);
    gm = find_species ("grain(-)", network);
    gp = find_species ("grain(+)", network);
    
    // Check if grain abundances have already been initialized one way or another
    gabs=0.0;
    if(g>=0) gabs += abundances[ g ];
    if(gm>=0) gabs += abundances[ gm ];
    if(gp>=0) gabs += abundances[ gp ];
    
    if(gabs == 0.0) {
    	// Grains have not been initialized
    	// Check that grains are defined in our network, and if so, set the grain abundance
    	if(g>=0)
    		abundances[ g ] = input_params->phys.grain_abundance;
    }
#endif


  double min_nh;                 /* Minimum density */

  /* Compute the minimum density to set the absolute tolerance of the
     solver */
  min_nh = cell->nh[0];
  if (mode == DYNAMIC)
    {
      int i;

      for (i = 1; i < ts->n_time_steps; i++)
        {
          if (cell->nh[i] < min_nh)
            {
              min_nh = cell->nh[i];
            }
        }
    }

  astrochem_mem_t astrochem_mem;
  cell_t cell_unik;
  cell_unik.av = cell->av[0];
  cell_unik.nh = cell->nh[0];
  cell_unik.tgas = cell->tgas[0];
  cell_unik.tdust = cell->tdust[0];
  if( solver_init( &cell_unik, network, &input_params->phys, abundances, min_nh, input_params->solver.abs_err,  input_params->solver.rel_err, &astrochem_mem ) != EXIT_SUCCESS )
    {
      return EXIT_FAILURE;
    }
  else
    {
      int i, j;

      /* Solve the system for each time step. */
      for (i = 0; i < ts->n_time_steps; i++)
        {


          if (i!=0 && mode == DYNAMIC)
            {
              cell_unik.av = cell->av[i];
              cell_unik.nh = cell->nh[i];
              cell_unik.tgas = cell->tgas[i];
              cell_unik.tdust = cell->tdust[i];

              if( solve( &astrochem_mem, network, abundances,  ts->time_steps[i], &cell_unik, verbose ) != EXIT_SUCCESS )
                {
                  return EXIT_FAILURE;
                }
            }
          else
            {
              if( solve( &astrochem_mem, network, abundances,  ts->time_steps[i], NULL, verbose ) != EXIT_SUCCESS )
                {
                  return EXIT_FAILURE;
                }
            }


          /* Fill the array of abundances with the output species
             abundances. Ignore species that are not in the
             network. Abundance that are lower than MIN_ABUNDANCES are
             set to 0. */

          for (j = 0; j < input_params->output.n_output_species; j++)
            {
              if (mode == STATIC)
                {
                  output_abundances[j] =
                   (double) NV_Ith_S (astrochem_mem.y, input_params->output.output_species_idx[j]) / cell->nh[0];
                }
              else
                {
                  output_abundances[j] =
                   (double) NV_Ith_S (astrochem_mem.y, input_params->output.output_species_idx[j]) / cell->nh[i];
                }
              if (output_abundances[j] < MIN_ABUNDANCE)
                output_abundances[j] = 0.;

#ifdef HAVE_OPENMP
              omp_set_lock(&lock);
#endif
              // Select a chunk of the file
              hsize_t     start[3]={  cell_index, i, 0 };
              H5Sselect_hyperslab( fileDataspace, H5S_SELECT_SET, start, NULL, count , NULL );

              // Write the chunk
              H5Dwrite(dataset, datatype, memDataspace, fileDataspace, H5P_DEFAULT,
                       output_abundances );

#ifdef HAVE_OPENMP
              omp_unset_lock(&lock);
#endif

            }

          /* Compute the rate of each formation/destruction route for
             each output specie. */

          if (input_params->output.trace_routes)
            {
              for (j = 0; j < input_params->output.n_output_species; j++)
                {
                  int k;
                  int l;
                  for (l = 0; l < N_OUTPUT_ROUTES; l++)
                    {
                      routes[ j*N_OUTPUT_ROUTES + l ].formation.rate = 0;
                      routes[ j*N_OUTPUT_ROUTES + l ].destruction.rate = 0;
                    }
                  for (k = 0; k < network->n_reactions; k++)
                    {
                      /* If the species is a product of the
                         reaction then compute the formation
                         rate. If the rate is greater than the
                         smallest rate in the formation route
                         structure, we add the current reaction
                         number and rate to that structure. */

                      bool specie_in_products = false;
                      int p;
                      for( p = 0; p < MAX_PRODUCTS; p++ )
                        {
                          if( network->reactions[k].products[p] ==  input_params->output.output_species_idx[j])
                            {
                              specie_in_products = true;
                              break;
                            }
                        }
                      if( specie_in_products )
                        {
                          r_t formation_route;
                          double min_rate;
                          unsigned int min_rate_index;
                          if (network->reactions[k].reaction_type == 0)
                            {
                              formation_route.rate = astrochem_mem.params.reac_rates[k];
                              formation_route.rate *=
                               NV_Ith_S (astrochem_mem.y, network->reactions[k].reactants[0]);
                            }
                          else if (network->reactions[k].reaction_type == 23)
                            {
                              formation_route.rate = astrochem_mem.params.reac_rates[k];
                            }
                          else
                            {
                              formation_route.rate = astrochem_mem.params.reac_rates[k];
                              int r;
                              for( r = 0; r < MAX_REACTANTS; r++ )
                                {
                                  if( network->reactions[k].reactants[r] != -1 )
                                    {
                                      formation_route.rate *=
                                       NV_Ith_S (astrochem_mem.y, network->reactions[k].reactants[r]);
                                    }
                                }
                            }
                          formation_route.reaction_no =
                           network->reactions[k].reaction_no;
                          min_rate = routes[ j*N_OUTPUT_ROUTES  ].formation.rate;
                          min_rate_index = 0;
                          for (l = 1; l < N_OUTPUT_ROUTES; l++)
                            {
                              if (routes[ j*N_OUTPUT_ROUTES + l ].formation.rate <
                                  min_rate)
                                {
                                  min_rate =
                                   routes[ j*N_OUTPUT_ROUTES + l ].formation.rate;
                                  min_rate_index = (unsigned int) l;
                                }
                            }
                          if (formation_route.rate > min_rate)
                            {
                              routes[ j*N_OUTPUT_ROUTES + min_rate_index ].formation.rate = formation_route.rate;
                              routes[ j*N_OUTPUT_ROUTES + min_rate_index ].formation.reaction_no = formation_route.reaction_no;
                            }
                        }

                      /* If the species is reactant of the reaction
                         then compute the destruction rate. */
                      bool species_in_reactants = false;
                      int r;
                      for ( r = 0; r < MAX_REACTANTS; r++ )
                        {
                          if ( network->reactions[k].reactants[r] == input_params->output.output_species_idx[j])
                            {
                              species_in_reactants = true;
                              break;
                            }
                        }
                      if( species_in_reactants )
                        {
                          r_t destruction_route;
                          double min_rate;
                          unsigned int min_rate_index;

                          if (network->reactions[k].reaction_type == 0)
                            {
                              destruction_route.rate = astrochem_mem.params.reac_rates[k];
                              destruction_route.rate *=
                               NV_Ith_S (astrochem_mem.y, network->reactions[k].reactants[0]);
                            }
                          else if (network->reactions[k].reaction_type == 23)
                            {
                              destruction_route.rate = astrochem_mem.params.reac_rates[k];
                            }
                          else
                            {
                              destruction_route.rate = astrochem_mem.params.reac_rates[k];
                              for ( r = 0; r < MAX_REACTANTS; r++ )
                                {
                                  if (network->reactions[k].reactants[r] != -1)
                                    {
                                      destruction_route.rate *=
                                       NV_Ith_S (astrochem_mem.y, network->reactions[k].reactants[r]);
                                    }
                                }
                            }
                          destruction_route.reaction_no =
                           network->reactions[k].reaction_no;

                          min_rate = routes[ j*N_OUTPUT_ROUTES  ].destruction.rate;
                          min_rate_index = 0;
                          for (l = 1; l < N_OUTPUT_ROUTES; l++)
                            {
                              if (routes[ j*N_OUTPUT_ROUTES + l ].destruction.rate <
                                  min_rate)
                                {
                                  min_rate =
                                   routes[ j*N_OUTPUT_ROUTES + l ].destruction.rate;
                                  min_rate_index = (unsigned int) l;
                                }
                            }
                          if (destruction_route.rate > min_rate)
                            {
                              routes[ j*N_OUTPUT_ROUTES + min_rate_index ].destruction.rate = destruction_route.rate;
                              routes[ j*N_OUTPUT_ROUTES + min_rate_index ].destruction.reaction_no = destruction_route.reaction_no;
                            }
                        }
                    }
                }
#ifdef HAVE_OPENMP
              omp_set_lock(&lock);
#endif
              // Selecting a chunk of the file
              hsize_t     routeStart[4]={  cell_index, i, 0, 0 };
              H5Sselect_hyperslab( routeFileDataspace, H5S_SELECT_SET, routeStart, NULL, routeCount , NULL );

              int spec_idx;
              for( spec_idx = 0; spec_idx < input_params->output.n_output_species; spec_idx++ )
                {
                  // Writing in each route datasets
                  H5Dwrite( routeDatasets[ spec_idx ], routeDatatype, routeMemDataspace, routeFileDataspace, H5P_DEFAULT,
                            routes );
                }

#ifdef HAVE_OPENMP
              omp_unset_lock(&lock);
#endif
            }
        }

    }
#ifdef HAVE_OPENMP
  omp_set_lock(&lock);
#endif
  // Cleaning up hdf5
  H5Sclose(memDataspace);
  H5Sclose(fileDataspace);
  if (input_params->output.trace_routes)
    {
      H5Sclose(routeMemDataspace);
      H5Sclose(routeFileDataspace);
    }
#ifdef HAVE_OPENMP
  omp_unset_lock(&lock);
#endif
  // Free
  free( output_abundances );
  free( routes );
  free_abundances( abundances );
  solver_close( &astrochem_mem );
  return EXIT_SUCCESS;
}
int main(int argc, char *argv[])
{
    #include "setRootCase.H"

    #include "createTime.H"
    #include "createMesh.H"
    #include "createFields.H"

    #include "initContinuityErrs.H"

    // create cfdemCloud
    #include "readGravitationalAcceleration.H"
    cfdemCloud particleCloud(mesh);

    #include "checkModelType.H"
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    Info<< "\nStarting time loop\n" << endl;

    while (runTime.loop())
    {
        Info<< "Time = " << runTime.timeName() << nl << endl;

        #include "readPISOControls.H"
        #include "CourantNo.H"

        // do particle stuff
        Info << "- evolve()" << endl;
        particleCloud.evolve(voidfraction,Us,U);

        Ksl.internalField() = particleCloud.momCoupleM(0).impMomSource();
        Ksl.correctBoundaryConditions();

        #include "solverDebugInfo.H"

        // get scalar source from DEM        
        particleCloud.forceM(1).manipulateScalarField(Tsource);
        Tsource.correctBoundaryConditions();

        // solve scalar transport equation
        phi = fvc::interpolate(U*voidfraction) & mesh.Sf();

        solve
        (
            fvm::ddt(voidfraction,T)
          + fvm::div(phi, T)
          - fvm::laplacian(DT*voidfraction, T)
          ==
            Tsource
        );

        // Pressure-velocity PISO corrector
        {
            // Momentum predictor
            fvVectorMatrix UEqn
            (
                fvm::ddt(voidfraction,U)
              + fvm::div(phi, U)
              + turbulence->divDevReff(U)
             == 
              - fvm::Sp(Ksl/rho,U)
            );

            UEqn.relax();

            if (momentumPredictor)
            {
                //solve UEqn
                if (modelType=="B")
                    solve(UEqn == - fvc::grad(p) + Ksl/rho*Us);
                else
                    solve(UEqn == - voidfraction*fvc::grad(p) + Ksl/rho*Us);
            }

            // --- PISO loop

            //for (int corr=0; corr<nCorr; corr++)
            int nCorrSoph = nCorr + 5 * pow((1-particleCloud.dataExchangeM().timeStepFraction()),1);
            for (int corr=0; corr<nCorrSoph; corr++)
            {
                volScalarField rUA = 1.0/UEqn.A();
                surfaceScalarField rUAf("(1|A(U))", fvc::interpolate(rUA));

                U = rUA*UEqn.H();

                phi = fvc::interpolate(U*voidfraction) & mesh.Sf();
                                      //+ fvc::ddtPhiCorr(rUA, U, phi)
                surfaceScalarField phiS(fvc::interpolate(Us*voidfraction) & mesh.Sf());
                surfaceScalarField phiGes = phi + rUAf*(fvc::interpolate(Ksl/rho) * phiS);
                volScalarField rUAvoidfraction("(voidfraction2|A(U))",rUA*voidfraction);
                if (modelType=="A")
                    rUAvoidfraction = volScalarField("(voidfraction2|A(U))",rUA*voidfraction*voidfraction);

                // Non-orthogonal pressure corrector loop
                for (int nonOrth=0; nonOrth<=nNonOrthCorr; nonOrth++)
                {
                    // Pressure corrector
                    fvScalarMatrix pEqn
                    (
                        fvm::laplacian(rUAvoidfraction, p) == fvc::div(phiGes) + fvc::ddt(voidfraction)
                    );
                    pEqn.setReference(pRefCell, pRefValue);

                    if
                    (
                        corr == nCorr-1
                     && nonOrth == nNonOrthCorr
                    )
                    {
                        pEqn.solve(mesh.solver("pFinal"));
                    }
                    else
                    {
                        pEqn.solve();
                    }

                    if (nonOrth == nNonOrthCorr)
                    {
                        phiGes -= pEqn.flux();
                    }

                } // end non-orthogonal corrector loop

                #include "continuityErrs.H"

                if (modelType=="B")
                    U -= rUA*fvc::grad(p) - Ksl/rho*Us*rUA;
                else
                    U -= voidfraction*rUA*fvc::grad(p) - Ksl/rho*Us*rUA;

                U.correctBoundaryConditions();

            } // end piso loop
        }

        turbulence->correct();

        runTime.write();

        Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"
            << "  ClockTime = " << runTime.elapsedClockTime() << " s"
            << nl << endl;
    }

    Info<< "End\n" << endl;

    return 0;
}
示例#19
0
文件: 3.cpp 项目: nozdrenkov/sp
int main() {

  solve();

  return 0;
}
示例#20
0
size_t FieldStatic::solveRows() {
    size_t maxIterationsCount = 0;

    auto solveStart = picosecFromStart();

    if (transposed) {
        if (algo::ftr().Balancing()) {
            --balancingCounter;
            if (balancingCounter == 0) {
                shouldSendWeights = true;
                balancingCounter = (int)algo::ftr().TransposeBalanceIterationsInterval();
            }
        }

        resetCalculatingRows();
        bool first = true;

        if (myCoord == 0) {
            balanceBundleSize();
        }

        bool solving = true;
        while (solving) {
            size_t fromFirstPassRow = 0;
            size_t fromSecondPassRow = 0;

            while (fromSecondPassRow < height) {
                size_t nextSecondPassRow = 0;
                if (fromSecondPassRow < height && fromFirstPassRow > fromSecondPassRow) {
                    nextSecondPassRow = secondPasses(fromSecondPassRow, first, true);
                }

                size_t nextFirstPassRow = 0;
                if (fromFirstPassRow < height) {
                    nextFirstPassRow = firstPasses(fromFirstPassRow, first, true);
                }

                if (nextFirstPassRow == 0 && nextSecondPassRow == 0) {
                    if (fromFirstPassRow < height) {
                        nextFirstPassRow = firstPasses(fromFirstPassRow, first, false);
                    }
                    else {
                        nextSecondPassRow = secondPasses(fromSecondPassRow, first, false);
                    }
                }

                if (nextFirstPassRow > 0) {
                    if (nextFirstPassRow == height * 2) {
                        solving = false;
                        break;
                    }
                    fromFirstPassRow = nextFirstPassRow;
                }
                if (nextSecondPassRow > 0) {
                    fromSecondPassRow = nextSecondPassRow;
                }
            }

            if (solving == false) {
                break;
            }

            first = false;
            std::swap(nextCalculatingRows, calculatingRows);
            ++maxIterationsCount;
            if (maxIterationsCount >= MAX_ITTERATIONS_COUNT) {
                break;
            }

            if (leftN == NOBODY) {
                solving = false;
                for (size_t row = 0; row < height; ++row) {
                    if (calculatingRows[row]) {
                        solving = true;
                        break;
                    }
                }

                if (solving == false) {
                    sendDoneAsFirstPass();
                }
            }
        }
    }
    else {
        if (shouldBalanceNext) {
            balance();
            shouldBalanceNext = false;
        }

        size_t firstRealRow = (topN == NOBODY ? 0 : 1);
        size_t lastRealRow = height - firstRealRow - (bottomN ? 0 : 1);
        for (size_t row = 0; row < height; ++row) {
            fillFactors(row, true);
            double delta = solve(row, true);
            size_t iterationsCount = 1;
            auto startTime = picosecFromStart();

            while (delta > epsilon) {
                fillFactors(row, false);
                delta = solve(row, false);
                ++iterationsCount;

                if (iterationsCount > MAX_ITTERATIONS_COUNT) {
                    break;
                }
            }
            maxIterationsCount = std::max(maxIterationsCount, iterationsCount);

            if (firstRealRow <= row && row <= lastRealRow) {
                weights[mySY + row - firstRealRow] =
                        weights[mySY + row - firstRealRow] * algo::ftr().TransposeBalanceFactor()
                        + iterationsCount * (1.0 - algo::ftr().TransposeBalanceTimeFactor())
                        + (picosecFromStart() - startTime) * 1e-12 * algo::ftr().TransposeBalanceTimeFactor();
            }
        }
    }

    if (transposed) {
        syncPartTime += picosecFromStart() - solveStart;
    } else {
        parallelPartTime += picosecFromStart() - solveStart;
    }
    
    return maxIterationsCount;
}
int main(int argc, char *argv[])
{
#include "setRootCase.H"

#include "createTime.H"
#include "createDynamicFvMesh.H"

    pimpleControl pimple(mesh);

#include "createFields.H"
#include "readTimeControls.H"
    bool checkMeshCourantNo =
        readBool(pimple.dict().lookup("checkMeshCourantNo"));
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

#include "initContinuityErrs.H"
#include "readCourantType.H"

    dimensionedScalar v_zero("v_zero", dimVolume/dimTime, 0.0);

    Info<< "\nStarting time loop\n" << endl;

#include "createSurfaceFields.H"
#include "markBadQualityCells.H"

    while (runTime.run())
    {
#include "acousticCourantNo.H"
#include "compressibleCourantNo.H"
#include "readTimeControls.H"
#include "setDeltaT.H"

        runTime++;

        psi.oldTime();
        rho.oldTime();
        p.oldTime();
        U.oldTime();
        h.oldTime();

        Info<< "Time = " << runTime.timeName() << nl << endl;

        // --- Move mesh and update fluxes
        {
            // Do any mesh changes
            mesh.update();

            if (mesh.changing())
            {
                if (runTime.timeIndex() > 1)
                {
                    surfaceScalarField amNew = min(min(phiv_pos - fvc::meshPhi(rho,U) - cSf_pos, phiv_neg - fvc::meshPhi(rho,U) - cSf_neg), v_zero);
                    phiNeg += kappa*(amNew - am)*p_neg*psi_neg;
                    phiPos += (1.0 - kappa)*(amNew - am)*p_neg*psi_neg;
                }
                else
                {
                    phiNeg -= fvc::meshPhi(rho,U) * fvc::interpolate(rho);
                }

                phi = phiPos + phiNeg;

                if (checkMeshCourantNo)
                {
#include "meshCourantNo.H"
                }

#include "markBadQualityCells.H"
            }
        }

        // --- Solve density
        solve
        (
            fvm::ddt(rho) + fvc::div(phi)
        );
        Info<< "rho max/min : " << max(rho).value()
            << " " << min(rho).value() << endl;


        // --- Solve momentum
#include "UEqn.H"

        // --- Solve energy
#include "hEqn.H"

        // --- Solve pressure (PISO)
        {
            while (pimple.correct())
            {
#include "pEqnDyM.H"
            }
#include "updateKappa.H"
        }

        // --- Solve turbulence
        turbulence->correct();

        Ek = 0.5*magSqr(U);
        EkChange = fvc::ddt(rho,Ek) + fvc::div(phiPos,Ek) + fvc::div(phiNeg,Ek);
        dpdt = fvc::ddt(p) - fvc::div(fvc::meshPhi(rho,U), p);

        runTime.write();

        Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"
            << "  ClockTime = " << runTime.elapsedClockTime() << " s"
            << nl << endl;
    }

    Info<< "End\n" << endl;

    return 0;
}
示例#22
0
int main(int argc, char *argv[])
{
    #include "setRootCase.H"

    #include "createTime.H"
    #include "createMesh.H"
    #include "createFields.H"
    #include "initContinuityErrs.H"

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    Info<< nl << "Starting time loop" << endl;

    while (runTime.loop())
    {
        #include "readPISOControls.H"
        #include "readBPISOControls.H"

        Info<< "Time = " << runTime.timeName() << nl << endl;

        #include "CourantNo.H"

        {
            fvVectorMatrix UEqn
            (
                fvm::ddt(U)
              + fvm::div(phi, U)
              - fvc::div(phiB, 2.0*DBU*B)
              - fvm::laplacian(nu, U)
              + fvc::grad(DBU*magSqr(B))
            );

            solve(UEqn == -fvc::grad(p));


            // --- PISO loop

            for (int corr=0; corr<nCorr; corr++)
            {
                volScalarField rUA = 1.0/UEqn.A();

                U = rUA*UEqn.H();

                phi = (fvc::interpolate(U) & mesh.Sf())
                    + fvc::ddtPhiCorr(rUA, U, phi);

                for (int nonOrth=0; nonOrth<=nNonOrthCorr; nonOrth++)
                {
                    fvScalarMatrix pEqn
                    (
                        fvm::laplacian(rUA, p) == fvc::div(phi)
                    );

                    pEqn.setReference(pRefCell, pRefValue);
                    pEqn.solve();

                    if (nonOrth == nNonOrthCorr)
                    {
                        phi -= pEqn.flux();
                    }
                }

                #include "continuityErrs.H"

                U -= rUA*fvc::grad(p);
                U.correctBoundaryConditions();
            }
        }

        // --- B-PISO loop

        for (int Bcorr=0; Bcorr<nBcorr; Bcorr++)
        {
            fvVectorMatrix BEqn
            (
                fvm::ddt(B)
              + fvm::div(phi, B)
              - fvc::div(phiB, U)
              - fvm::laplacian(DB, B)
            );

            BEqn.solve();

            volScalarField rBA = 1.0/BEqn.A();

            phiB = (fvc::interpolate(B) & mesh.Sf())
                + fvc::ddtPhiCorr(rBA, B, phiB);

            fvScalarMatrix pBEqn
            (
                fvm::laplacian(rBA, pB) == fvc::div(phiB)
            );
            pBEqn.solve();

            phiB -= pBEqn.flux();

            #include "magneticFieldErr.H"
        }

        runTime.write();
    }

    Info<< "End\n" << endl;

    return 0;
}
示例#23
0
 void solveSudoku(vector<vector<char>>& board) {
     solve(board);
 }
示例#24
0
文件: wspn.c 项目: layeredqueuing/V5
int
main()
{
	char * place_name;

	printf("\n---Enter the name of the result file.---");
	scanf("\n%s", filename);
	fpr = fopen(filename, "w");

	readin();

#ifdef	WSPN
	printf("---Enter the initial value.\n");
	scanf("%e", &mu);

	netobj = head_net;
	i = 1;
	while (i <= 6) {
		net_name = strdup( netobj->comment->next->line);
		if (strcmp(net_name, "tiny/firstsubnet") == 0)
			change_trate("T14", mu);
		else
			change_trate("T13", mu);

		write_file(net_name);
		put_file();

		solve(net_name);

		if (strcmp(net_name, "tiny/firstsubnet") == 0) {
			fprintf(fpr, "\n %d  First:    %f", i, mu);
			p1 = value_pmmean("P1");
			p13 = value_pmmean("P13");
			mu1 = value_trate("T1");
			mu = (p1 * mu1) / (1 - p13);
		} else {
			fprintf(fpr, "\n %d  Second:   %f", i, mu);
			p2 = value_pmmean("P2");
			p16 = value_pmmean("P16");
			mu2 = value_trate("T2");
			mu = (p2 * mu2) / (1 - p16);
		}
		if (netobj == head_net)
			netobj = head_net->next;
		else
			netobj = head_net;
		i++;
	}
#else
	net_name = strdup( netobj->comment->next->line);
	solve( net_name );
	place_name = "P1";
	printf( "info for %s, pmmean = %f, P(0) = %f, P(1) = %f, P(2) = %f, P(3) = %f, P(4) = %f\n",
	       place_name,
	       value_pmmean( place_name ),
	       value_prob( place_name, 0 ),
	       value_prob( place_name, 1 ),
	       value_prob( place_name, 2 ),
	       value_prob( place_name, 3 ),
	       value_prob( place_name, 4 ) );
	place_name = "P7";
	printf( "info for %s, pmmean = %f, P(0) = %f, P(1) = %f, P(2) = %f, P(3) = %f, P(4) = %f\n",
	       place_name,
	       value_pmmean( place_name ),
	       value_prob( place_name, 0 ),
	       value_prob( place_name, 1 ),
	       value_prob( place_name, 2 ),
	       value_prob( place_name, 3 ),
	       value_prob( place_name, 4 ) );
	place_name = "P11";
	printf( "info for %s, pmmean = %f, P(0) = %f, P(1) = %f, P(2) = %f, P(3) = %f, P(4) = %f\n",
	       place_name,
	       value_pmmean( place_name ),
	       value_prob( place_name, 0 ),
	       value_prob( place_name, 1 ),
	       value_prob( place_name, 2 ),
	       value_prob( place_name, 3 ),
	       value_prob( place_name, 4 ) );
#endif
	(void) fclose(fpr);
	printf("\n\n");
	return 0;
}
示例#25
0
void CPoissonExt::poissonExtend_cuda(cv::Mat &dst,int size)
{

	cv::Mat gx=Mat::zeros(h+2*ex,w+2*ex,CV_32FC4);
	cv::Mat gy=Mat::zeros(h+2*ex,w+2*ex,CV_32FC4);

	#pragma omp parallel for
		for(int y=0;y<h+ex*2;y++)
			for (int x=0;x<w+ex*2;x++)
			{
				if(type[y*(w+2*ex)+x]>1)
				{
					Vec4f BGRA0;
					Vec4f BGRA1;
					BGRA1=dst.at<Vec4b>(y,x);

					if(x>0)
					{
						if(type[y*(w+2*ex)+x-1]>1)
						{
							BGRA0=dst.at<Vec4b>(y,x-1);

							if(BGRA0!=Vec4f(255,0,255,0)&&BGRA1!=Vec4f(255,0,255,0))
								gx.at<Vec4f>(y,x)=BGRA1-BGRA0;

						}
					}

					if(y>0)
					{
						if(type[(y-1)*(w+2*ex)+x]>1)
						{
							BGRA0=dst.at<Vec4b>(y-1,x);

							if(BGRA0!=Vec4f(255,0,255)&&BGRA1!=Vec4f(255,0,255))
								gy.at<Vec4f>(y,x)=BGRA1-BGRA0;
						}
					}
				}

			}


			//matrix
			cusp::csr_matrix<int,float,cusp::host_memory> A(size,size,5*size-w*2-h*2);
			cusp::array1d<float, cusp::host_memory> X0(A.num_rows, 0);
			cusp::array1d<float, cusp::host_memory> B0(A.num_rows, 0);
			cusp::array1d<float, cusp::host_memory> X1(A.num_rows, 0);
			cusp::array1d<float, cusp::host_memory> B1(A.num_rows, 0);
			cusp::array1d<float, cusp::host_memory> X2(A.num_rows, 0);
			cusp::array1d<float, cusp::host_memory> B2(A.num_rows, 0);
		//	cusp::array1d<float, cusp::host_memory> X3(A.num_rows, 0);
		//	cusp::array1d<float, cusp::host_memory> B3(A.num_rows, 0);
			int nNonZeros=0;
			A.row_offsets[0]=0;


			Vec4f BGRA;
			for(int y=0;y<h+ex*2;y++)
				for (int x=0;x<w+ex*2;x++)
				{
					float a[5];
					a[0]=a[1]=a[2]=a[3]=a[4]=0.0f;
					int ii=y*(w+2*ex)+x;

					switch(type[ii])
					{
					case 0://inside
						break;
					case 1://boundary
						a[2]+=1.0f;
						BGRA=dst.at<Vec4b>(y,x);
						B0[index[ii]]+=BGRA[0];
						B1[index[ii]]+=BGRA[1];
						B2[index[ii]]+=BGRA[2];
					//	B3[index[ii]]+=BGRA[3];

					case 2://outside
						if(y-1>=0&&type[ii-(w+2*ex)]>0)
						{
							a[2]+=1.0f;
							a[0]-=1.0f;
							BGRA=gy.at<Vec4f>(y,x);
							B0[index[ii]]+=BGRA[0];
							B1[index[ii]]+=BGRA[1];
							B2[index[ii]]+=BGRA[2];
						//	B3[index[ii]]+=BGRA[3];
						}
						if(x-1>=0&&type[ii-1]>0)
						{
							a[2]+=1.0f;
							a[1]-=1.0f;
							BGRA=gx.at<Vec4f>(y,x);
							B0[index[ii]]+=BGRA[0];
							B1[index[ii]]+=BGRA[1];
							B2[index[ii]]+=BGRA[2];
						//	B3[index[ii]]+=BGRA[3];
						}
						if(x+1<w+2*ex&&type[ii+1]>0)
						{
							a[2]+=1.0f;
							a[3]-=1.0f;
							BGRA=gx.at<Vec4f>(y,x+1);
							B0[index[ii]]-=BGRA[0];
							B1[index[ii]]-=BGRA[1];
							B2[index[ii]]-=BGRA[2];
						//	B3[index[ii]]+=BGRA[3];
						}
						if(y+1<h+2*ex&&type[ii+(w+2*ex)]>0)
						{
							a[2]+=1.0f;
							a[4]-=1.0f;
							BGRA=gy.at<Vec4f>(y+1,x);
							B0[index[ii]]-=BGRA[0];
							B1[index[ii]]-=BGRA[1];
							B2[index[ii]]-=BGRA[2];
						//	B3[index[ii]]+=BGRA[3];
						}


						//put into A
						if(a[0]!=0)
						{
							A.values[nNonZeros]=a[0];
							A.column_indices[nNonZeros]=index[ii-(w+2*ex)];
							nNonZeros++;
						}
						if(a[1]!=0)
						{
							A.values[nNonZeros]=a[1];
							A.column_indices[nNonZeros]=index[ii-1];
							nNonZeros++;
						}
						if(a[2]!=0)
						{
							A.values[nNonZeros]=a[2];
							A.column_indices[nNonZeros]=index[ii];
							nNonZeros++;
						}
						if(a[3]!=0)
						{
							A.values[nNonZeros]=a[3];
							A.column_indices[nNonZeros]=index[ii+1];
							nNonZeros++;
						}
						if(a[4]!=0)
						{
							A.values[nNonZeros]=a[4];
							A.column_indices[nNonZeros]=index[ii+(w+2*ex)];
							nNonZeros++;
						}
						A.row_offsets[index[ii]+1]=nNonZeros;

						break;
					}
				}

				//SOLVER;
				solve(A,B0,X0);
				solve(A,B1,X1);
				solve(A,B2,X2);
			//	solve(A,B3,X3);

				//paste
				#pragma omp parallel for
				for(int y=0;y<h+ex*2;y++)
					for (int x=0;x<w+ex*2;x++)
					{
						int ii=y*(w+2*ex)+x;
						if(type[ii]>0)
						{

							int B=MIN(MAX(X0[index[ii]],0),255);
							int G=MIN(MAX(X1[index[ii]],0),255);
							int R=MIN(MAX(X2[index[ii]],0),255);
							int A=0;
							dst.at<Vec4b>(y,x)=Vec4b(B,G,R,A);
						}
					}

}
示例#26
0
 int run() {
     while ( init(), input() ) {
         output(solve());
     }
     return 0;
 }
示例#27
0
文件: 3461.cpp 项目: 199911/acm
int main() {
	int T;
	scanf( "%d", &T );
	while( T-- ) solve();
	return 0;
}
示例#28
0
void realizableKE_Veh::correct()
{
    RASModel::correct();

    if (!turbulence_)
    {
        return;
    }

    const volTensorField gradU(fvc::grad(U_));
    const volScalarField S2(2*magSqr(dev(symm(gradU))));
    const volScalarField magS(sqrt(S2));

    const volScalarField eta(magS*k_/epsilon_);
    tmp<volScalarField> C1 = max(eta/(scalar(5) + eta), scalar(0.43));

    volScalarField G("RASModel::G", nut_*S2);

    //Estimating source terms for vehicle canopy
    volVectorField Fi = 0.5*Cfcar_*VAD_*mag(U_-Ucar_)*(U_-Ucar_);
    volScalarField Fk = (U_-Ucar_)&Fi;
    volScalarField Fepsilon = epsilon_*sqrt(k_)*Cecar_/L_;

    // Update epsilon and G at the wall
    epsilon_.boundaryField().updateCoeffs();


    // Dissipation equation
    tmp<fvScalarMatrix> epsEqn
    (
        fvm::ddt(epsilon_)
      + fvm::div(phi_, epsilon_)
      - fvm::Sp(fvc::div(phi_), epsilon_)
      - fvm::laplacian(DepsilonEff(), epsilon_)
     ==
        Fepsilon
      + C1*magS*epsilon_
      - fvm::Sp
        (
            C2_*epsilon_/(k_ + sqrt(nu()*epsilon_)),
            epsilon_
        )
    );

    epsEqn().relax();

    epsEqn().boundaryManipulate(epsilon_.boundaryField());

    solve(epsEqn);
    bound(epsilon_, epsilonMin_);


    // Turbulent kinetic energy equation
    tmp<fvScalarMatrix> kEqn
    (
        fvm::ddt(k_)
      + fvm::div(phi_, k_)
      - fvm::Sp(fvc::div(phi_), k_)
      - fvm::laplacian(DkEff(), k_)
     ==
        Fk
      + G - fvm::Sp(epsilon_/k_, k_)
    );

    kEqn().relax();
    solve(kEqn);
    bound(k_, kMin_);


    // Re-calculate viscosity
    nut_ = rCmu(gradU, S2, magS)*sqr(k_)/epsilon_;
    nut_.correctBoundaryConditions();
}
int main() {  
    init();  
    cal();  
    solve();  
    return 0;  
}  
示例#30
0
文件: blas.hpp 项目: 2asoft/xray-16
 V &
 tsv (V &v, const M &m, C) {
     return v = solve (m, v, C ());
 }