Input (int argc, char** argv, const Teuchos::RCP<const Teuchos::Comm<int> >& icomm) {
   init(icomm);
   Teuchos::CommandLineProcessor clp(false);
   clp.setDocString("Unit and performance tester for BlockTriDiContainer. The performance test\n"
                    "constructs a 3D 7-point stencil in a block domain of arbitrary size. The\n"
                    "block is distributed by splitting it in each axis. The index space is\n"
                    "denoted (I,J,K) in the documentation. The lines are in the K dimension.");
   clp.setOption("ni", &ni, "Number of cells in the I dimension.");
   clp.setOption("nj", &nj, "Number of cells in the J dimension.");
   clp.setOption("nk", &nk, "Number of cells in the K dimension.");
   clp.setOption("isplit", &isplit, "Cut the I dimension into this many pieces for MPI distribution. "
                 "isplit*jsplit must equal the number of ranks.");
   clp.setOption("jsplit", &jsplit, "Cut the J dimension into this many pieces for MPI distribution. "
                 "isplit*jsplit must equal the number of ranks.");
   clp.setOption("bs", &bs, "Block size. This might be the number of degrees of freedom in a system of PDEs, "
                 "for example.");
   clp.setOption("nrhs", &nrhs, "Number of right hand sides to solve for.");
   clp.setOption("repeat", &repeat, "Number of times to run the performance test for timing. "
                 "To run the performance test, set it to a number > 0.");
   clp.setOption("iterations", &iterations, "Max number of fixed-point iterations.");
   clp.setOption("tol", &tol, "Tolerance for norm-based termination. Set to <= 0 to turn off norm-based termination.");
   clp.setOption("check-tol-every", &check_tol_every, "Check norm every CE iterations.");
   clp.setOption("verbose", "quiet", &verbose, "Verbose output.");
   clp.setOption("test", "notest", &teuchos_test, "Run unit tests.");
   clp.setOption("jacobi", "tridiag", &jacobi, "Run with little-block Jacobi instead of block tridagional.");
   clp.setOption("contiguous", "noncontiguous", &contiguous, "Use contiguous GIDs.");
   clp.setOption("seq-method", "non-seq-method", &use_seq_method, "Developer option.");
   clp.setOption("overlap-comm", "non-overlap-comm", &use_overlap_comm, "Developer option.");
   auto out = clp.parse(argc, argv, icomm->getRank() == 0 ? &std::cerr : nullptr);
   TEUCHOS_TEST_FOR_EXCEPT_MSG(out > Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED,
                               "Parse error.");
   check();
 }
Beispiel #2
0
//解析命令行参数
int ParseParam(int argc, char* argv[],char *pDSN,const int iDsnLen)
{
    //定义参数格式和选项
    CommandLineParser clp(argc, argv);
    clp.set_check_condition("-H", 0);
    clp.set_check_condition("-h", 0);
    clp.set_check_condition("-c", 1);
    clp.check();

    const vector<CommandLineParser::OptArgsPair>& pairs = clp.opt_args_pairs();
    vector<CommandLineParser::OptArgsPair>::const_iterator it;
    for (it = pairs.begin(); it != pairs.end(); ++it)
    {
        const string& opt = (*it)._first;
        const vector<string>& args = (*it)._second;
        if(opt == "-h" || opt == "-H")
        {
            Help(argc,argv);
            return -1;
        }
        if(opt == "-c")
        {
            SAFESTRCPY(pDSN,iDsnLen,args[0].c_str());
            pDSN[strlen(pDSN)] = '\0';
            continue;
        }
    }
    if(strlen(pDSN) == 0)
    {
        Help(argc,argv);
        return -1;
    }
    return 0;
}
Beispiel #3
0
int	main(void)
{
	FragTrap	clp("CL4P-TR4P");

	std::srand(time(0));

	clp.vaulthunter_dot_exe("nobody");
	clp.meleeAttack("TORGUE");
	clp.rangedAttack("Roland");
	clp.takeDamage(15);
	clp.vaulthunter_dot_exe("nobody1");
	clp.vaulthunter_dot_exe("nobody2");
	clp.vaulthunter_dot_exe("nobody3");
	clp.vaulthunter_dot_exe("nobody4");
	clp.vaulthunter_dot_exe("nobody5");
	clp.beRepaired(2);

	std::cout << std::endl;

	ScavTrap	sca("ButtStallion");

	sca.meleeAttack("Lilith");
	sca.rangedAttack("Mordekai");
	sca.takeDamage(15);
	sca.challengeNewcomer("Jack");
	sca.challengeNewcomer("Nisha");
	sca.challengeNewcomer("Athena");
	sca.beRepaired(2);

	return 0;
}
int main(int argc, char *argv[]){
  
    int c;
    CommandLineParser clp(argv[1],',');   //instantiating the class CommandLineParser
    string line;

    if (argc ==1)  {
        cout << "One argument must be passed." << endl ;
        return -1;
    }
    //use CommandLineParser to get the script name
    char *fileA = clp.extract("script");

cout << "script file is: " << fileA << endl;

    //use ScriptParser to get the commands from script file
    ScriptParser SParser =  ScriptParser();
    ifstream indata(fileA);
    
     while(getline( indata, line ) ) {
        cout<<line << endl;
         SParser.ParseLine(line);
          cout<< SParser.cmd.listID<< " " <<SParser.cmd.value1<< "-"<< SParser.cmd.value2<<" Op.Code:";
          switch (SParser.operationCode())
          {
          case 1:
             
              cout << SParser.operationCode()<<endl;
               // Call your function to insert here
              break;
          case 2:
              
              cout << SParser.operationCode()<<endl;
               // Call your function to delete here
              break;
          case 3:
             
             cout << SParser.operationCode()<<endl;
               // Call your function to insert here
              break;
          case 4:
             cout << SParser.operationCode()<<endl;
             // Call your function to fwr write here
              break;
          case 5:
              cout << SParser.operationCode()<<endl;
             // Call your function to rev write here
              break;
           case 0:
              cout << SParser.operationCode()<<" ERROR "<<endl;
              break;
          }
 
    }
  
  cout << "end of parsing" <<endl;

  return  0;
}
void CLIntervalMaker::print()
{
	CLIntervalPrinter clp(_arg, "test", "var", "", "CLMaker's print()");
	clp.setDegrees(false);
	clp.addIntervals(_clintervals1sigma);
	clp.addIntervals(_clintervals2sigma);
	clp.print();
	cout << endl;
}
Beispiel #6
0
void SundanceGlobal::setOption(const std::string& optionTrueName,
  const std::string& optionFalseName,
  bool& value,
  const std::string& helpMsg)
{
  clp().setOption(optionTrueName.c_str(),
    optionFalseName.c_str(),
    &value,
    helpMsg.c_str());
}
bool LLCommandLineParser::parseCommandLineString(const std::string& str)
{
    // Split the string content into tokens
    boost::escaped_list_separator<char> sep("\\", "\r\n ", "\"'");
    boost::tokenizer< boost::escaped_list_separator<char> > tok(str, sep);
    std::vector<std::string> tokens;
    // std::copy(tok.begin(), tok.end(), std::back_inserter(tokens));
    for(boost::tokenizer< boost::escaped_list_separator<char> >::iterator i = tok.begin();
            i != tok.end();
            ++i)
    {
        if(0 != i->size())
        {
            tokens.push_back(*i);
        }
    }

    po::command_line_parser clp(tokens);
    return parseAndStoreResults(clp);

}
bool LLCommandLineParser::parseCommandLine(int argc, char **argv)
{
    po::command_line_parser clp(argc, argv);
    return parseAndStoreResults(clp);
}
Beispiel #9
0
int SundanceGlobal::init(int* argc, char*** argv)
{

  try
  {
    /* start up MPI. In a serial run, this will be a no-op */
    //      MPISession::init(argc, argv);
    MPISession::init(argc, (char***) argv);

    /* Start a stopwatch. It will be stopped upon a call to finalize() */
    totalTimer().start();

    Tabs tab;

    /* read standard command line flags */
    std::string configFilename = "";

    bool defaultFpCheck = false;
    bool debugWait = false;
    bool showVersion = false;
    bool showBanner = true;
    bool showTimings = false;
    bool cmdFpCheck = defaultFpCheck;
    int defaultWorkSetSize = 400;
    int cmdWorkSetSize = defaultWorkSetSize;

    Assembler::workSetSize() = defaultWorkSetSize;

    clp().setOption("config", &configFilename, "Configuration file");
    clp().setOption("fpcheck", "nofpcheck", &cmdFpCheck, 
      "Check results of math lib calls in expr evals");
    clp().setOption("version", "noversion", &showVersion, 
      "Show Sundance version number and exit");
    clp().setOption("banner", "nobanner", &showBanner, 
      "Show Sundance banner on root processor at start of run");
    clp().setOption("timings", "notimings", &showTimings, 
      "Show timings at end of run");

    clp().setOption("workset", &cmdWorkSetSize, 
      "Work set size");

      
    clp().setOption("debug", "nodebug", &debugWait, "Whether to attach a debugger to this process, holding until 'wait' is set to 0");


    clp().throwExceptions(false);
    clp().recogniseAllOptions(false);

    CommandLineProcessor::EParseCommandLineReturn rtn 
      = clp().parse(*argc, (char**) *argv);

    TEUCHOS_TEST_FOR_EXCEPTION(rtn != CommandLineProcessor::PARSE_SUCCESSFUL,
      std::runtime_error,
      "Command-line parsing failed");


    if (showVersion)
    {
      if (MPIComm::world().getRank()==0)
      {
        cout << "Simulation built using Sundance version " 
             << VersionString::number() 
             << " (" << VersionString::date() << ")" << std::endl;
        exit(0);
      }
    }
    if (showBanner && MPIComm::world().getRank()==0)
    {
      ostringstream oss;
      oss << "Simulation built using Sundance version " 
           << VersionString::number() 
           << " (" << VersionString::date() << ")" << std::endl;
      
      oss << "Sundance is copyright" 
           << std::endl << " (C) 2005-2012 Sandia National Laboratories " 
           << std::endl
           << " (C) 2007-2012 Texas Tech University"
           << std::endl;
      oss << "and is licensed under the GNU Lesser General Public License, version 2.1" << std::endl;
      oss << std::endl;
      cout << oss.str() << flush;
    }

    MPIComm::world().synchronize();
    if (!showTimings) skipTimingOutput() = true;

    //      debugWait = true;
    if (debugWait)
    {
      int wait=1;
      int pid = getpid();
      std::string myCommandName=((char**)(*argv))[0];
      std::string debugCmd = "ddd --gdb -x ~/.gdbinit " + myCommandName 
        + " " + Teuchos::toString(pid) + " &";
      cout << "launching " << debugCmd << std::endl;
      system(debugCmd.c_str());
      while (wait) {;}
    }


    bool worksetSetOnCmdLine = cmdWorkSetSize != defaultWorkSetSize;
    if (worksetSetOnCmdLine)
    {
      Assembler::workSetSize() = (int) cmdWorkSetSize;
    }
  }
  catch(std::exception& e)
  {
    handleException(e);
    return 1;
  }
  return 0;
} 
Beispiel #10
0
int main(int argc, char* argv[])
{
    int iRet = 0;
    if(argc < 2 || strcmp(argv[1],"-h")==0||strcmp(argv[1],"-H")==0)
    {
        Help();
        return iRet;
    }
	bool bShowObject = false;
	bool bIncSystable = false;
	char sTypeName[128] = {0};
	char sConStr[256] = {0};
	
    char sDsn[32] = {0};
	char sUid[32] = {0};
	char sPwd[32] = {0};
	
    //定义参数格式和选项
    CommandLineParser clp(argc, argv);
    //clp.set_check_condition("", 7);					// 指定程序的参数个数
    // 指定选项的参数个数,下同
	clp.set_check_condition("-l", 0);

	clp.set_check_condition("-h", 0);
	
	clp.set_check_condition("-n", 1);
	clp.set_check_condition("-s", 0);
	clp.set_check_condition("-c", 1);

	
	
    if(clp.check() == false)
	{
    	Help();
        return 0;
	}
	
	
    const std::vector<CommandLineParser::OptArgsPair>& pairs = clp.opt_args_pairs();
	std::vector<CommandLineParser::OptArgsPair>::const_iterator it;

	
	for (it = pairs.begin(); it != pairs.end(); ++it)
	{
		const string& opt = (*it)._first;
		const std::vector<string>& args = (*it)._second;
		
		if(opt == "-l")
		{
			
           bShowObject = true;
			continue;
		}
		if(opt == "-h" || opt == "-H")
		{
        	Help();
        	return 0;
		}
		if(opt == "-c")
		{
            SAFESTRCPY(sConStr,sizeof(sConStr),args[0].c_str());
			sConStr[strlen(sConStr)] = '\0';
			continue;
		}
        if(opt == "-n")
		{
            SAFESTRCPY(sTypeName,sizeof(sTypeName),args[0].c_str());
			sTypeName[strlen(sTypeName)]='\0';
            continue;
		}
        if(opt == "-s")
		{
           bIncSystable =true;
            continue;
		}
		
       
    
        
    }

	//if(bShowObject && sTypeName[0] != 0)
	//{
	//	TADD_ERROR(ERR_APP_INVALID_PARAM,"can't show object names and export ddl at the same time,the cmd option is invalid");
	//	return 0;

	//}

	CHECK_RET(ParseQmdbOper(sConStr,sDsn,sUid,sPwd,32),"the connection str is invalid");
	CHECK_RET(CheckConStrValid(sDsn,sUid,sPwd),"the user is invaid for this dsn");
	
	

    TADD_START(sDsn,"mdbSchema",0,false,false);
    TADD_NORMAL("[BEGIN]");
    
    CHECK_RET(ExptDDL(sDsn,bShowObject,bIncSystable,sTypeName),"ExptDDL failed");
    TADD_NORMAL("[END]");
    return 0;
}
Beispiel #11
0
void CEigenLSS::solve()
{
#ifdef CF_HAVE_TRILINOS
  Timer timer;
  const Uint nb_rows = size();
  cf_assert(nb_rows == m_system_matrix.outerSize());

  Epetra_SerialComm comm;
  Epetra_Map map(nb_rows, 0, comm);

  Epetra_Vector ep_rhs(View, map, m_rhs.data());
  Epetra_Vector ep_sol(View, map, m_solution.data());

  // Count non-zeros
  std::vector<int> nnz(nb_rows, 0);
  for(int row=0; row < nb_rows; ++row)
  {
    for(MatrixT::InnerIterator it(m_system_matrix, row); it; ++it)
    {
      ++nnz[row];
    }
    cf_assert(nnz[row]);
  }

  Epetra_CrsMatrix ep_A(Copy, map, &nnz[0]);
  time_matrix_construction = timer.elapsed(); timer.restart();

  // Fill the matrix
  for(int row=0; row < nb_rows; ++row)
  {
    std::vector<int> indices; indices.reserve(nnz[row]);
    std::vector<Real> values; values.reserve(nnz[row]);
    for(MatrixT::InnerIterator it(m_system_matrix, row); it; ++it)
    {
      indices.push_back(it.col());
      values.push_back(it.value());
    }
    ep_A.InsertGlobalValues(row, nnz[row], &values[0], &indices[0]);
  }

  ep_A.FillComplete();

  time_matrix_fill = timer.elapsed(); timer.restart();

///////////////////////////////////////////////////////////////////////////////////////////////
//BEGIN////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

  Teuchos::RCP<Epetra_CrsMatrix> epetra_A=Teuchos::rcpFromRef(ep_A);
  Teuchos::RCP<Epetra_Vector>    epetra_x=Teuchos::rcpFromRef(ep_sol);
  Teuchos::RCP<Epetra_Vector>    epetra_b=Teuchos::rcpFromRef(ep_rhs);

  const URI config_uri = option("config_file").value<URI>();
  const std::string config_path = config_uri.path();

  Stratimikos::DefaultLinearSolverBuilder linearSolverBuilder(config_path); // the most important in general setup

  Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); // TODO: decouple from fancyostream to ostream or to C stdout when possible
  typedef Teuchos::ParameterList::PrintOptions PLPrintOptions;
  Teuchos::CommandLineProcessor  clp(false); // false: don't throw exceptions

  Teuchos::RCP<const Thyra::LinearOpBase<double> > A = Thyra::epetraLinearOp( epetra_A );
  Teuchos::RCP<Thyra::VectorBase<double> >         x = Thyra::create_Vector( epetra_x, A->domain() );
  Teuchos::RCP<const Thyra::VectorBase<double> >   b = Thyra::create_Vector( epetra_b, A->range() );

  // r = b - A*x, initial L2 norm
  double nrm_r=0.;
  Real systemResidual=-1.;
  {
    Epetra_Vector epetra_r(*epetra_b);
    Epetra_Vector epetra_A_x(epetra_A->OperatorRangeMap());
    epetra_A->Apply(*epetra_x,epetra_A_x);
    epetra_r.Update(-1.0,epetra_A_x,1.0);
    epetra_r.Norm2(&nrm_r);
  }

  // Reading in the solver parameters from the parameters file and/or from
  // the command line.  This was setup by the command-line options
  // set by the setupCLP(...) function above.
  linearSolverBuilder.readParameters(0); // out.get() if want confirmation about the xml file within trilinos
  Teuchos::RCP<Thyra::LinearOpWithSolveFactoryBase<double> > lowsFactory = linearSolverBuilder.createLinearSolveStrategy(""); // create linear solver strategy
  lowsFactory->setVerbLevel(Teuchos::VERB_NONE); // set verbosity

//  // print back default and current settings
//  if (opts->trilinos.dumpDefault!=0) {
//    fflush(stdout); cout << flush;
//    _MMESSAGE_(0,1,"Dumping Trilinos/Stratimikos solver defaults to files: 'trilinos_default.txt' and 'trilinos_default.xml'...\n");
//    fflush(stdout); cout << flush;
//    std::ofstream ofs("./trilinos_default.txt");
//    linearSolverBuilder.getValidParameters()->print(ofs,PLPrintOptions().indent(2).showTypes(true).showDoc(true)); // the last true-false is the deciding about whether printing documentation to option or not
//    ofs.flush();ofs.close();
//    ofs.open("./trilinos_default.xml");
//    Teuchos::writeParameterListToXmlOStream(*linearSolverBuilder.getValidParameters(),ofs);
//    ofs.flush();ofs.close();
//  }
//  if (opts->trilinos.dumpCurrXML!=0) {
//    fflush(stdout); cout << flush;
//    _MMESSAGE_(0,1,"Dumping Trilinos/Stratimikos current settings to file: 'trilinos_current.xml'...\n");
//    fflush(stdout); cout << flush;
//    linearSolverBuilder.writeParamsFile(*lowsFactory,"./trilinos_current.xml");
//  }

  time_solver_setup = timer.elapsed(); timer.restart();

  // solve the matrix
  Teuchos::RCP<Thyra::LinearOpWithSolveBase<double> > lows = Thyra::linearOpWithSolve(*lowsFactory, A); // create solver
  Thyra::solve(*lows, Thyra::NOTRANS, *b, &*x); // solve

  time_solve = timer.elapsed(); timer.restart();

  // r = b - A*x, final L2 norm
  {
    Epetra_Vector epetra_r(*epetra_b);
    Epetra_Vector epetra_A_x(epetra_A->OperatorRangeMap());
    epetra_A->Apply(*epetra_x,epetra_A_x);
    epetra_r.Update(-1.0,epetra_A_x,1.0);
    systemResidual=1./nrm_r;
    nrm_r=0.;
    epetra_r.Norm2(&nrm_r);
    systemResidual*=nrm_r;
  }

  time_residual = timer.elapsed();

///////////////////////////////////////////////////////////////////////////////////////////////
//END//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

#else // no trilinos

#ifdef CF_HAVE_SUPERLU
  Eigen::SparseMatrix<Real> A(m_system_matrix);
  Eigen::SparseLU<Eigen::SparseMatrix<Real>,Eigen::SuperLU> lu_of_A(A);
  if(!lu_of_A.solve(rhs(), &m_solution))
    throw Common::FailedToConverge(FromHere(), "Solution failed.");
#else // no trilinos and no superlu
  RealMatrix A(m_system_matrix);
  Eigen::FullPivLU<RealMatrix> lu_of_A(A);
  m_solution = lu_of_A.solve(m_rhs);
#endif // end ifdef superlu

#endif // end ifdef trilinos

}
Beispiel #12
0
    unsigned render_clipper(Scanline& sl, Ras& ras)
    {
        agg::pixfmt_bgr24 pf(rbuf_window());
        agg::renderer_base<agg::pixfmt_bgr24> rb(pf);
        agg::renderer_scanline_aa_solid<agg::renderer_base<agg::pixfmt_bgr24> > ren(rb);


        switch(m_polygons.cur_item())
        {
            case 0:
            {
                //------------------------------------
                // Two simple paths
                //
                agg::path_storage ps1;
                agg::path_storage ps2;

                agg::conv_clipper<agg::path_storage, agg::path_storage> clp(ps1, ps2, agg::clipper_or, agg::clipper_non_zero, agg::clipper_non_zero);

                double x = m_x - initial_width()/2 + 100;
                double y = m_y - initial_height()/2 + 100;
                ps1.move_to(x+140, y+145);
                ps1.line_to(x+225, y+44);
                ps1.line_to(x+296, y+219);
                ps1.close_polygon();

                ps1.line_to(x+226, y+289);
                ps1.line_to(x+82,  y+292);

                ps1.move_to(x+220, y+222);
                ps1.line_to(x+363, y+249);
                ps1.line_to(x+265, y+331);

                ps1.move_to(x+242, y+243);
                ps1.line_to(x+268, y+309);
                ps1.line_to(x+325, y+261);

                ps1.move_to(x+259, y+259);
                ps1.line_to(x+273, y+288);
                ps1.line_to(x+298, y+266);

                ps2.move_to(100+32,  100+77);
                ps2.line_to(100+473, 100+263);
                ps2.line_to(100+351, 100+290);
                ps2.line_to(100+354, 100+374);

                ras.reset();
                ras.add_path(ps1);
                ren.color(agg::rgba(0, 0, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                ras.reset();
                ras.add_path(ps2);
                ren.color(agg::rgba(0, 0.6, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                perform_rendering(sl, ras, ren, clp);
            }
            break;

            case 1:
            {
                //------------------------------------
                // Closed stroke
                //
                agg::path_storage ps1;
                agg::path_storage ps2;
                agg::conv_stroke<agg::path_storage> stroke(ps2);
                stroke.width(10.0);

                agg::conv_clipper<agg::path_storage, 
                              agg::conv_stroke<agg::path_storage> > clp(ps1, stroke, agg::clipper_or, agg::clipper_non_zero, agg::clipper_non_zero);


                double x = m_x - initial_width()/2 + 100;
                double y = m_y - initial_height()/2 + 100;
                ps1.move_to(x+140, y+145);
                ps1.line_to(x+225, y+44);
                ps1.line_to(x+296, y+219);
                ps1.close_polygon();

                ps1.line_to(x+226, y+289);
                ps1.line_to(x+82,  y+292);

                ps1.move_to(x+220-50, y+222);
                ps1.line_to(x+265-50, y+331);
                ps1.line_to(x+363-50, y+249);
                ps1.close_polygon(agg::path_flags_ccw);

                ps2.move_to(100+32,  100+77);
                ps2.line_to(100+473, 100+263);
                ps2.line_to(100+351, 100+290);
                ps2.line_to(100+354, 100+374);
                ps2.close_polygon();

                ras.reset();
                ras.add_path(ps1);
                ren.color(agg::rgba(0, 0, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                ras.reset();
                ras.add_path(stroke);
                ren.color(agg::rgba(0, 0.6, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                perform_rendering(sl, ras, ren, clp);
            }
            break;


            case 2:
            {
                //------------------------------------
                // Great Britain and Arrows
                //
                agg::path_storage gb_poly;
                agg::path_storage arrows;
                make_gb_poly(gb_poly);
                make_arrows(arrows);

                agg::trans_affine mtx1;
                agg::trans_affine mtx2;
                mtx1 *= agg::trans_affine_translation(-1150, -1150);
                mtx1 *= agg::trans_affine_scaling(2.0);

                mtx2 = mtx1;
                mtx2 *= agg::trans_affine_translation(m_x - initial_width()/2, 
                                                      m_y - initial_height()/2);

                agg::conv_transform<agg::path_storage> trans_gb_poly(gb_poly, mtx1);
                agg::conv_transform<agg::path_storage> trans_arrows(arrows, mtx2);

                agg::conv_clipper<agg::conv_transform<agg::path_storage>, 
                              agg::conv_transform<agg::path_storage> > clp(trans_gb_poly, trans_arrows, agg::clipper_or, agg::clipper_non_zero, agg::clipper_non_zero);

                ras.add_path(trans_gb_poly);
                ren.color(agg::rgba(0.5, 0.5, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                agg::conv_stroke<agg::conv_transform<agg::path_storage> > stroke_gb_poly(trans_gb_poly);
                stroke_gb_poly.width(0.1);
                ras.add_path(stroke_gb_poly);
                ren.color(agg::rgba(0, 0, 0));
                agg::render_scanlines(ras, sl, ren);
        
                ras.add_path(trans_arrows);
                ren.color(agg::rgba(0.0, 0.5, 0.5, 0.1));
                agg::render_scanlines(ras, sl, ren);

                perform_rendering(sl, ras, ren, clp);
            }
            break;


            case 3:
            {
                //------------------------------------
                // Great Britain and a Spiral
                //
                spiral sp(m_x, m_y, 10, 150, 30, 0.0);
                agg::conv_stroke<spiral> stroke(sp);
                stroke.width(15.0);

                agg::path_storage gb_poly;
                make_gb_poly(gb_poly);

                agg::trans_affine mtx;
                mtx *= agg::trans_affine_translation(-1150, -1150);
                mtx *= agg::trans_affine_scaling(2.0);

                agg::conv_transform<agg::path_storage> trans_gb_poly(gb_poly, mtx);

                agg::conv_clipper<agg::conv_transform<agg::path_storage>, 
                              agg::conv_stroke<spiral> > clp(trans_gb_poly, stroke, agg::clipper_or, agg::clipper_non_zero, agg::clipper_non_zero);

                ras.add_path(trans_gb_poly);
                ren.color(agg::rgba(0.5, 0.5, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                agg::conv_stroke<agg::conv_transform<agg::path_storage> > stroke_gb_poly(trans_gb_poly);
                stroke_gb_poly.width(0.1);
                ras.add_path(stroke_gb_poly);
                ren.color(agg::rgba(0, 0, 0));
                agg::render_scanlines(ras, sl, ren);
        
                ras.add_path(stroke);
                ren.color(agg::rgba(0.0, 0.5, 0.5, 0.1));
                agg::render_scanlines(ras, sl, ren);

                perform_rendering(sl, ras, ren, clp);
            }
            break;


            case 4:
            {
                //------------------------------------
                // Spiral and glyph
                //
                spiral sp(m_x, m_y, 10, 150, 30, 0.0);
                agg::conv_stroke<spiral> stroke(sp);
                stroke.width(15.0);

                agg::path_storage glyph;
                glyph.move_to(28.47, 6.45);
                glyph.curve3(21.58, 1.12, 19.82, 0.29);
                glyph.curve3(17.19, -0.93, 14.21, -0.93);
                glyph.curve3(9.57, -0.93, 6.57, 2.25);
                glyph.curve3(3.56, 5.42, 3.56, 10.60);
                glyph.curve3(3.56, 13.87, 5.03, 16.26);
                glyph.curve3(7.03, 19.58, 11.99, 22.51);
                glyph.curve3(16.94, 25.44, 28.47, 29.64);
                glyph.line_to(28.47, 31.40);
                glyph.curve3(28.47, 38.09, 26.34, 40.58);
                glyph.curve3(24.22, 43.07, 20.17, 43.07);
                glyph.curve3(17.09, 43.07, 15.28, 41.41);
                glyph.curve3(13.43, 39.75, 13.43, 37.60);
                glyph.line_to(13.53, 34.77);
                glyph.curve3(13.53, 32.52, 12.38, 31.30);
                glyph.curve3(11.23, 30.08, 9.38, 30.08);
                glyph.curve3(7.57, 30.08, 6.42, 31.35);
                glyph.curve3(5.27, 32.62, 5.27, 34.81);
                glyph.curve3(5.27, 39.01, 9.57, 42.53);
                glyph.curve3(13.87, 46.04, 21.63, 46.04);
                glyph.curve3(27.59, 46.04, 31.40, 44.04);
                glyph.curve3(34.28, 42.53, 35.64, 39.31);
                glyph.curve3(36.52, 37.21, 36.52, 30.71);
                glyph.line_to(36.52, 15.53);
                glyph.curve3(36.52, 9.13, 36.77, 7.69);
                glyph.curve3(37.01, 6.25, 37.57, 5.76);
                glyph.curve3(38.13, 5.27, 38.87, 5.27);
                glyph.curve3(39.65, 5.27, 40.23, 5.62);
                glyph.curve3(41.26, 6.25, 44.19, 9.18);
                glyph.line_to(44.19, 6.45);
                glyph.curve3(38.72, -0.88, 33.74, -0.88);
                glyph.curve3(31.35, -0.88, 29.93, 0.78);
                glyph.curve3(28.52, 2.44, 28.47, 6.45);
                glyph.close_polygon();

                glyph.move_to(28.47, 9.62);
                glyph.line_to(28.47, 26.66);
                glyph.curve3(21.09, 23.73, 18.95, 22.51);
                glyph.curve3(15.09, 20.36, 13.43, 18.02);
                glyph.curve3(11.77, 15.67, 11.77, 12.89);
                glyph.curve3(11.77, 9.38, 13.87, 7.06);
                glyph.curve3(15.97, 4.74, 18.70, 4.74);
                glyph.curve3(22.41, 4.74, 28.47, 9.62);
                glyph.close_polygon();

                agg::trans_affine mtx;
                mtx *= agg::trans_affine_scaling(4.0);
                mtx *= agg::trans_affine_translation(220, 200);
                agg::conv_transform<agg::path_storage> trans(glyph, mtx);
                agg::conv_curve<agg::conv_transform<agg::path_storage> > curve(trans);

                agg::conv_clipper<agg::conv_stroke<spiral>, 
                                 agg::conv_curve<
                                     agg::conv_transform<
                                         agg::path_storage> > > clp(stroke, curve, agg::clipper_or, agg::clipper_non_zero, agg::clipper_non_zero);

                ras.reset();
                ras.add_path(stroke);
                ren.color(agg::rgba(0, 0, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                ras.reset();
                ras.add_path(curve);
                ren.color(agg::rgba(0, 0.6, 0, 0.1));
                agg::render_scanlines(ras, sl, ren);

                perform_rendering(sl, ras, ren, clp);
            }
            break;
        }

        return 0;
    }
int SpecCheckInterface::processOptions(int argc, char **argv)
{
  //--------------------------------------------------------------------------------------------
  // Initialize directories used
  //--------------------------------------------------------------------------------------------


  //--------------------------------------------------------------------------------------------
  // Parse the command line parameters
  //--------------------------------------------------------------------------------------------
  vector<CommandLineParser::Option> listOptions;

  //  c++ instruction                            cmd line option    parameter name    takes value?

  listOptions.push_back(CommandLineParser::Option("-help",            "help",             false));
  listOptions.push_back(CommandLineParser::Option("-version",         "VERSION",          false));

  listOptions.push_back(CommandLineParser::Option("-input-list",      "INPUT_LIST",       true));
  listOptions.push_back(CommandLineParser::Option("-inputspectra",    "INPUT_SPECS_MS",   true));

  // parameter file
  listOptions.push_back(CommandLineParser::Option("-p",               "PARAMETER_FILE",   true));


  ////////////////////////////////////////////////////////////////////////////////
  // Execute the command line parser
  CommandLineParser clp(argc, argv, 0, listOptions);

  ////////////////////////////////////////////////////////////////////////////////
  // Checking for errors
  string parser_error;
  if (!clp.validate(parser_error)) {
    ERROR_MSG(parser_error);
    return -1;
  }


  ////////////////////////////////////////////////////////////////////////////////
  // The parameters' values
  ParameterList commandLineParams;
  clp.getOptionsAsParameterList(commandLineParams);

  ////////////////////////////////////////////////////////////////////////////////
  // Parameter file
  ////////////////////////////////////////////////////////////////////////////////

  if (commandLineParams.exists("PARAMETER_FILE")) {

    string parameterFilename = commandLineParams.getValue("PARAMETER_FILE");

    ParameterList ip;
    ip.readFromFile(parameterFilename);
    // Combine the command line parameters to the file ones
    //   Command line parameters take precedence (hence the overwrite flag not set)
    commandLineParams.addList(ip, false);
  }

  ////////////////////////////////////////////////////////////////////////////////
  // "help" prints help and exits
  if (commandLineParams.exists("VERSION"))
    return version(cout);

  ////////////////////////////////////////////////////////////////////////////////
  // the same for "version"
  if (commandLineParams.exists("help"))
    return help(cout);



  ////////////////////////////////////////////////////////////////////////////////
  // File load section

  // input spectra file to load
  if (commandLineParams.exists("INPUT_LIST")) {
    inputFilesNames = commandLineParams.getValue("INPUT_LIST").c_str();

    // load input files names
    if(!loadStringVector(inputFilesNames, inputFiles)) {
      cerr << "Unable to load file: " << inputFilesNames << endl;
      exit(0);
    }
  }


  if (commandLineParams.exists("INPUT_SPECS_MS")) {
    string aux = commandLineParams.getValue("INPUT_SPECS_MS").c_str();
    splitText(aux.c_str(), inputFiles, ";|");
  }


  // Keep record of loaded files
  int filesLoaded = 0;

  cout  << "Loading " << inputFiles.size() << " files." << endl;

  for(int i = 0 ; i < inputFiles.size() ; i++) {
    SpecSet spec;
    if(loadSpecset(inputFiles[i], spec)) {
      inputData.push_back(spec);
      filesLoaded++;
    }
  }

  cout <<  filesLoaded << " files loaded." << endl;

  // exit if no file was loaded
  if(!filesLoaded) {
    cerr << "No file loaded." << endl;
    return 0;
  }


  ////////////////////////////////////////////////////////////////////////////////
  //  Processing section

  // check for zero PM

  cout << "Checking " << inputData.size() << " specsets." << endl;
  for(int i = 0 ; i < inputData.size() ; i++) {
    cout << "  #" << i << " Checking " << inputData[i].size() << " spectra." << endl;
    vector<int> aux;
    for(int j = 0 ; j < inputData[i].size() ; j++) {
      if(inputData[i][j].parentMass < 2.0) {
        aux.push_back(j);
        cout << "found: " << i << " ; " << j << " -> " << inputData[i][j].parentMass << endl;
      } //else
      //  cout << "value: " << i << " ; " << j << " -> " << inputData[i][j].parentMass << " - " << inputData[i][j].parentMZ << endl;
    }
    if(aux.size())
      invalid.insert(pair<int, vector<int> >(i, aux));
  }


  ////////////////////////////////////////////////////////////////////////////////
  //  output section

  map<int, vector<int> >::iterator it;
  for(it = invalid.begin() ; it != invalid.end() ; it++) {
    int fileIdx = it->first;
    string fn = inputFiles[fileIdx];

    cout << "------- " << fn << " -------" << endl;

    for(int i = 0 ; i > it->second.size() ; i++) {
      if(!i) cout << " ; ";
      cout << it->second[i];
    }
    cout << endl;
  }


   // return status ok
  return 0;
}
Beispiel #14
0
//
// MAIN
//
int main(int argc, const char *argv[]){
	
	//
	// Command line processor:
	//
	CLP clp("Fontaine","1.2.1",L("Copyright ⓒ 2014 by Edward H. Trager. All Rights Reserved. Released under GPL v. 2 or later."),"http://www.unifont.org","fontaine [option]... [font file]...\n");
	
	//
	// Set up command line switches:
	//
	
	clp.addSwitch("--json"            , "-J" , "Produce output report in JSON format. (default)");
	clp.addSwitch("--text"            , "-T" , "Produce output report in plain text format.");
	clp.addSwitch("--xhtml"           , "-H" , "Produce output report in XHTML format.");
	clp.addSwitch("--fxhtml"          , "-Y" , "Produce output report in FANCY XHTML format.");
	clp.addSwitch("--xml"             , "-X" , "Produce output report in XML format.");
	// ---
	clp.addSwitch("--show-conscript"  , "-C" , "Report fictional orthographies");
	clp.addSwitch("--hide-conscript"  , "-c" , "Don't report fictional orthographies (default)");
	clp.addSwitch("--show-full"       , "-F" , "Report orthographies for which the font provides full support");
	clp.addSwitch("--hide-full"       , "-f" , "Don't report orthographies for which the font provides full support");
	clp.addSwitch("--show-missing"    , "-M" , "Report which Unicode values are missing from fragmentary and partially-supported orthographies. (default)");
	clp.addSwitch("--hide-missing"    , "-m" , "Don't report which Unicode values are missing from fragmentary and partially-supported orthographies.");
	clp.addSwitch("--show-partial"    , "-P" , "Report orthographies for which the font provides only partial support");
	clp.addSwitch("--hide-partial"    , "-p" , "Don't report orthographies for which the font provides only partial support");
	clp.addSwitch("--show-fragmentary", "-R" , "Report orthographies for which the font provides only fragmentary support.");
	clp.addSwitch("--hide-fragmentary", "-r" , "Don't report orthographies for which the font provides only fragmentary support.");
	// ---
	clp.addSwitch("--version"         , "-v" , "Print version and exit");
	clp.addSwitch("--help"            , "-h" , "Print help and exit");
	
	//
	// Parse command line arguments:
	//
	if(clp.parse(argc,argv)){
	
		// No error, process the switches
		if(clp.hasSwitchSet("--help")){
			clp.printHelp();
			return 0;
		}
		if(clp.hasSwitchSet("--version")){
			
			clp.printCopyrightNotice();
			return 0;
			
		}
		
		////////////////////
		//
		// MAIN PROCESSING:
		//
		////////////////////
		
		//
		// These are the arguments left over after stripping off command line arguments:
		//
		std::vector<std::string> arguments = clp.getArguments();
		
		FontLibrary myLibrary;
		
		////////////////////////////////////////////////////////////
		//
		// The report object:
		//
		// Can only have one report, so we only instantiate the first
		// one ...
		//
		////////////////////////////////////////////////////////////
		
		MLR *mlr;
		unsigned int reportCount=0;
		
		if      (clp.hasSwitchSet("--text" ) ) mlr = new TEXTR();
		else if (clp.hasSwitchSet("--xhtml") ) mlr = new XHTMLR();
		else if (clp.hasSwitchSet("--fxhtml")) mlr = new FXHTMLR();
		else if (clp.hasSwitchSet("--xml"  ) ) mlr = new XMLR();
		else {
			//
			// Always maintain JSON as the last option
			// so that it will be the default option as well:
			//
			// if (clp.hasSwitchSet("--json" ) ) ...
			//
			mlr = new JSONR();
			
		}
		
		mlr->startRoot();
		mlr->startList("fonts");
		//
		// Read font disk files:
		//
		for(unsigned i=0;i<arguments.size();i++){
			
			//
			// instantiate a FontFace object using the font file name:
			//
			FontFace myFace(myLibrary,arguments[i].c_str());
			
			//
			// The options are currently set in the FontFace object --
			// -- this could change to a more elegant design in the future ...
			//
			if      (clp.hasSwitchSet("--show-missing")) myFace.setReportOnMissing(true);
			else if (clp.hasSwitchSet("--hide-missing")) myFace.setReportOnMissing(false);
			
			if      (clp.hasSwitchSet("--show-fragmentary")) myFace.setReportOnFragmentary(true);
			else if (clp.hasSwitchSet("--hide-fragmentary")) myFace.setReportOnFragmentary(false);
			
			if      (clp.hasSwitchSet("--show-partial")) myFace.setReportOnPartial(true);
			else if (clp.hasSwitchSet("--hide-partial")) myFace.setReportOnPartial(false);
			
			if      (clp.hasSwitchSet("--show-full")) myFace.setReportOnFull(true);
			else if (clp.hasSwitchSet("--hide-full")) myFace.setReportOnFull(false);
			
			if      (clp.hasSwitchSet("--show-conscript")) myFace.setReportOnConscript(true);
			else if (clp.hasSwitchSet("--hide-conscript")) myFace.setReportOnConscript(false);
			
			myFace.checkOrthographies();
			//
			// non-const method that calls methods 
			// on mlr to prepare the report:
			//
			myFace.fillReport(mlr);
			
		}
		
		mlr->endList("fonts");
		mlr->endRoot();
		
		//
		// Print the report:
		//
		std::cout << mlr->getReport();
		
		delete mlr;
	}
	
	return 0;
	
}
Beispiel #15
0
// Parse command line
clp_return_type parse_cmdline( int argc , char ** argv, CMD & cmdline,
                               const Teuchos::Comm<int>& comm,
                               const bool uq )
{
    Teuchos::ParameterList params;
    Teuchos::CommandLineProcessor clp(false);

    const int num_grouping_types = 4;
    const GroupingType grouping_values[] = {
        GROUPING_NATURAL, GROUPING_MAX_ANISOTROPY, GROUPING_MORTAN_Z,
        GROUPING_TASMANIAN_SURROGATE
    };
    const char *grouping_names[] = { "natural", "max-anisotropy", "mortan-z", "tasmanian-surrogate" };

    const int num_sampling_types = 3;
    const SamplingType sampling_values[] = {
        SAMPLING_STOKHOS, SAMPLING_TASMANIAN, SAMPLING_FILE
    };
    const char *sampling_names[] = { "stokhos", "tasmanian", "file" };

    clp.setOption("serial", "no-serial",     &cmdline.USE_SERIAL, "use the serial device");
    clp.setOption("threads",                 &cmdline.USE_THREADS, "number of pthreads threads");
    clp.setOption("openmp",                  &cmdline.USE_OPENMP,  "number of openmp threads");
    clp.setOption("numa",                    &cmdline.USE_NUMA,  "number of numa nodes");
    clp.setOption("cores",                   &cmdline.USE_CORE_PER_NUMA, "cores per numa node");
    clp.setOption("cuda", "no-cuda",         &cmdline.USE_CUDA,  "use the CUDA device");
    clp.setOption("device",                  &cmdline.USE_CUDA_DEV,  "CUDA device ID.  Set to default of -1 to use the default device as determined by the local node MPI rank and --ngpus");
    clp.setOption("ngpus",                   &cmdline.USE_NGPUS, "Number of GPUs per node for multi-GPU runs via MPI");
    std::string fixtureSpec="2x2x2";
    clp.setOption("fixture",                 &fixtureSpec,  "fixture string: \"XxYxZ\"");
    clp.setOption("fixture-x",               &cmdline.USE_FIXTURE_X,  "fixture");
    clp.setOption("fixture-y",               &cmdline.USE_FIXTURE_Y,  "fixture");
    clp.setOption("fixture-z",               &cmdline.USE_FIXTURE_Z,  "fixture");
    clp.setOption("fixture-quadratic", "no-fixture-quadratic", &cmdline.USE_FIXTURE_QUADRATIC,  "quadratic");

    clp.setOption("atomic", "no-atomic",      &cmdline.USE_ATOMIC ,  "atomic");
    clp.setOption("trials",                   &cmdline.USE_TRIALS,  "trials");
    clp.setOption("xml-file",                 &cmdline.USE_FENL_XML_FILE, "XML file containing solver parameters");
    clp.setOption("belos", "no-belos",        &cmdline.USE_BELOS ,  "use Belos solver");
    clp.setOption("muelu", "no-muelu",        &cmdline.USE_MUELU,  "use MueLu preconditioner");
    clp.setOption("mean-based", "no-mean-based", &cmdline.USE_MEANBASED,  "use mean-based preconditioner");
    if(cmdline.USE_MUELU || cmdline.USE_MEANBASED)
        cmdline.USE_BELOS = true;

    clp.setOption("sampling", &cmdline.USE_UQ_SAMPLING, num_sampling_types, sampling_values, sampling_names, "UQ sampling method");
    clp.setOption("uq-fake",                  &cmdline.USE_UQ_FAKE,  "setup a fake UQ problem of this size");
    clp.setOption("uq-dim",                   &cmdline.USE_UQ_DIM,  "UQ dimension");
    clp.setOption("uq-order",                 &cmdline.USE_UQ_ORDER,  "UQ order");
    clp.setOption("uq-init-level",            &cmdline.USE_UQ_INIT_LEVEL,  "Initial adaptive sparse grid level");
    clp.setOption("uq-max-level",             &cmdline.USE_UQ_MAX_LEVEL,  "Max adaptive sparse grid level");
    clp.setOption("uq-max-samples",           &cmdline.USE_UQ_MAX_SAMPLES,  "Max number of samples to run");
    clp.setOption("uq-tol",                   &cmdline.USE_UQ_TOL,  "Adaptive sparse grid tolerance");
    clp.setOption("diff-coeff-linear",        &cmdline.USE_DIFF_COEFF_LINEAR,  "Linear term in diffusion coefficient");
    clp.setOption("diff-coeff-constant",      &cmdline.USE_DIFF_COEFF_CONSTANT,  "Constant term in diffusion coefficient");
    clp.setOption("mean",                     &cmdline.USE_MEAN,  "KL diffusion mean");
    clp.setOption("var",                      &cmdline.USE_VAR,  "KL diffusion variance");
    clp.setOption("cor",                      &cmdline.USE_COR,  "KL diffusion correlation");
    clp.setOption("exponential", "no-exponential", &cmdline.USE_EXPONENTIAL,  "take exponential of KL diffusion coefficient");
    clp.setOption("exp-shift",                &cmdline.USE_EXP_SHIFT,  "Linear shift of exponential of KL diffusion coefficient");
    clp.setOption("exp-scale",                &cmdline.USE_EXP_SCALE,  "Multiplicative scale of exponential of KL diffusion coefficient");
    clp.setOption("discontinuous-exp-scale", "continuous-exp-scale", &cmdline.USE_DISC_EXP_SCALE,  "use discontinuous scale factor on exponential");
    clp.setOption("isotropic", "anisotropic", &cmdline.USE_ISOTROPIC,  "use isotropic or anisotropic diffusion coefficient");
    clp.setOption("coeff-src",                &cmdline.USE_COEFF_SRC,  "Coefficient for source term");
    clp.setOption("coeff-adv",                &cmdline.USE_COEFF_ADV,  "Coefficient for advection term");
    clp.setOption("sparse", "tensor",         &cmdline.USE_SPARSE ,  "use sparse or tensor grid");
    clp.setOption("ensemble",                 &cmdline.USE_UQ_ENSEMBLE,  "UQ ensemble size.  This needs to be a valid choice based on available instantiations.");
    clp.setOption("grouping", &cmdline.USE_GROUPING, num_grouping_types, grouping_values, grouping_names, "Sample grouping method for ensemble propagation");
    clp.setOption("surrogate-grouping-level", &cmdline.TAS_GROUPING_INITIAL_LEVEL,  "Starting level for surrogate-based grouping");

    clp.setOption("vtune", "no-vtune",       &cmdline.VTUNE ,  "connect to vtune");
    clp.setOption("verbose", "no-verbose",   &cmdline.VERBOSE, "print verbose intialization info");
    clp.setOption("print", "no-print",        &cmdline.PRINT,  "print detailed test output");
    clp.setOption("print-its", "no-print-its",&cmdline.PRINT_ITS,  "print solver iterations after each sample");
    clp.setOption("summarize", "no-summarize",&cmdline.SUMMARIZE,  "summarize Teuchos timers at end of run");

    bool doDryRun = false;
    clp.setOption("echo", "no-echo",          &doDryRun,  "dry-run only");

    switch (clp.parse(argc, argv)) {
    case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
        return CLP_HELP;
    case Teuchos::CommandLineProcessor::PARSE_ERROR:
    case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
        return CLP_ERROR;
    case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
        break;
    }

#if defined( KOKKOS_HAVE_CUDA )
    // Set CUDA device based on local node rank
    if (cmdline.USE_CUDA && cmdline.USE_CUDA_DEV == -1) {
        int local_rank = 0;
        char *str;
        if ((str = std::getenv("MV2_COMM_WORLD_LOCAL_RANK")))
            local_rank = std::atoi(str);
        else if ((str = getenv("OMPI_COMM_WORLD_LOCAL_RANK")))
            local_rank = std::atoi(str);
        else if ((str = std::getenv("SLURM_LOCALID")))
            local_rank = std::atoi(str);
        cmdline.USE_CUDA_DEV = local_rank % cmdline.USE_NGPUS;

        // Check device is valid
        int num_device;
        cudaGetDeviceCount(&num_device);
        TEUCHOS_TEST_FOR_EXCEPTION(
            cmdline.USE_CUDA_DEV >= cmdline.USE_NGPUS, std::logic_error,
            "Invalid device ID " << cmdline.USE_CUDA_DEV << ".  You probably are trying" <<
            " to run with too many GPUs per node");
    }
#endif

    sscanf( fixtureSpec.c_str() , "%dx%dx%d" ,
            &cmdline.USE_FIXTURE_X ,
            &cmdline.USE_FIXTURE_Y ,
            &cmdline.USE_FIXTURE_Z );

    cmdline.USE_UQ = uq;

    if (doDryRun) {
        print_cmdline( std::cout , cmdline );
        cmdline.ECHO  = 1;
    } else {
        cmdline.ECHO  = 0;
    }
    cmdline.ERROR  = 0 ;

    return CLP_OK;

}
Beispiel #16
0
int main(int argc, char *argv[]) {
#include "MueLu_UseShortNames.hpp"

  Teuchos::oblackholestream blackhole;
  Teuchos::GlobalMPISession mpiSession(&argc,&argv,&blackhole);

  bool success = true;
  bool verbose = true;
  try {
    Teuchos::RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();

    /**********************************************************************************/
    /* SET TEST PARAMETERS                                                            */
    /**********************************************************************************/
    // Note: use --help to list available options.
    Teuchos::CommandLineProcessor clp(false);

    // Default is Laplace1D with nx = 8748.
    // It's a nice size for 1D and perfect aggregation. (6561=3^8)
    //Nice size for 1D and perfect aggregation on small numbers of processors. (8748=4*3^7)
    Galeri::Xpetra::Parameters<GO> matrixParameters(clp, 8748); // manage parameters of the test case
    Xpetra::Parameters xpetraParameters(clp);             // manage parameters of xpetra

    // custom parameters
    int pauseForDebugger=0;
    //std::string aggOrdering = "natural";
    int minPerAgg=2; //was 3 in simple
    int maxNbrAlreadySelected=0;
    int printTimings=0;
    std::string xmlFile="parameters.xml";

    //clp.setOption("aggOrdering",&aggOrdering,"aggregation ordering strategy (natural,graph)");
    clp.setOption("debug",&pauseForDebugger,"pause to attach debugger");
    clp.setOption("maxNbrSel",&maxNbrAlreadySelected,"maximum # of nbrs allowed to be in other aggregates");
    clp.setOption("minPerAgg",&minPerAgg,"minimum #DOFs per aggregate");
    clp.setOption("timings",&printTimings,"print timings to screen");
    clp.setOption("xmlFile",&xmlFile,"file name containing MueLu multigrid parameters in XML format");

    switch (clp.parse(argc,argv)) {
      case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:        return EXIT_SUCCESS; break;
      case Teuchos::CommandLineProcessor::PARSE_ERROR:
      case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE; break;
      case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:                               break;
    }

    Teuchos::RCP<Teuchos::TimeMonitor> globalTimeMonitor = Teuchos::rcp (new Teuchos::TimeMonitor(*Teuchos::TimeMonitor::getNewTimer("Timings: Global Time")));

    if (pauseForDebugger) {
      Utilities::PauseForDebugger();
    }

    matrixParameters.check();
    xpetraParameters.check();
    Xpetra::UnderlyingLib lib = xpetraParameters.GetLib();

    if (comm->getRank() == 0) {
      std::cout << xpetraParameters << matrixParameters;
    }

    /**********************************************************************************/
    /* CREATE INITIAL MATRIX                                                          */
    /**********************************************************************************/
    Teuchos::RCP<const Map> map;
    Teuchos::RCP<Matrix> A;

    {
      Teuchos::TimeMonitor tm(*Teuchos::TimeMonitor::getNewTimer("Timings: Matrix Build"));

      map = MapFactory::Build(lib, matrixParameters.GetNumGlobalElements(), 0, comm);
      Teuchos::RCP<Galeri::Xpetra::Problem<Map,CrsMatrixWrap,MultiVector> > Pr =
        Galeri::Xpetra::BuildProblem<SC,LO,GO,Map,CrsMatrixWrap,MultiVector>(matrixParameters.GetMatrixType(), map, matrixParameters.GetParameterList()); //TODO: Matrix vs. CrsMatrixWrap
      A = Pr->BuildMatrix();

    }
    /**********************************************************************************/
    /*                                                                                */
    /**********************************************************************************/
    Teuchos::ParameterList paramList;
    Teuchos::updateParametersFromXmlFileAndBroadcast(xmlFile, Teuchos::Ptr<Teuchos::ParameterList>(&paramList), *comm);

    // create parameter list interpreter
    Teuchos::RCP<HierarchyManager> mueluFactory = Teuchos::rcp(new ParameterListInterpreter(paramList));

    Teuchos::RCP<Hierarchy> H = mueluFactory->CreateHierarchy();

    H->GetLevel(0)->Set< Teuchos::RCP<Matrix> >("A", A);

    Teuchos::RCP<MultiVector> nullspace = MultiVectorFactory::Build(A->getRowMap(), 1);
    nullspace->putScalar(1.0);
    H->GetLevel(0)->Set("Nullspace", nullspace);

    // set minimal information about number of layers for semicoarsening...
    // This information can also be provided as a user parameter in the xml file using the
    // parameter: "semicoarsen: num layers"
    H->GetLevel(0)->Set("NumZLayers",matrixParameters.GetParameterList().get<GO>("nz"));


    mueluFactory->SetupHierarchy(*H);

    for (int l=0; l<H->GetNumLevels(); l++) {
      Teuchos::RCP<MueLu::Level> level = H->GetLevel(l);
      if(level->IsAvailable("A", MueLu::NoFactory::get()) == false) { success = false; H->GetLevel(l)->print(std::cout, MueLu::Debug);}
      if(level->IsAvailable("P", MueLu::NoFactory::get()) == false && l>0) { success = false; H->GetLevel(l)->print(std::cout, MueLu::Debug);}
      if(level->IsAvailable("R", MueLu::NoFactory::get()) == false && l>0) { success = false; H->GetLevel(l)->print(std::cout, MueLu::Debug);}
      if(level->IsAvailable("PreSmoother",  MueLu::NoFactory::get()) == false) { success = false; H->GetLevel(l)->print(std::cout, MueLu::Debug);}
      if(level->IsAvailable("PostSmoother", MueLu::NoFactory::get()) == false && l<H->GetNumLevels()-1) { success = false; H->GetLevel(l)->print(std::cout, MueLu::Debug);}
      if(level->IsAvailable("NumZLayers",   MueLu::NoFactory::get()) == true && l>0) {  success = false; H->GetLevel(l)->print(std::cout, MueLu::Debug);}
      H->GetLevel(l)->print(std::cout, MueLu::Debug);
    }
    ///////////////////////////////////////////////////////////

    // =========================================================================
    // System solution (Ax = b)
    // =========================================================================
    comm->barrier();
    typedef Teuchos::ScalarTraits<SC> STS;
    SC zero = STS::zero(), one = STS::one();

    Teuchos::RCP<Vector> X = VectorFactory::Build(A->getRowMap());
    Teuchos::RCP<Vector> B = VectorFactory::Build(A->getRowMap());

    {
      // we set seed for reproducibility
      Utilities::SetRandomSeed(*comm);
      X->randomize();
      A->apply(*X, *B, Teuchos::NO_TRANS, one, zero);

      Teuchos::Array<STS::magnitudeType> norms(1);
      B->norm2(norms);
      B->scale(one/norms[0]);
      X->putScalar(zero);
    }

    comm->barrier();

    H->IsPreconditioner(false);
    H->Iterate(*B, *X, 20);

    // Timer final summaries
    globalTimeMonitor = Teuchos::null; // stop this timer before summary

    if (printTimings)
      Teuchos::TimeMonitor::summarize();
  }
  TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);

  return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
Beispiel #17
0
void SundanceGlobal::setOption(const std::string& optionName,
  std::string& value,
  const std::string& helpMsg)
{
  clp().setOption(optionName.c_str(), &value, helpMsg.c_str());
}
Beispiel #18
0
int main(int argc, char *argv[])
{
    ofstream log; // to record log file
    log.open("log.txt", std::fstream::app);
    int i = 0;
    int n;
    CommandLineParser clp(argv[1],',');   //instantiating the class CommandLineParser
    string line; // store each line in script file
    string listID = "";
    WordList L1; // list class

    if (argc == 1) 
    {
        log << "Error: no argument is passed." << endl;
        log.close();
        return -1;
    }

    //use CommandLineParser to get the script name
    char *script = clp.extract("script");
    if (script == NULL)
    {
        log << "Error: no script file specified." << endl;
        log.close();
        return -1;
    }

    //use ScriptParser to get the commands from script file
    ScriptParser SParser =  ScriptParser();
    ifstream indata(script);
    if (!indata.is_open()) // check if script file is correctly opened.
    {
        log << "Error: Script file \'" << script << "\' cannot be opened or does not exist." << endl;
        log.close();
        return -1;
    }
    
    log << "Begin parsing:\n" << endl;
    while(getline(indata, line))
    {
        log << line << '\n';
        SParser.ParseLine(line);

// we need to use "map" container to map different 'listID' to corresponding 'list', here, we suppose only one list will be used (the first created one), the other 'listID' which are different from the first one will be invalid.

/*        if (SParser.operationCode() == 3 && i == 0) // this is the first time create listID
        { 
            listID = SParser.cmd.listID;
        }
        else if (listID == "") // this is the time when list is not created yet
        {
            log << "Error: invalid operation, because list \'" << SParser.cmd.listID << "\' is not created yet, program is terminated.\n\n" << "End of parsing.\n" << endl;
            return -1;
        }
        else if (listID != SParser.cmd.listID) // if we want to create or visit more list other than the first, omit this operation
        {
            log << "Error: only one list \'" << listID << "\' is permitted, \'" << SParser.cmd.listID << "\' is not or cannot be created, program is terminated.\n\n" << "End of parsing.\n" <<endl;
            return -1;
        } */

        // do all the list operations, such as read, insert, delete, write.
        switch (SParser.operationCode())
        {
        case 1:
            n = L1.insert(SParser.cmd.value2, SParser.cmd.value1);
            if (n == -1) { 
                log << "Warning: in insertion, " << '\'' << SParser.cmd.value1 << '\'' << " cannot be found, so insertion fails.\n";
            }
            else {
                log << '\'' << SParser.cmd.value2 << '\'' << " has been inserted after the first appeared word " << '\'' << SParser.cmd.value1 << "\'.\n";
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 2:
            n = L1.erase(SParser.cmd.value1);
	    if (n == 0) log << "Waring: ";
            log << n << " word(s) " << '\'' << SParser.cmd.value1 << '\'' << " have been deleted.\n";
            log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 3:
            ++i;
            n = L1.read(SParser.cmd.value1);
            if (n == 0) {
                log << "Input file \'" << SParser.cmd.value1 << "\' is successfully read into list.\n";
            }
            else {
                log << "Error: fail to open input file \'" << SParser.cmd.value1 << "\', program is terminated.\n" << endl;
		log << "End of parsing.\n" << endl;
		return -1;
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 4:
            n = L1.output_forward(SParser.cmd.value1);
            if (n == 0) {
                log << "List is successfully written to file " << '\'' << SParser.cmd.value1 << '\'' << " in forward order.\n";
            }
            else {
                log << "Error: fail to create output file " << SParser.cmd.value1 << ".\n";
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 5:
            n = L1.output_backward(SParser.cmd.value1);
            if (n == 0) {
                log << "List is successfully written to file " << '\'' << SParser.cmd.value1 << '\'' << " in reverse order.\n";
            }
            else {
                log << "Error: fail to create output file " << SParser.cmd.value1 << ".\n";
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 0:
            cout << SParser.cmd.listID << endl;
            cout << "Error: above line is not a valid script form.\n" << endl;
            log << "Error: above line is not a valid script form.\n" << endl;
            break;
        } 
    }
  
  log << "End of parsing.\n" <<endl;
  log.close();
  return 0;
}
int main(int argc, char* argv[]) {
    bool success = true;
    try {

        // Set up command line options
        Teuchos::CommandLineProcessor clp(false);
        clp.setDocString("This program tests the speed of various forward mode AD implementations for simple Kokkos kernel");
        int m = 100000;
        clp.setOption("m", &m, "Number of matrix rows");
        int n = 100;
        clp.setOption("n", &n, "Number of matrix columns");
        int p = SFadSize;
        clp.setOption("p", &p, "Number of derivative components");
        int nloop = 10;
        clp.setOption("nloop", &nloop, "Number of loops");
#ifdef KOKKOS_HAVE_SERIAL
        bool serial = 0;
        clp.setOption("serial", "no-serial", &serial, "Whether to run Serial");
#endif
#ifdef KOKKOS_HAVE_OPENMP
        int openmp = 0;
        clp.setOption("openmp", &openmp, "Number of OpenMP threads");
#endif
#ifdef KOKKOS_HAVE_PTHREAD
        int threads = 0;
        clp.setOption("threads", &threads, "Number of pThreads threads");
#endif
#ifdef KOKKOS_HAVE_CUDA
        bool cuda = 0;
        clp.setOption("cuda", "no-cuda", &cuda, "Whether to run CUDA");
#endif
        int numa = 0;
        clp.setOption("numa", &numa,
                      "Number of NUMA domains to use (set to 0 to use all NUMAs");
        int cores_per_numa = 0;
        clp.setOption("cores-per-numa", &cores_per_numa,
                      "Number of CPU cores per NUMA to use (set to 0 to use all cores)");
        bool print_config = false;
        clp.setOption("print-config", "no-print-config", &print_config,
                      "Whether to print Kokkos device configuration");
        LayoutType layout = LAYOUT_DEFAULT;
        clp.setOption("layout", &layout, num_layout_types, layout_values,
                      layout_names, "View layout");
        bool vtune = false;
        clp.setOption("vtune", "no-vtune", &vtune, "Profile with vtune");
        bool value = true;
        clp.setOption("value", "no-value", &value, "Run value calculation");
        bool analytic = true;
        clp.setOption("analytic", "no-analytic", &analytic,
                      "Run analytic derivative calculation");
        bool sfad = true;
        clp.setOption("sfad", "no-sfad", &sfad, "Run SFad derivative calculation");
        bool slfad = true;
        clp.setOption("slfad", "no-slfad", &slfad, "Run SLFad derivative calculation");
        bool dfad = true;
        clp.setOption("dfad", "no-dfad", &dfad, "Run DFad derivative calculation");
        bool check = false;
        clp.setOption("check", "no-check", &check, "Check calculations are correct");

        // Parse options
        switch (clp.parse(argc, argv)) {
        case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
            return 0;
        case Teuchos::CommandLineProcessor::PARSE_ERROR:
        case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
            return 1;
        case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
            break;
        }

        if (vtune)
            connect_vtune();

#ifdef KOKKOS_HAVE_SERIAL
        if (serial) {
            Kokkos::Serial::initialize();
            if (print_config)
                Kokkos::Serial::print_configuration(std::cout, true);
            do_times_layout<SFadSize,SLFadSize,Kokkos::Serial>(
                m,n,p,nloop,value,analytic,sfad,slfad,dfad,check,layout,"Serial");
            Kokkos::Serial::finalize();
        }
#endif

#ifdef KOKKOS_HAVE_OPENMP
        if (openmp) {
            Kokkos::OpenMP::initialize(openmp, numa, cores_per_numa);
            if (print_config)
                Kokkos::OpenMP::print_configuration(std::cout, true);
            do_times_layout<SFadSize,SLFadSize,Kokkos::OpenMP>(
                m,n,p,nloop,value,analytic,sfad,slfad,dfad,check,layout,"OpenMP");
            Kokkos::OpenMP::finalize();
        }
#endif

#ifdef KOKKOS_HAVE_PTHREAD
        if (threads) {
            Kokkos::Threads::initialize(threads, numa, cores_per_numa);
            if (print_config)
                Kokkos::Threads::print_configuration(std::cout, true);
            do_times_layout<SFadSize,SLFadSize,Kokkos::Threads>(
                m,n,p,nloop,value,analytic,sfad,slfad,dfad,check,layout,"Threads");
            Kokkos::Threads::finalize();
        }
#endif

#ifdef KOKKOS_HAVE_CUDA
        if (cuda) {
            Kokkos::HostSpace::execution_space::initialize();
            Kokkos::Cuda::initialize();
            if (print_config)
                Kokkos::Cuda::print_configuration(std::cout, true);
            do_times_layout<SFadSize,SLFadSize,Kokkos::Cuda>(
                m,n,p,nloop,value,analytic,sfad,slfad,dfad,check,layout,"Cuda");
            Kokkos::HostSpace::execution_space::finalize();
            Kokkos::Cuda::finalize();
        }
#endif

    }
    TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success);

    return !success;
}
int main(int argc, char *argv[]) {
#include "MueLu_UseShortNames.hpp"

  Teuchos::oblackholestream blackhole;
  Teuchos::GlobalMPISession mpiSession(&argc,&argv,&blackhole);

  bool success = false;
  bool verbose = true;
  try {
    Teuchos::RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();

    /**********************************************************************************/
    /* SET TEST PARAMETERS                                                            */
    /**********************************************************************************/
    /**********************************************************************************/
    /* SET TEST PARAMETERS                                                            */
    /**********************************************************************************/
    // Note: use --help to list available options.
    Teuchos::CommandLineProcessor clp(false);

    // Default is Laplace1D with nx = 8748.
    // It's a nice size for 1D and perfect aggregation. (6561=3^8)
    //Nice size for 1D and perfect aggregation on small numbers of processors. (8748=4*3^7)
    Galeri::Xpetra::Parameters<GO> matrixParameters(clp, 8748); // manage parameters of the test case
    Xpetra::Parameters xpetraParameters(clp);             // manage parameters of xpetra

    // custom parameters
    int pauseForDebugger=0;
    //std::string aggOrdering = "natural";
    int minPerAgg=2; //was 3 in simple
    int maxNbrAlreadySelected=0;
    int printTimings=0;

    //clp.setOption("aggOrdering",&aggOrdering,"aggregation ordering strategy (natural,graph)");
    clp.setOption("debug",&pauseForDebugger,"pause to attach debugger");
    clp.setOption("maxNbrSel",&maxNbrAlreadySelected,"maximum # of nbrs allowed to be in other aggregates");
    clp.setOption("minPerAgg",&minPerAgg,"minimum #DOFs per aggregate");
    clp.setOption("timings",&printTimings,"print timings to screen");

    switch (clp.parse(argc,argv)) {
      case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:        return EXIT_SUCCESS; break;
      case Teuchos::CommandLineProcessor::PARSE_ERROR:
      case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE; break;
      case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:                               break;
    }

    Teuchos::RCP<Teuchos::TimeMonitor> globalTimeMonitor = Teuchos::rcp (new Teuchos::TimeMonitor(*Teuchos::TimeMonitor::getNewTimer("Timings: Global Time")));

    if (pauseForDebugger) {
      Utilities::PauseForDebugger();
    }

    matrixParameters.check();
    xpetraParameters.check();
    Xpetra::UnderlyingLib lib = xpetraParameters.GetLib();

    if (comm->getRank() == 0) {
      std::cout << xpetraParameters << matrixParameters;
    }

    /**********************************************************************************/
    /* CREATE INITIAL MATRIX                                                          */
    /**********************************************************************************/
    Teuchos::RCP<const Map> map;
    Teuchos::RCP<Matrix> A;

    {
      Teuchos::TimeMonitor tm(*Teuchos::TimeMonitor::getNewTimer("Timings: Matrix Build"));

      map = MapFactory::Build(lib, matrixParameters.GetNumGlobalElements(), 0, comm);
      Teuchos::RCP<Galeri::Xpetra::Problem<Map,CrsMatrixWrap,MultiVector> > Pr =
        Galeri::Xpetra::BuildProblem<SC,LO,GO,Map,CrsMatrixWrap,MultiVector>(matrixParameters.GetMatrixType(), map, matrixParameters.GetParameterList()); //TODO: Matrix vs. CrsMatrixWrap
      A = Pr->BuildMatrix();

    }
    /**********************************************************************************/
    /*                                                                                */
    /**********************************************************************************/


    Teuchos::RCP<Hierarchy> hierarchy = Teuchos::rcp(new Hierarchy(A));
    hierarchy->SetDefaultVerbLevel(MueLu::toMueLuVerbLevel(Teuchos::VERB_EXTREME));
    hierarchy->SetMaxCoarseSize(100);

    ///////////////////////////////////////////////////////////

    Teuchos::RCP<MueLu::Level> Finest = hierarchy->GetLevel();  // get finest level

    Finest->Set("A",A);

    Teuchos::RCP<AmalgamationFactory> amalgFact = Teuchos::rcp(new AmalgamationFactory());
    Teuchos::RCP<CoalesceDropFactory> dropFact = Teuchos::rcp(new CoalesceDropFactory());
    dropFact->SetFactory("UnAmalgamationInfo", amalgFact);

    // aggregation factory
    Teuchos::RCP<UncoupledAggregationFactory> UnCoupledAggFact = Teuchos::rcp(new UncoupledAggregationFactory(/*dropFact*/));
    UnCoupledAggFact->SetFactory("Graph", dropFact);
    UnCoupledAggFact->SetFactory("DofsPerNode", dropFact);
    //UnCoupledAggFact->SetFactory("Graph", dropFact); // UnCoupledAggFact not changed to new factory handling
    //UnCoupledAggFact->SetMinNodesPerAggregate(minPerAgg);
    //UnCoupledAggFact->SetMaxNeighAlreadySelected(maxNbrAlreadySelected);
    //UnCoupledAggFact->SetOrdering(MueLu::AggOptions::GRAPH);
    UnCoupledAggFact->SetParameter("aggregation: max selected neighbors", Teuchos::ParameterEntry(maxNbrAlreadySelected));
    UnCoupledAggFact->SetParameter("aggregation: min agg size",           Teuchos::ParameterEntry(minPerAgg));
    UnCoupledAggFact->SetParameter("aggregation: ordering",               Teuchos::ParameterEntry(std::string("graph")));

    Finest->Request("Graph",dropFact.get());
    Finest->Request("DofsPerNode",dropFact.get());
    Finest->Request("UnAmalgamationInfo",amalgFact.get());
    UnCoupledAggFact->Build(*Finest);

    // Timer final summaries
    globalTimeMonitor = Teuchos::null; // stop this timer before summary

    if (printTimings)
      Teuchos::TimeMonitor::summarize();

    success = true;
  }
  TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);

  return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
int main(int argc, char** argv) {

  int rc=0, fail = 0;
#ifdef HAVE_EPETRAEXT
  bool verbose = false;
  int localProc = 0;
//   std::string *fstr;

#ifdef HAVE_MPI
  int numProcs;
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &localProc);
  MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
  const Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
  const Epetra_SerialComm Comm;
#endif

  Teuchos::CommandLineProcessor clp(false,true);

  // --f=fileName provides a different matrix market file for input
  // --v will print out the partitioning (small files only)

  std::string *inputFile = new std::string("simple.mtx");
  bool runAll = false;

  clp.setOption( "f", inputFile,
		"Name of input matrix market file");
  clp.setOption( "run-all", "abort", &runAll,
		"Don't abort if one test fails, run all of them.");
  clp.setOption( "v", "q", &verbose,
		"Display matrix before and after partitioning.");

  Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return =
    clp.parse(argc,argv);

  if( parse_return == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED){
#ifdef HAVE_MPI
    MPI_Finalize();
#endif
    return 0;
  }
  if( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {
#ifdef HAVE_MPI
    MPI_Finalize();
#endif
    return 1;
  }

  const char *fname = inputFile->c_str();

  // Read in the matrix market file and distribute its rows across the
  // processes.
  //
  // This reader uses the default Epetra_Map for number of rows for the
  // RowMap() and for the RangeMap().  For non-square matrices it uses
  // the default Epetra_Map for the number of columns for the DomainMap(),
  // otherwise it uses the RowMap().
  //
  // The maps can be specified with other versions of MMFtoCrsMatrix().


  Epetra_CrsMatrix *matrixPtr;
  rc = EpetraExt::MatrixMarketFileToCrsMatrix(fname, Comm, matrixPtr);
  if (rc < 0){
    if (localProc==0){
      std::cout << "error reading input file" << std::endl << "FAIL" << std::endl;
    }
    exit(1);
  }

  bool square = (matrixPtr->NumGlobalRows() == matrixPtr->NumGlobalCols());
  // If matrix is square, determine if it's symmetric  TODO


  // Run some partitioning tests
  //   Test graph and hypergraph partitioning
  //   Test with and without application supplied weights
  //   Test the Epetra_CrsMatrix interface and also the Epetra_CrsGraph interface
  //   Do tests where the vertex or edge weights vary widely

  Teuchos::RCP<Epetra_CrsMatrix> testm = Teuchos::rcp(matrixPtr);
  int failures = 0;

#ifdef SHORT_TEST
  fail = run_test(testm,
	     verbose,
	     false,                 // do not test #partitions < #processes
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     EPETRA_CRSGRAPH);

  CHECK_FAILED();
  goto Report;

#else

  if (square){
#ifdef HAVE_ISORROPIA_ZOLTAN
    fail = run_test(testm,            // test matrix
	       verbose,               // display matrix before and after?
	       false,                 // do not test #partitions < #processes
	       GRAPH_PARTITIONING,    // perform zoltan graph partitioning
	       NO_APPLICATION_SUPPLIED_WEIGHTS,
	       NO_APPLICATION_SUPPLIED_WEIGHTS,
	       EPETRA_LINEARPROBLEM); // use linear problem interface of isorropia

    CHECK_FAILED();

    fail = run_test(testm,
	       verbose,            // draw graph before and after partitioning?
	       false,                 // do not test #partitions < #processes
	       HYPERGRAPH_PARTITIONING,      // do graph partitioning
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	       EPETRA_CRSMATRIX);       // use the Epetra_CrsMatrix interface

    CHECK_FAILED();

    fail = run_test(testm,
	       verbose,
	       true,                 // test #partitions < #processes
	       GRAPH_PARTITIONING,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	       EPETRA_CRSMATRIX);

    CHECK_FAILED();

    fail = run_test(testm,
	       verbose,
	       false,                 // do not test #partitions < #processes
	       GRAPH_PARTITIONING,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	       EPETRA_LINEARPROBLEM);

    CHECK_FAILED();

    fail = run_test(testm,
	       verbose,
	       false,                 // do not test #partitions < #processes
	       GRAPH_PARTITIONING,
	       NO_APPLICATION_SUPPLIED_WEIGHTS,
	       NO_APPLICATION_SUPPLIED_WEIGHTS,
	       EPETRA_ROWMATRIX);

    CHECK_FAILED();
#else
  fail = 0;
  if (localProc == 0){
    std::cout << "Test not run because it requires EPETRA_EXT" << std::endl;
  }
#endif



#ifdef HAVE_ISORROPIA_ZOLTAN

  fail = run_test(testm,
	     verbose,
	     true,                 // test #partitions < #processes
	     HYPERGRAPH_PARTITIONING,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     EPETRA_CRSGRAPH);

   CHECK_FAILED();

  fail = run_test(testm,
	     verbose,
	     false,                 // do not test #partitions < #processes
	     HYPERGRAPH_PARTITIONING,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     EPETRA_ROWMATRIX);

   CHECK_FAILED();

  fail = run_test(testm,
	     verbose,
	     false,                 // do not test #partitions < #processes
	     HYPERGRAPH_PARTITIONING,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     NO_APPLICATION_SUPPLIED_WEIGHTS,
	     EPETRA_LINEARPROBLEM);

   CHECK_FAILED();

#endif
  }
#endif // SHORT_TEST

#else
  fail = 0;
  if (localProc == 0){
    std::cout << "Test not run because it requires EPETRA_EXT" << std::endl;
  }
#endif

Report:

#ifdef HAVE_MPI
  MPI_Finalize();
#endif

  if (localProc == 0){
    if (failures){
      if (failures > 1)
	std::cout << std::endl << failures << " FAILURES" << std::endl;
      else
	std::cout << std::endl << "1 FAILURE" << std::endl;

      if (!runAll){
	std::cout <<
       "(Use option --run-all if you do not want this test to abort on failure)" << std::endl;
      }
    }
    else
      std::cout << std::endl << "PASS" << std::endl;
  }

  return fail;
}
Beispiel #22
0
int main(int argc, char *argv[]) {
#include "MueLu_UseShortNames.hpp"

  Teuchos::oblackholestream blackhole;
  Teuchos::GlobalMPISession mpiSession(&argc,&argv,&blackhole);
  RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();

  /**********************************************************************************/
  /* SET TEST PARAMETERS                                                            */
  /**********************************************************************************/
  // Note: use --help to list available options.
  Teuchos::CommandLineProcessor clp(false);

  // Default is Laplace1D with nx = 8748.
  // It's a nice size for 1D and perfect aggregation. (6561=3^8)
  //Nice size for 1D and perfect aggregation on small numbers of processors. (8748=4*3^7)
  Galeri::Xpetra::Parameters<GO> matrixParameters(clp, 8748); // manage parameters of the test case
  Xpetra::Parameters xpetraParameters(clp);             // manage parameters of xpetra

  // custom parameters
  LO maxLevels = 1;
  LO its=2;
  std::string coarseSolver="amesos2";
  clp.setOption("maxLevels",&maxLevels,"maximum number of levels allowed");
  clp.setOption("its",&its,"number of multigrid cycles");
  clp.setOption("coarseSolver",&coarseSolver,"amesos2 or ifpack2 (Tpetra specific. Ignored for Epetra)");

  switch (clp.parse(argc,argv)) {
  case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:        return EXIT_SUCCESS; break;
  case Teuchos::CommandLineProcessor::PARSE_ERROR:
  case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE; break;
  case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:                               break;
  }

  matrixParameters.check();
  xpetraParameters.check();
  // TODO: check custom parameters

  if (comm->getRank() == 0) {
    matrixParameters.print();
    xpetraParameters.print();
    // TODO: print custom parameters
  }


#ifdef FOR_PARALLEL_DEBUGGING
  //Utils::BreakForDebugger(*comm);

  LO mypid = comm->getRank();

  if (mypid  == 0) std::cout << "Host and Process Ids for tasks" << std::endl;
  for (LO i = 0; i <comm->getSize(); i++) {
    if (i == mypid ) {
      char buf[80];
      char hostname[80];
      gethostname(hostname, sizeof(hostname));
      LO pid = getpid();
      sprintf(buf, "Host: %s\tMPI rank: %d,\tPID: %d\n\tattach %d\n\tcontinue\n",
              hostname, mypid, pid, pid);
      printf("%s\n",buf);
      fflush(stdout);
      sleep(1);
    }
  }

  if (mypid == 0) {
    printf( "** Enter a character to continue > "); fflush(stdout);
    char go = ' ';
    scanf("%c",&go);
  }
  comm->barrier();
#endif

  /**********************************************************************************/
  /* CREATE INITIAL MATRIX                                                          */
  /**********************************************************************************/
  const RCP<const Map> map = MapFactory::Build(xpetraParameters.GetLib(), matrixParameters.GetNumGlobalElements(), 0, comm);
  RCP<Galeri::Xpetra::Problem<Map,CrsMatrixWrap,MultiVector> > Pr =
      Galeri::Xpetra::BuildProblem<SC, LO, GO, Map, CrsMatrixWrap, MultiVector>(matrixParameters.GetMatrixType(), map, matrixParameters.GetParameterList()); //TODO: Matrix vs. CrsMatrixWrap
  RCP<Matrix> Op = Pr->BuildMatrix();
  /**********************************************************************************/
  /*                                                                                */
  /**********************************************************************************/

  // dump matrix to file
  //std::string fileName = "Amat.mm";
  //Utils::Write(fileName,Op);

  RCP<MultiVector> nullSpace = MultiVectorFactory::Build(map,1);
  nullSpace->putScalar( (SC) 1.0);
  Teuchos::Array<Teuchos::ScalarTraits<SC>::magnitudeType> norms(1);
  nullSpace->norm1(norms);
  if (comm->getRank() == 0)
    std::cout << "||NS|| = " << norms[0] << std::endl;

  RCP<MueLu::Hierarchy<SC,LO,GO,NO,LMO> > H = rcp( new Hierarchy() );
  H->setDefaultVerbLevel(Teuchos::VERB_HIGH);
  RCP<MueLu::Level> Finest = rcp( new MueLu::Level() );
  Finest->setDefaultVerbLevel(Teuchos::VERB_HIGH);

  Finest->Set("A",Op);
  Finest->Set("Nullspace",nullSpace);
  Finest->Request("Nullspace"); //FIXME putting this in to avoid error until Merge needs business
                                //FIXME is implemented

  Finest->Set("NullSpace",nullSpace);
  H->SetLevel(Finest);

  RCP<CoupledAggregationFactory> CoupledAggFact = rcp(new CoupledAggregationFactory());
  CoupledAggFact->SetMinNodesPerAggregate(3);
  CoupledAggFact->SetMaxNeighAlreadySelected(0);
  CoupledAggFact->SetOrdering("natural");
  CoupledAggFact->SetPhase3AggCreation(0.5);

  RCP<TentativePFactory> TentPFact = rcp(new TentativePFactory(CoupledAggFact));

  RCP<SaPFactory>       Pfact = rcp( new SaPFactory(TentPFact) );
  //Pfact->SetDampingFactor(0.);
  RCP<Factory>         Rfact = rcp( new TransPFactory() );
  RCP<GenericPRFactory> PRfact = rcp( new GenericPRFactory(Pfact,Rfact));
  RCP<RAPFactory>       Acfact = rcp( new RAPFactory() );

  RCP<SmootherPrototype> smooProto;
  Teuchos::ParameterList ifpackList;
  ifpackList.set("relaxation: sweeps", (LO) 1);
  ifpackList.set("relaxation: damping factor", (SC) 1.0);
  /*
  ifpackList.set("type", "Chebyshev");
  ifpackList.set("chebyshev: degree", (int) 1);
  ifpackList.set("chebyshev: max eigenvalue", (double) 2.0);
  ifpackList.set("chebyshev: min eigenvalue", (double) 1.0);
  ifpackList.set("chebyshev: zero starting solution", false);
  */
  if (xpetraParameters.GetLib() == Xpetra::UseEpetra) {
#if defined(HAVE_MUELU_EPETRA) && defined(HAVE_MUELU_IFPACK)
    ifpackList.set("relaxation: type", "symmetric Gauss-Seidel");
    smooProto = rcp( new IfpackSmoother("point relaxation stand-alone",ifpackList) );
#endif
  } else if (xpetraParameters.GetLib() == Xpetra::UseTpetra) {
#if defined(HAVE_MUELU_TPETRA) && defined(HAVE_MUELU_IFPACK2)
    ifpackList.set("relaxation: type", "Symmetric Gauss-Seidel");
    smooProto = rcp( new Ifpack2Smoother("RELAXATION",ifpackList) );
#endif
  }
  if (smooProto == Teuchos::null) {
    throw(MueLu::Exceptions::RuntimeError("main: smoother error"));
  }

  RCP<SmootherFactory> SmooFact = rcp( new SmootherFactory(smooProto) );
  Acfact->setVerbLevel(Teuchos::VERB_HIGH);

  Teuchos::ParameterList status;
  status = H->FullPopulate(PRfact,Acfact,SmooFact,0,maxLevels);
  //RCP<MueLu::Level> coarseLevel = H.GetLevel(1);
  //RCP<Matrix> P = coarseLevel->template Get< RCP<Matrix> >("P");
  //fileName = "Pfinal.mm";
  //Utils::Write(fileName,P);
  if (comm->getRank() == 0) {
    std::cout  << "======================\n Multigrid statistics \n======================" << std::endl;
    status.print(std::cout,Teuchos::ParameterList::PrintOptions().indent(2));
  }

  //FIXME we should be able to just call smoother->SetNIts(50) ... but right now an exception gets thrown

  RCP<SmootherPrototype> coarseProto;
  if (xpetraParameters.GetLib() == Xpetra::UseEpetra) {
#if defined(HAVE_MUELU_EPETRA) && defined(HAVE_MUELU_AMESOS)
    if (comm->getRank() == 0) std::cout << "CoarseGrid: AMESOS" << std::endl;
    Teuchos::ParameterList amesosList;
    amesosList.set("PrintTiming",true);
    coarseProto = rcp( new AmesosSmoother("Amesos_Klu",amesosList) );
    //#elif
#endif
  } else if (xpetraParameters.GetLib() == Xpetra::UseTpetra) {
    if (coarseSolver=="amesos2") {
#if defined(HAVE_MUELU_TPETRA) && defined(HAVE_MUELU_AMESOS2)
      if (comm->getRank() == 0) std::cout << "CoarseGrid: AMESOS2" << std::endl;
      Teuchos::ParameterList paramList; //unused
      coarseProto = rcp( new Amesos2Smoother("Superlu", paramList) );
#else
      std::cout  << "AMESOS2 not available (try --coarseSolver=ifpack2)" << std::endl;
      return EXIT_FAILURE;
#endif // HAVE_MUELU_TPETRA && HAVE_MUELU_AMESOS2
    } else if(coarseSolver=="ifpack2") {
#if defined(HAVE_MUELU_TPETRA) && defined(HAVE_MUELU_IFPACK2)
        if (comm->getRank() == 0) std::cout << "CoarseGrid: IFPACK2" << std::endl;
        Teuchos::ParameterList ifpack2List;
        ifpack2List.set("fact: ilut level-of-fill",99); // TODO ??
        ifpack2List.set("fact: drop tolerance", 0);
        ifpack2List.set("fact: absolute threshold", 0);
        ifpack2List.set("fact: relative threshold", 0);
        coarseProto = rcp( new Ifpack2Smoother("ILUT",ifpack2List) );
#else
        std::cout  << "IFPACK2 not available (try --coarseSolver=amesos2)" << std::endl;
        return EXIT_FAILURE;
#endif
    } else {
      std::cout  << "Unknow coarse grid solver (try  --coarseSolver=ifpack2 or --coarseSolver=amesos2)" << std::endl;
      return EXIT_FAILURE;
    }

  }
  if (coarseProto == Teuchos::null) {
    throw(MueLu::Exceptions::RuntimeError("main: coarse smoother error"));
  }

  SmootherFactory coarseSolveFact(coarseProto);
  H->SetCoarsestSolver(coarseSolveFact,MueLu::PRE);

  // Define RHS
  RCP<MultiVector> X = MultiVectorFactory::Build(map,1);
  RCP<MultiVector> RHS = MultiVectorFactory::Build(map,1);

  X->setSeed(846930886);
  X->randomize();
  X->norm2(norms);
  if (comm->getRank() == 0)
    std::cout << "||X_true|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << norms[0] << std::endl;

  Op->apply(*X,*RHS,Teuchos::NO_TRANS,(SC)1.0,(SC)0.0);

  // Use AMG directly as an iterative method
  {
    X->putScalar( (SC) 0.0);

    H->PrintResidualHistory(true);
    H->Iterate(*RHS,*X,its);

    X->norm2(norms);
    if (comm->getRank() == 0)
      std::cout << "||X_" << std::setprecision(2) << its << "|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << norms[0] << std::endl;
  }

  return EXIT_SUCCESS;

}
Beispiel #23
0
int main(int argc, char** argv) {

  int fail = 0, dim=0;

#ifdef HAVE_MPI
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &localProc);
  MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
  const Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
  const Epetra_SerialComm Comm;
#endif

  // =============================================================
  // get command line options
  // =============================================================

  Teuchos::CommandLineProcessor clp(false,true);

  std::string *inputFile = new std::string("simple.coords");
  bool verbose = false;

  clp.setOption( "f", inputFile, "Name of coordinate input file");

  clp.setOption( "v", "q", &verbose,
		"Display coordinates and weights before and after partitioning.");

  Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return =
    clp.parse(argc,argv);

  if( parse_return == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED){
#ifdef HAVE_MPI
    MPI_Finalize();
#endif
    return 0;
  }
  if( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {
#ifdef HAVE_MPI
    MPI_Finalize();
#endif
    return 1;
  }

  // =============================================================
  // Open file of coordinates and distribute them across processes
  // so they are unbalanced.
  // =============================================================

  Epetra_MultiVector *mv = ispatest::file2multivector(Comm, *inputFile);

  if (!mv || ((dim = mv->NumVectors()) < 1)){
    if (localProc == 0)
      std::cerr << "Invalid input file " << *inputFile << std::endl;
    exit(1);
  }

  if (localProc == 0){
    std::cerr << "Found input file " << *inputFile << ", " ;
    std::cerr << dim << " dimensional coordinates" << std::endl;
  }

  delete inputFile;

  int base = mv->Map().IndexBase();
  int globalSize = mv->GlobalLength();
  int myShare = 0;
  int n = numProcs - 1;

  if (n){
    if (localProc < n){
      int oneShare = globalSize / n;
      int leftOver = globalSize - (n * oneShare);
      myShare = oneShare + ((localProc < leftOver) ? 1 : 0);
    }
  }
  else{
    myShare = globalSize;
  }

  Epetra_BlockMap unbalancedMap(globalSize, myShare, 1, base, mv->Map().Comm());
  Epetra_Import importer(unbalancedMap, mv->Map());
  Epetra_MultiVector umv(unbalancedMap, dim);
  umv.Import(*mv, importer, Insert);

  delete mv;

  Teuchos::RCP<const Epetra_MultiVector> coords =
    Teuchos::rcp(new const Epetra_MultiVector(umv));

  // =============================================================
  // Create some different coordinate weight vectors
  // =============================================================

  Epetra_MultiVector *unitWgts = ispatest::makeWeights(coords->Map(), &ispatest::unitWeights);
  Epetra_MultiVector *veeWgts = ispatest::makeWeights(coords->Map(), &ispatest::veeWeights);
  Epetra_MultiVector *altWgts = ispatest::makeWeights(coords->Map(), &ispatest::alternateWeights);

  Teuchos::RCP<const Epetra_MultiVector> unit_weights_rcp = Teuchos::rcp(unitWgts);
  Teuchos::RCP<const Epetra_MultiVector> vee_weights_rcp = Teuchos::rcp(veeWgts);
  Teuchos::RCP<const Epetra_MultiVector> alt_weights_rcp = Teuchos::rcp(altWgts);

  if (localProc == 0){
    std::cerr << "Unit weights: Each object has weight 1.0" << std::endl;
    std::cerr << "V weights: Low and high GIDs have high weights, center GIDs have low weights" << std::endl;
    std::cerr << "Alternate weights: Objects on even rank processes have one weight, on odd another weight" << std::endl;
    std::cerr << std::endl;
  }

  // ======================================================================
  //  Create a parameter list for Zoltan, and one for internal partitioning
  // ======================================================================

  Teuchos::ParameterList internalParams;

  internalParams.set("PARTITIONING_METHOD", "SIMPLE_LINEAR");


  Teuchos::ParameterList zoltanParams;

  Teuchos::ParameterList sublist = zoltanParams.sublist("ZOLTAN");

  //sublist.set("DEBUG_LEVEL", "1"); // Zoltan will print out parameters
  //sublist.set("DEBUG_LEVEL", "5");   // proc 0 will trace Zoltan calls
  //sublist.set("DEBUG_MEMORY", "2");  // Zoltan will trace alloc & free

  // =============================================================
  // Run some tests
  // =============================================================
  zoltanParams.set("PARTITIONING METHOD", "RCB");

  if (localProc == 0){
    std::cerr << "RCB - unit weights" << std::endl;
  }

  fail = run_test(coords, unit_weights_rcp, zoltanParams);

  if (fail) goto failure;

  if (localProc == 0){
    std::cerr << "PASS" << std::endl << std::endl;
  }
  // *************************************************************

  if (localProc == 0){
    std::cerr << "HSFC - V weights" << std::endl;
  }


  zoltanParams.set("PARTITIONING METHOD", "HSFC");
  fail = run_test(coords, vee_weights_rcp, zoltanParams);

  if (fail) goto failure;

  if (localProc == 0){
    std::cerr << "PASS" << std::endl << std::endl;
  }

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

  if (localProc == 0){
    std::cerr << "RIB - alternate weights" << std::endl;
  }
  zoltanParams.set("PARTITIONING METHOD", "RIB");

  fail = run_test(coords, alt_weights_rcp, zoltanParams);

  if (fail) goto failure;

  if (localProc == 0){
    std::cerr << "PASS" << std::endl << std::endl;
  }

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

  if (localProc == 0){
    std::cerr << "RIB - no weights supplied" << std::endl;
  }
  zoltanParams.set("PARTITIONING METHOD", "RIB");

  fail = run_test(coords, zoltanParams);

  if (fail) goto failure;

  if (localProc == 0){
    std::cerr << "PASS" << std::endl << std::endl;
  }

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

  goto done;


failure:

  if (localProc == 0){
    std::cerr << "FAIL: test failed" << std::endl;
  }

done:

#ifdef HAVE_MPI
  MPI_Finalize();
#endif

  return fail;
}
Beispiel #24
0
int main(int argc, char *argv[])
{
    bool verbose = false; // verbosity level.
    bool success = true; // determine if the run was successfull

    Teuchos::GlobalMPISession mpiSession(&argc,&argv);

    Teuchos::RCP<Teuchos::FancyOStream>
    out = Teuchos::VerboseObjectBase::getDefaultOStream();

#ifdef HAVE_MPI
    MPI_Comm mpiComm = MPI_COMM_WORLD;
#endif // HAVE_MPI

    try { // catch exceptions

        double omega = 1.0e-2;   // Van Der Pol coefficient
        double x0_1 = 2.0; // ODE initial condition
        double x0_2 = -0.66; // ODE initial condition
        double initialTime = 0.0; // ODE initial time
        double finalTime = 2.0; // ODE final time
        double minStep = 1.0e-10; // minimum step size
        double maxStep = 1.0; // maximum step size
        int degree = 40; // degree of taylor polynomial expansion
        double tol = 1.0e-10; // local error tolerance
        int N = 1000;  // number of steps to take
        string outfile_name = "vdp.out";
        const int num_methods = 2;
        const EMethod method_values[] = { METHOD_ERK, METHOD_ETI };
        const char * method_names[] = { "ERK", "ETI" };
        EMethod method_val = METHOD_ETI;
        Teuchos::EVerbosityLevel verbLevel = Teuchos::VERB_NONE;

        // Parse the command-line options:
        Teuchos::CommandLineProcessor  clp(false); // Don't throw exceptions
        clp.addOutputSetupOptions(true);
        clp.setOption( "x0_1", &x0_1, "First coordinate of initial condition." );
        clp.setOption( "x0_2", &x0_2, "Second coordinate of initial condition." );
        clp.setOption( "omega", &omega, "VDP Coefficient" );
        clp.setOption( "T_initial", &initialTime, "Initial time for simulation." );
        clp.setOption( "T_final", &finalTime, "Final time for simulation." );
        clp.setOption( "minStep", &minStep, "Minimum step size." );
        clp.setOption( "maxStep", &maxStep, "Maximum step size." );
        clp.setOption( "degree", &degree,
                       "Degree of taylor polynomial expansion." );
        clp.setOption( "tol", &tol, "Local error tolerance." );
        clp.setOption( "numsteps", &N, "Number of integration steps to take" );
        clp.setOption( "method", &method_val, num_methods, method_values,
                       method_names, "Integration method" );
        clp.setOption( "verbose", "quiet", &verbose,
                       "Set if output is printed or not" );
        clp.setOption( "output", &outfile_name, "Output file name." );
        setVerbosityLevelOption( "verb-level", &verbLevel, "Overall verbosity level.", &clp );

        Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return =
            clp.parse(argc,argv);
        if( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL )
            return parse_return;

        if (minStep > maxStep)
        {
            std::cerr << "min step must be smaller than max step" << std::endl;
            return(1);
        }

        if (finalTime <= initialTime)
        {
            std::cerr << "Final simulation time must be > initial time."
                      << std::endl;
            return(1);
        }

        // Set up the parameter list for the application:
        Teuchos::ParameterList params;
        Teuchos::ParameterList& vdpoParams = params.sublist("Van Der Pol Oscillator Settings");
        vdpoParams.set( "implicit", false );
        vdpoParams.set( "x0_1", x0_1 );
        vdpoParams.set( "x0_2", x0_2 );
        vdpoParams.set( "omega", omega );
        vdpoParams.set( "Output File Name", outfile_name );

        Teuchos::ParameterList& etpParams = params.sublist("Explicit Taylor Polynomial Settings");
        etpParams.set( "Initial Time", initialTime );
        etpParams.set( "Final Time", finalTime );
        etpParams.set( "Local Error Tolerance", tol );
        etpParams.set( "Minimum Step Size", minStep );
        etpParams.set( "Maximum Step Size", maxStep );
        etpParams.set( "Taylor Polynomial Degree", Teuchos::as<unsigned int>(degree) );
#ifdef HAVE_MPI
        Teuchos::RCP<Epetra_Comm> epetra_comm_ptr_ = Teuchos::rcp( new Epetra_MpiComm(mpiComm) );
#else
        Teuchos::RCP<Epetra_Comm> epetra_comm_ptr_ = Teuchos::rcp( new Epetra_SerialComm  );
#endif // HAVE_MPI

        // Create the factory for the LinearOpWithSolveBase object
        Teuchos::RCP<Thyra::LinearOpWithSolveFactoryBase<double> >
        W_factory;

        // create interface to problem
        Teuchos::RCP<VanDerPolOscillator>
        epetraModel = Teuchos::rcp(new VanDerPolOscillator(epetra_comm_ptr_,
                                   vdpoParams));
        Teuchos::RCP<Thyra::ModelEvaluator<double> >
        model = Teuchos::rcp(new Thyra::EpetraModelEvaluator(epetraModel,
                             W_factory));
        Thyra::ModelEvaluatorBase::InArgs<double> model_ic = model->getNominalValues();

        // Create Stepper object depending on command-line input
        std::string method;
        Teuchos::RCP<Rythmos::StepperBase<double> > stepper_ptr;
        if ( method_val == METHOD_ERK ) {
            stepper_ptr = Rythmos::explicitRKStepper<double>(model);
            Teuchos::RCP<Teuchos::ParameterList> ERKparams = Teuchos::rcp(new Teuchos::ParameterList);
            ERKparams->sublist("VerboseObject").set(
                "Verbosity Level",
                Teuchos::getVerbosityLevelParameterValueName(verbLevel)
            );
            stepper_ptr->setParameterList(ERKparams);
            method = "Explicit Runge-Kutta of order 4";
        }
        else if (method_val == METHOD_ETI) {
            method = "Explicit Taylor";
            stepper_ptr = Teuchos::rcp(new Rythmos::ExplicitTaylorPolynomialStepper<double>);
            stepper_ptr->setModel(model);
            stepper_ptr->setParameterList(Teuchos::rcp(&etpParams,false));
        }
        else {
            TEUCHOS_TEST_FOR_EXCEPT(true);
        }
        Rythmos::StepperBase<double> &stepper = *stepper_ptr;
        stepper.setInitialCondition(model_ic);

        double t = initialTime;
        double dt;
        int step = 0;
        if (method_val == METHOD_ETI) {
            while ( fabs(finalTime-t) > 1.0e-14 ) {
                if (verbose)
                    cout << "t = " << t << endl;

                dt = stepper.takeStep(0.0, Rythmos::STEP_TYPE_VARIABLE);
                t += dt;
                step++;

                epetraModel->saveSolution(*get_Epetra_Vector(*(epetraModel->get_x_map()), stepper.getStepStatus().solution),t);
            }

        }
        else {
            dt = (finalTime-initialTime)/N;

            // Integrate forward with fixed step sizes:
            for (int i=1 ; i<=N ; ++i, step++) {
                if (verbose)
                    cout << "t = " << t << endl;
                double dt_taken = stepper.takeStep(dt, Rythmos::STEP_TYPE_FIXED);
                if (dt_taken != dt) {
                    cerr << "Error, stepper took step of dt = " << dt_taken
                         << " when asked to take step of dt = " << dt << std::endl;
                    break;
                }
                t += dt_taken;
                epetraModel->saveSolution(*get_Epetra_Vector(*(epetraModel->get_x_map()), stepper.getStepStatus().solution),t);
            }
        }
        if (verbose)
            cout << "num steps = " << step << endl;

        // Get final solution
        Teuchos::RCP<const Epetra_Vector> final_x =
            get_Epetra_Vector(*(epetraModel->get_x_map()), stepper.getStepStatus().solution);
        double final_tol = 1.0e-2;
        if (std::abs((*final_x)[0]-1.93704) < final_tol &&
                std::abs((*final_x)[1]+0.70225) < final_tol)
            success = true;
        else
            success = false;

    } // end try
    catch( const std::exception &excpt ) {
        std::cerr << "*** Caught a standard exception : "
                  << excpt.what() << std::endl;
        success = false;
    }
    catch( ... ) {
        std::cerr << "*** Caught an unknown exception!\n";
        success = false;
    }

    if(success)
        *out << "\nEnd Result: TEST PASSED" << endl;
    else
        *out << "\nEnd Result: TEST FAILED" << endl;

    return success ? 0 : 1;
} // end main() [Doxygen looks for this!]