Teuchos::RCP<Tpetra::Operator<Scalar,LocalOrdinal,GlobalOrdinal,Node> >
build_precond(Teuchos::ParameterList& test_params,
              const Teuchos::RCP<const Tpetra::CrsMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node,LocalMatOps> >& A)
{
  Teuchos::Time timer("precond");

  typedef Ifpack2::Preconditioner<Scalar,LocalOrdinal,GlobalOrdinal,Node> Tprec;
  Teuchos::RCP<Tprec> prec;
  Ifpack2::Factory factory;

  std::string prec_name("not specified");
  Ifpack2::getParameter(test_params, "Ifpack2::Preconditioner", prec_name);
  prec = factory.create(prec_name, A);

  Teuchos::ParameterList tif_params;
  if (test_params.isSublist("Ifpack2")) {
    tif_params = test_params.sublist("Ifpack2");
  }

  if (A->getRowMap()->getComm()->getRank() == 0) {
    std::cout << "Configuring/Initializing/Computing Ifpack2 preconditioner..."
       << std::endl;
  }

  prec->setParameters(tif_params);
  prec->initialize();
  timer.start();
  prec->compute();
  timer.stop();

  if (A->getRowMap()->getComm()->getRank() == 0) {
    std::cout << "... Finished Computing Ifpack2 preconditioner (time: "<<timer.totalElapsedTime() << "s)"
       << std::endl;
  }

  typedef typename Teuchos::ScalarTraits<Scalar>::magnitudeType magnitudeType;
  magnitudeType condest = prec->computeCondEst(Ifpack2::Cheap);
  if (A->getRowMap()->getComm()->getRank() == 0) {
    std::cout << "Condition estimate(cheap) for preconditioner on proc 0: "
              << condest << std::endl;
  }
  return prec;
}
void PeridigmNS::HorizonManager::loadHorizonInformationFromBlockParameters(Teuchos::ParameterList& blockParams) {

  // Find the horizon value for each block and record the default horizon value (if any)
  for(Teuchos::ParameterList::ConstIterator it = blockParams.begin() ; it != blockParams.end() ; it++){
    Teuchos::ParameterList& params = blockParams.sublist(it->first);
    bool hasConstantHorizon = params.isType<double>("Horizon");
    bool hasVariableHorizon = params.isType<string>("Horizon");
    TEUCHOS_TEST_FOR_EXCEPT_MSG(hasConstantHorizon && hasVariableHorizon, "\n**** Error parsing horizon information!  Multiple horizon definitions found!\n");
    TEUCHOS_TEST_FOR_EXCEPT_MSG(!hasConstantHorizon && !hasVariableHorizon, "\n**** Error parsing horizon information!  No horizon definition found!\n");

    // Record the horizon as a string regardless of whether or not it is constant
    string horizonString;
    if(hasConstantHorizon){
      double constantHorizon = params.get<double>("Horizon");
      stringstream horizonStringStream;
      horizonStringStream.precision(16);
      horizonStringStream << constantHorizon;
      horizonString = horizonStringStream.str();
    }
    else{
      horizonString = params.get<string>("Horizon");
    }

    // Parse space-delimited list of block names
    string blockNamesString = params.get<string>("Block Names");
    istringstream iss(blockNamesString);
    vector<string> blockNames;
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter<vector<string> >(blockNames));

    for(vector<string>::const_iterator it = blockNames.begin() ; it != blockNames.end() ; ++it){
      if( *it == "Default" || *it == "default" || *it == "DEFAULT" ){
        horizonIsConstant["default"] = hasConstantHorizon;
        horizonStrings["default"] = horizonString;
      }
      else{
        horizonIsConstant[*it] = hasConstantHorizon;
        horizonStrings[*it] = horizonString;
      }
    }
  }
}
 inline Teuchos::RCP<RiskMeasure<Real> > RiskMeasureFactory(Teuchos::ParameterList &parlist) {
   std::string dist = parlist.sublist("SOL").sublist("Risk Measure").get("Name","CVaR");
   ERiskMeasure ed = StringToERiskMeasure(dist);
   switch(ed) {
     case RISKMEASURE_CVAR:
            return Teuchos::rcp(new CVaR<Real>(parlist));
     case RISKMEASURE_EXPUTILITY:
            return Teuchos::rcp(new ExpUtility<Real>(parlist));
     case RISKMEASURE_HMCR:
            return Teuchos::rcp(new HMCR<Real>(parlist));
     case RISKMEASURE_MEANDEVIATIONFROMTARGET:
            return Teuchos::rcp(new MeanDeviationFromTarget<Real>(parlist));
     case RISKMEASURE_MEANDEVIATION:
            return Teuchos::rcp(new MeanDeviation<Real>(parlist));
     case RISKMEASURE_MEANVARIANCEFROMTARGET:
            return Teuchos::rcp(new MeanVarianceFromTarget<Real>(parlist));
     case RISKMEASURE_MEANVARIANCE:
            return Teuchos::rcp(new MeanVariance<Real>(parlist));
     case RISKMEASURE_MOREAUYOSIDACVAR:
            return Teuchos::rcp(new MoreauYosidaCVaR<Real>(parlist));
     case RISKMEASURE_LOGEXPONENTIALQUADRANGLE:
            return Teuchos::rcp(new LogExponentialQuadrangle<Real>(parlist));
     case RISKMEASURE_LOGQUANTILEQUADRANGLE:
            return Teuchos::rcp(new LogQuantileQuadrangle<Real>(parlist));
     case RISKMEASURE_MIXEDQUANTILEQUADRANGLE:
            return Teuchos::rcp(new MixedQuantileQuadrangle<Real>(parlist));
     case RISKMEASURE_QUANTILEQUADRANGLE:
            return Teuchos::rcp(new QuantileQuadrangle<Real>(parlist));
     case RISKMEASURE_QUANTILERADIUSQUADRANGLE:
            return Teuchos::rcp(new QuantileRadiusQuadrangle<Real>(parlist));
     case RISKMEASURE_SMOOTHEDWORSTCASEQUADRANGLE:
            return Teuchos::rcp(new SmoothedWorstCaseQuadrangle<Real>(parlist));
     case RISKMEASURE_TRUNCATEDMEANQUADRANGLE:
            return Teuchos::rcp(new TruncatedMeanQuadrangle<Real>(parlist));
     case RISKMEASURE_CHI2DIVERGENCE:
            return Teuchos::rcp(new Chi2Divergence<Real>(parlist));
     case RISKMEASURE_KLDIVERGENCE:
            return Teuchos::rcp(new KLDivergence<Real>(parlist));
     default:
       TEUCHOS_TEST_FOR_EXCEPTION(true,std::logic_error,
                                  "Invalid risk measure type" << dist);
   }
 }
bool NOX::Epetra::LinearSystemMPBD::
applyJacobianInverse(Teuchos::ParameterList &params, 
		     const NOX::Epetra::Vector &input, 
		     NOX::Epetra::Vector &result)
{
  TEUCHOS_FUNC_TIME_MONITOR("Total deterministic solve Time");

  // Extract blocks
  EpetraExt::BlockVector input_block(View, *base_map, 
				     input.getEpetraVector());
  EpetraExt::BlockVector result_block(View, *base_map, 
				      result.getEpetraVector());
  result_block.PutScalar(0.0);
   
  
  Teuchos::ParameterList& block_solver_params = 
    params.sublist("Deterministic Solver Parameters");
  
  // Solve block linear systems
  bool final_status = true;
  bool status;
  for (int i=0; i<num_mp_blocks; i++) {
    NOX::Epetra::Vector nox_input(input_block.GetBlock(i), 
				  NOX::Epetra::Vector::CreateView);
    NOX::Epetra::Vector nox_result(result_block.GetBlock(i), 
				   NOX::Epetra::Vector::CreateView);
    
    block_solver->setJacobianOperatorForSolve(block_ops->getCoeffPtr(i));

    if (precStrategy == STANDARD)
      block_solver->setPrecOperatorForSolve(precs[i]);
    else if (precStrategy == ON_THE_FLY) {
      block_solver->createPreconditioner(*(prec_x->GetBlock(i)), 
					 block_solver_params, false);
    }

    status = block_solver->applyJacobianInverse(block_solver_params, nox_input, 
						nox_result);
    final_status = final_status && status;
  }

  return final_status;
}
Exemple #5
0
int main(int argc, char *argv[]) {

  bool success = false;
  bool verbose = false;
  try {
    // Set up the printing utilities
    Teuchos::ParameterList noxParams;
    Teuchos::ParameterList& printParams = noxParams.sublist("Printing");
    printParams.set("Output Precision", 5);
    if (argc > 1) {
      if (argv[1][0]=='-' && argv[1][1]=='v')
        printParams.set("Output Information",
            NOX::Utils::OuterIteration +
            NOX::Utils::OuterIterationStatusTest +
            NOX::Utils::InnerIteration +
            NOX::Utils::Parameters +
            NOX::Utils::Details +
            NOX::Utils::Warning +
            NOX::Utils::TestDetails);
      else
        printParams.set("Output Information", NOX::Utils::Error);
    }
    NOX::Utils printing(printParams);

    // Identify the test
    if (printing.isPrintType(NOX::Utils::TestDetails)) {
      std::cout << "Starting lapack/NOX_NewTest/NOX_NewTest.exe" << std::endl;
    }

    // *** Insert your testing here! ***

    success = true;

    if (success)
      std::cout << "Test passed!" << std::endl;
    else
      std::cout << "Test failed!" << std::endl;
  }
  TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);

  return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
Exemple #6
0
Teuchos::RCP<Belos::SolverManager<Scalar,MV,OP> >
build_solver(const Teuchos::RCP<const Teuchos::Comm<int> > &comm,
             Teuchos::ParameterList& test_params,
             Teuchos::RCP<Belos::LinearProblem<Scalar,MV,OP> > problem)
{
  typedef Belos::LinearProblem<Scalar,MV,OP> BLinProb;
  Teuchos::RCP<Belos::SolverManager<Scalar,MV,OP> > solver;

  Teuchos::ParameterList bparams;
  if (test_params.isSublist("Belos")) {
    bparams = test_params.sublist("Belos");
  }
  Teuchos::RCP<Teuchos::ParameterList> rcpparams = Teuchos::rcpFromRef(bparams);

  std::string solver_type("not specified");
  Ifpack2::getParameter(test_params, "solver_type", solver_type);
  if (solver_type == "BlockGmres") {
    // if (comm->getRank() == 0) std::cout << *rcpparams << std::endl;
    solver = Teuchos::rcp(new Belos::BlockGmresSolMgr<Scalar,MV,OP>(problem,rcpparams));
  }
  // else if (solver_type == "PseudoBlockGmres") {
  //   solver = Teuchos::rcp(new Belos::PseudoBlockGmresSolMgr<Scalar,MV,OP>(problem,rcpparams));
  // }
  // else if (solver_type == "PseudoBlockCG") {
  //   solver = Teuchos::rcp(new Belos::PseudoBlockCGSolMgr<Scalar,MV,OP>(problem,rcpparams));
  // }
  // else if (solver_type == "TFQMR") {
  //   solver = Teuchos::rcp(new Belos::TFQMRSolMgr<Scalar,MV,OP>(problem,rcpparams));
  // }
  else if (solver_type == "not specified") {
    throw std::runtime_error("Error in build_solver: solver_type not specified.");
  }
  else {
    std::ostringstream os;
    os << "Error in build_solver: solver_type ("<<solver_type<<") not recognized.";
    os << "\nIfpack2's test-driver recognizes these solvers: PseudoBlockCG, PesudoBlockGmres, BlockGmres, TFQMR.";
    std::string str = os.str();
    throw std::runtime_error(str);
  }
  return solver;
}
Exemple #7
0
int main(int argc, char *argv[]) {

  // Set up the printing utilities
  Teuchos::ParameterList noxParams;
  Teuchos::ParameterList& printParams = noxParams.sublist("Printing");
  printParams.set("Output Precision", 5);
  if (argc > 1) { 
    if (argv[1][0]=='-' && argv[1][1]=='v')
       printParams.set("Output Information", 
			NOX::Utils::OuterIteration + 
			NOX::Utils::OuterIterationStatusTest + 
			NOX::Utils::InnerIteration +
			NOX::Utils::Parameters + 
			NOX::Utils::Details + 
			NOX::Utils::Warning +
			NOX::Utils::TestDetails);
    else
       printParams.set("Output Information", NOX::Utils::Error);
  }
  NOX::Utils printing(printParams);

  // Identify the test
  if (printing.isPrintType(NOX::Utils::TestDetails)) {
    cout << "Starting lapack/NOX_NewTest/NOX_NewTest.exe" << endl;
  }

  // Final return value (0 = succefull, non-zero = failure)
  int status = 0;

  // *** Insert your testing here! ***


  
  if (status == 0) 
    cout << "Test passed!" << endl;
  else 
    cout << "Test failed!" << endl;

  // Final return value (0 = succefull, non-zero = failure)
  return status;
}
Exemple #8
0
bool
BroydenOperator::initialize( Teuchos::ParameterList & nlParams, const Epetra_Vector & vec )
{
  stepVec  = Teuchos::rcp( new NOX::Epetra::Vector(vec) );
  yieldVec = Teuchos::rcp( new NOX::Epetra::Vector(vec) );
  workVec  = Teuchos::rcp( new NOX::Epetra::Vector(vec) );
  oldX     = Teuchos::rcp( new NOX::Epetra::Vector(vec) );
  oldF     = Teuchos::rcp( new NOX::Epetra::Vector(vec) );

  // Set ourself as the Pre/Post Operator so we can update our data during
  // runPostIterate.  Note: we need to make provision for storing and calling 
  // any existing Pre/Post Operator.

  // RPP 9/20/2005: This is a very bad idea!  It breaks the rcp and
  // user's expectations.  For now we will have to create rcp without
  // ownership.  What happens if a user write their own PPO?
  Teuchos::RCP<NOX::Abstract::PrePostOperator> me = Teuchos::rcp(this, false);
  nlParams.sublist("Solver Options").set("User Defined Pre/Post Operator", me);

  return true;
}
Exemple #9
0
void xmlToModelPList(const Teuchos::XMLObject &xml, Teuchos::ParameterList & plist)
{
  // This method composes a plist for the problem
  Teuchos::XMLParameterListReader reader;
  plist = reader.toParameterList(xml);
  
  //  Get list of valid Zoltan2 Parameters
  // Zoltan 2 parameters appear in the input file
  // Right now we have default values stored in
  // the parameter list, we would like to apply
  // the options specified by the user in their
  // input file
  Teuchos::ParameterList zoltan2Parameters;
  Zoltan2::createAllParameters(zoltan2Parameters);
  
  if (plist.isSublist("Zoltan2Parameters")) {
    // Apply user specified zoltan2Parameters
    ParameterList &sub = plist.sublist("Zoltan2Parameters");
    zoltan2Parameters.setParameters(sub);
  }
  
}
  TEUCHOS_UNIT_TEST(bc, dirichlet_complete_param_list)
  {
    
    Teuchos::ParameterList p;
    p.set("Type", "Dirichlet");
    p.set("Sideset ID", "4");
    p.set("Element Block ID", "fluid");
    p.set("Equation Set Name", "UX");
    p.set("Strategy", "Constant");
    p.sublist("Data").set("Value",1.0);

    panzer::BC bc(0,p);

    TEST_EQUALITY(bc.bcID(), 0);
    TEST_EQUALITY(bc.bcType(), BCT_Dirichlet);
    TEST_EQUALITY(bc.sidesetID(), "4");
    TEST_EQUALITY(bc.elementBlockID(), "fluid");
    TEST_EQUALITY(bc.equationSetName(), "UX");

    std::stringstream s;
    s << bc << std::endl;
  }
Exemple #11
0
bool NOX::Epetra::LinearSystemMPBD::
recomputePreconditioner(const NOX::Epetra::Vector& x, 
			Teuchos::ParameterList& p) const
{
  EpetraExt::BlockVector mp_x_block(View, *base_map, x.getEpetraVector());
  Teuchos::ParameterList& solverParams = 
    p.sublist("Deterministic Solver Parameters");
  bool total_success = true;

  if (precStrategy == STANDARD) {
    for (int i=0; i<num_mp_blocks; i++) {
      block_solver->setJacobianOperatorForSolve(block_ops->getCoeffPtr(i));
      if (precs[i] != Teuchos::null)
	block_solver->setPrecOperatorForSolve(precs[i]);
      bool success = 
	block_solver->recomputePreconditioner(*(mp_x_block.GetBlock(i)), 
					      solverParams);
      precs[i] = block_solver->getGeneratedPrecOperator();
      total_success = total_success && success;
    }
  }

  else if (precStrategy == MEAN) {
    block_solver->setJacobianOperatorForSolve(block_ops->getCoeffPtr(0));
    bool success = 
      block_solver->recomputePreconditioner(*(mp_x_block.GetBlock(0)), 
					    solverParams);
    total_success = total_success && success;
  }

  else if (precStrategy == ON_THE_FLY) {
    if (prec_x == Teuchos::null)
      prec_x = Teuchos::rcp(new EpetraExt::BlockVector(mp_x_block));
    else
      *prec_x = mp_x_block;
  }

  return total_success;
}
  /** \brief Constructor.

      Constructor to build a NewtonKrylovStep object with user-defined 
      secant and Krylov objects.  Algorithmic specifications are passed in through 
      a Teuchos::ParameterList.

      @param[in]     parlist    is a parameter list containing algorithmic specifications
      @param[in]     krylov     is a user-defined Krylov object
      @param[in]     secant     is a user-defined secant object
  */
  NewtonKrylovStep(Teuchos::ParameterList &parlist,
             const Teuchos::RCP<Krylov<Real> > &krylov,
             const Teuchos::RCP<Secant<Real> > &secant,
             const bool computeObj = true)
    : Step<Real>(), secant_(secant), krylov_(krylov),
      ekv_(KRYLOV_USERDEFINED), esec_(SECANT_USERDEFINED),
      gp_(Teuchos::null), iterKrylov_(0), flagKrylov_(0),
      verbosity_(0), computeObj_(computeObj), useSecantPrecond_(false) {
    // Parse ParameterList
    Teuchos::ParameterList& Glist = parlist.sublist("General");
    useSecantPrecond_ = Glist.sublist("Secant").get("Use as Preconditioner", false);
    verbosity_ = Glist.get("Print Verbosity",0);
    // Initialize secant object
    if ( useSecantPrecond_ && secant_ == Teuchos::null ) {
      esec_ = StringToESecant(Glist.sublist("Secant").get("Type","Limited-Memory BFGS"));
      secant_ = SecantFactory<Real>(parlist);
    }
    // Initialize Krylov object
    if ( krylov_ == Teuchos::null ) {
      ekv_ = StringToEKrylov(Glist.sublist("Krylov").get("Type","Conjugate Gradients"));
      krylov_ = KrylovFactory<Real>(parlist);
    }
  }
// ************************************************************************
// ************************************************************************
Teuchos::RCP<LOCA::StatusTest::Abstract> LOCA::StatusTest::Factory::
buildComboTest(Teuchos::ParameterList& p,
               const Teuchos::RCP<const LOCA::GlobalData> & globalData,
	       std::map<std::string, Teuchos::RCP<LOCA::StatusTest::Abstract> >*
	       tagged_tests) const
{ 

  int number_of_tests = get<int>(p, "Number of Tests");
  
  std::string combo_type_string = get<std::string>(p, "Combo Type");
  LOCA::StatusTest::Combo::ComboType combo_type;
  if (combo_type_string == "AND")
    combo_type = LOCA::StatusTest::Combo::AND;
  else if (combo_type_string == "OR")
    combo_type = LOCA::StatusTest::Combo::OR;
  else{
    std::string msg = 
      "Error - The \"Combo Type\" must be \"AND\" or \"OR\"!";
    TEST_FOR_EXCEPTION(true, std::logic_error, msg);
  }
  
  RCP<LOCA::StatusTest::Combo> combo_test =
    rcp(new LOCA::StatusTest::Combo(combo_type, globalData));
  
  for (int i=0; i < number_of_tests; ++i) {
    ostringstream subtest_name;
    subtest_name << "Test " << i;
    ParameterList& subtest_list = p.sublist(subtest_name.str(), true);
    
    RCP<LOCA::StatusTest::Abstract> subtest =
      this->buildStatusTests(subtest_list, globalData, tagged_tests);
    
    combo_test->addStatusTest(subtest);
  }
  
  return combo_test;
}
Exemple #14
0
int Amesos_Scalapack::SetParameters( Teuchos::ParameterList &ParameterList ) {
  
  if( debug_ == 1 ) std::cout << "Entering `SetParameters()'" << std::endl;
  
  // retrive general parameters
  SetStatusParameters( ParameterList );
  
  SetControlParameters( ParameterList );
  
  //
  //  We have to set these to their defaults here because user codes 
  //  are not guaranteed to have a "Scalapack" parameter list.
  //
  TwoD_distribution_ = true; 
  grid_nb_ = 32; 
  
  //  Some compilers reject the following cast:
  //  if( &ParameterList == 0 ) return 0;
  
  // ========================================= //
  // retrive ScaLAPACK's parameters from list. //
  // ========================================= //
  
  // retrive general parameters
  //  check to see if they exist before trying to retrieve them
  if (ParameterList.isSublist("Scalapack") ) {
    const Teuchos::ParameterList ScalapackParams = ParameterList.sublist("Scalapack") ;
    //  Fix Bug #3251 
    if ( ScalapackParams.isParameter("2D distribution") )
      TwoD_distribution_ = ScalapackParams.get<bool>("2D distribution");
    if ( ScalapackParams.isParameter("grid_nb") )
      grid_nb_ = ScalapackParams.get<int>("grid_nb");
  }  
  
  return 0;
}
// ************************************************************************
// ************************************************************************
Teuchos::RCP<NOX::StatusTest::Generic> NOX::StatusTest::Factory::
buildComboTest(Teuchos::ParameterList& p, const NOX::Utils& u,
	       std::map<std::string, Teuchos::RCP<NOX::StatusTest::Generic> >* 
	       tagged_tests) const
{ 

  int number_of_tests = get<int>(p, "Number of Tests");
  
  std::string combo_type_string = get<std::string>(p, "Combo Type");
  NOX::StatusTest::Combo::ComboType combo_type;
  if (combo_type_string == "AND")
    combo_type = NOX::StatusTest::Combo::AND;
  else if (combo_type_string == "OR")
    combo_type = NOX::StatusTest::Combo::OR;
  else{
    std::string msg = 
      "Error - The \"Combo Type\" must be \"AND\" or \"OR\"!";
    TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, msg);
  }
  
  RCP<NOX::StatusTest::Combo> combo_test = 
    rcp(new NOX::StatusTest::Combo(combo_type, &u));
  
  for (int i=0; i < number_of_tests; ++i) {
    std::ostringstream subtest_name;
    subtest_name << "Test " << i;
    ParameterList& subtest_list = p.sublist(subtest_name.str(), true);
    
    RCP<NOX::StatusTest::Generic> subtest = 
      this->buildStatusTests(subtest_list, u, tagged_tests);
    
    combo_test->addStatusTest(subtest);
  }
  
  return combo_test;
}
  GMRES( Teuchos::ParameterList &parlist ) : isInitialized_(false) {

    using Teuchos::RCP;
    using Teuchos::rcp;
    using std::vector; 

    Teuchos::ParameterList &gList = parlist.sublist("General");
    Teuchos::ParameterList &kList = gList.sublist("Krylov");
    
    useInexact_      = gList.get("Inexact Hessian-Times-A-Vector",false);
    maxit_           = kList.get("Iteration Limit",50);
    absTol_          = kList.get("Absolute Tolerance", 1.e-4);
    relTol_          = kList.get("Relative Tolerance", 1.e-2);
    useInitialGuess_ = kList.get("Use Initial Guess",false);

    H_     = rcp( new SDMatrix( maxit_+1, maxit_ ) );
    cs_    = rcp( new SDVector( maxit_ ) );
    sn_    = rcp( new SDVector( maxit_ ) );
    s_     = rcp( new SDVector( maxit_+1 ) ); 
    y_     = rcp( new SDVector( maxit_+1 ) );
    cnorm_ = rcp( new SDVector( maxit_ ) );   
    res_   = rcp( new std::vector<Real>(maxit_+1,0.0) );
       
  }
 inline Teuchos::RCP<Distribution<Real> > DistributionFactory(Teuchos::ParameterList &parlist) {
   std::string dist = parlist.sublist("Distribution").get("Name","Dirac");
   EDistribution ed = StringToEDistribution(dist);
   switch(ed) {
     case DISTRIBUTION_ARCSINE:              return Teuchos::rcp(new Arcsine<Real>(parlist));
     case DISTRIBUTION_BETA:                 return Teuchos::rcp(new Beta<Real>(parlist));
     case DISTRIBUTION_CAUCHY:               return Teuchos::rcp(new Cauchy<Real>(parlist));
     case DISTRIBUTION_DIRAC:                return Teuchos::rcp(new Dirac<Real>(parlist));
     case DISTRIBUTION_EXPONENTIAL:          return Teuchos::rcp(new Exponential<Real>(parlist));
     case DISTRIBUTION_GAMMA:                return Teuchos::rcp(new Gamma<Real>(parlist));
     case DISTRIBUTION_GAUSSIAN:             return Teuchos::rcp(new Gaussian<Real>(parlist));
     case DISTRIBUTION_KUMARASWAMY:          return Teuchos::rcp(new Kumaraswamy<Real>(parlist));
     case DISTRIBUTION_LAPLACE:              return Teuchos::rcp(new Laplace<Real>(parlist));
     case DISTRIBUTION_LOGISTIC:             return Teuchos::rcp(new Logistic<Real>(parlist));
     case DISTRIBUTION_PARABOLIC:            return Teuchos::rcp(new Parabolic<Real>(parlist));
     case DISTRIBUTION_RAISEDCOSINE:         return Teuchos::rcp(new RaisedCosine<Real>(parlist));
     case DISTRIBUTION_SMALE:                return Teuchos::rcp(new Smale<Real>(parlist));
     case DISTRIBUTION_TRIANGLE:             return Teuchos::rcp(new Triangle<Real>(parlist));
     case DISTRIBUTION_TRUNCATEDEXPONENTIAL: return Teuchos::rcp(new TruncatedExponential<Real>(parlist));
     case DISTRIBUTION_TRUNCATEDGAUSSIAN:    return Teuchos::rcp(new TruncatedGaussian<Real>(parlist));
     case DISTRIBUTION_UNIFORM:              return Teuchos::rcp(new Uniform<Real>(parlist));
     default:                                return Teuchos::null;
   }
 }
Exemple #18
0
int main(int argc, char *argv[]) {

  // Set up the printing utilities
  Teuchos::ParameterList noxParams;
  Teuchos::ParameterList& printParams = noxParams.sublist("Printing");
  printParams.set("Output Precision", 5);
  if (argc > 1) { 
    if (argv[1][0]=='-' && argv[1][1]=='v')
       printParams.set("Output Information", 
			NOX::Utils::OuterIteration + 
			NOX::Utils::OuterIterationStatusTest + 
			NOX::Utils::InnerIteration +
			NOX::Utils::Parameters + 
			NOX::Utils::Details + 
			NOX::Utils::Warning +
			NOX::Utils::TestDetails);
    else
       printParams.set("Output Information", NOX::Utils::Error);
  }
  NOX::Utils printing(printParams);

  if (printing.isPrintType(NOX::Utils::TestDetails)) {
    cout << "Starting lapack/NOX_Group/NOX_Group.exe" << endl;
  }

  int status = 0;

  // Begin real testing here!
  if (status == 0) 
    cout << "Test passed!" << endl;
  else 
    cout << "Test failed!" << endl;

  // 0 is success
  return status;
}
void tLSCIntegrationTest::solveList(Teuchos::ParameterList & paramList,int vcycles)
{
   paramList.set("Linear Solver Type","AztecOO");
   paramList.sublist("Linear Solver Types")
            .sublist("AztecOO").sublist("Forward Solve").set("Max Iterations",500);
   paramList.sublist("Linear Solver Types")
            .sublist("AztecOO").sublist("Forward Solve").set("Tolerance",1e-12);
   paramList.sublist("Linear Solver Types")
            .sublist("AztecOO").sublist("Forward Solve").sublist("AztecOO Settings").set("Aztec Solver","GMRES");
   paramList.sublist("Linear Solver Types")
            .sublist("AztecOO").sublist("Forward Solve").sublist("AztecOO Settings").set("Size of Krylov Subspace",500);
   paramList.sublist("Linear Solver Types")
            .sublist("AztecOO").sublist("Forward Solve").sublist("AztecOO Settings").set("Output Frequency",0);
   paramList.set("Preconditioner Type","ML");
   Teuchos::ParameterList & MLList = paramList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings");

   // set default values for smoothed aggregation in MLList
   ML_Epetra::SetDefaults("SA",MLList);
   MLList.set("max levels",6);
   MLList.set("cycle applications",vcycles);
   MLList.set("coarse: type","Amesos-KLU");
}
Exemple #20
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;
}
Exemple #21
0
/** \brief This function builds the internals of the state from a parameter list.
  *        
  * This function builds the internals of the LU 2x2 state
  * from a parameter list. Furthermore, it allows a 
  * developer to easily add a factory to the build system.
  *
  * \param[in] settings Parameter list to use as the internal settings
  * \param[in] invLib Inverse library to use for building inverse factory objects
  *
  * \note The default implementation does nothing.
  */
void PCDStrategy::initializeFromParameterList(const Teuchos::ParameterList & pl,
                                              const InverseLibrary & invLib)
{
   Teko_DEBUG_SCOPE("PCDStrategy::initializeFromParameterList",10);

   std::string invStr="Amesos", invFStr="", invSStr="";
   massInverseType_ = Diagonal;

   // "parse" the parameter list
   if(pl.isParameter("Inverse Type"))
      invStr = pl.get<std::string>("Inverse Type");
   if(pl.isParameter("Inverse F Type"))
      invFStr = pl.get<std::string>("Inverse F Type");
   if(pl.isParameter("Inverse Laplace Type"))
      invSStr = pl.get<std::string>("Inverse Laplace Type");
   if(pl.isParameter("Inverse Mass Type")) {
      std::string massInverseStr = pl.get<std::string>("Inverse Mass Type");

      // build inverse types
      massInverseType_ = getDiagonalType(massInverseStr);
   }
   if(pl.isParameter("Flip Schur Complement Ordering"))
      schurCompOrdering_ = pl.get<bool>("Flip Schur Complement Ordering");

   // set defaults as needed
   if(invFStr=="") invFStr = invStr;
   if(invSStr=="") invSStr = invStr;

   // read pressure laplace parameters
   if(pl.isSublist("Pressure Laplace Parameters"))
      lapParams_ = Teuchos::rcp(new Teuchos::ParameterList(pl.sublist("Pressure Laplace Parameters")));
   else
      lapParams_ = Teuchos::rcp(new Teuchos::ParameterList);

   // read pcd operator parameters
   if(pl.isSublist("Pressure Convection Diffusion Parameters"))
      pcdParams_ = Teuchos::rcp(new Teuchos::ParameterList(pl.sublist("Pressure Convection Diffusion Parameters")));
   else
      pcdParams_ = Teuchos::rcp(new Teuchos::ParameterList);

   // The user should not have already added this parameters
   TEUCHOS_TEST_FOR_EXCEPTION(lapParams_->isParameter("Name"),std::logic_error,
                   "Teko: Parameter \"Name\" is not allowed in the sublist \""+lapParams_->name()+"\"");
   TEUCHOS_TEST_FOR_EXCEPTION(lapParams_->isParameter("Tag"),std::logic_error,
                   "Teko: Parameter \"Tag\" is not allowed in the sublist \""+lapParams_->name()+"\"");
   TEUCHOS_TEST_FOR_EXCEPTION(pcdParams_->isParameter("Name"),std::logic_error,
                   "Teko: Parameter \"Name\" is not allowed in the sublist \""+pcdParams_->name()+"\"");
   TEUCHOS_TEST_FOR_EXCEPTION(pcdParams_->isParameter("Tag"),std::logic_error,
                   "Teko: Parameter \"Tag\" is not allowed in the sublist \""+pcdParams_->name()+"\"");

   Teko_DEBUG_MSG_BEGIN(5)
      DEBUG_STREAM << "PCD Strategy Parameters: " << std::endl;
      DEBUG_STREAM << "   inv type   = \"" << invStr  << "\"" << std::endl;
      DEBUG_STREAM << "   inv F type = \"" << invFStr << "\"" << std::endl;
      DEBUG_STREAM << "   inv Laplace type = \"" << invSStr << "\"" << std::endl;
      DEBUG_STREAM << "   inv Mass type = \"" << Teko::getDiagonalName(massInverseType_) << "\"" << std::endl;
      DEBUG_STREAM << "PCD Strategy Parameter list: " << std::endl;
      pl.print(DEBUG_STREAM);
   Teko_DEBUG_MSG_END()

   // build velocity inverse factory
   invFactoryF_ = invLib.getInverseFactory(invFStr);
 
   if(invFStr==invSStr)
      invFactoryS_ = invFactoryF_;
   else
      invFactoryS_ = invLib.getInverseFactory(invSStr);

   lapParams_->set("Name",getPressureLaplaceString());
   pcdParams_->set("Name",getPCDString());

   // setup a request for required operators
   getRequestHandler()->preRequest<Teko::LinearOp>(getPressureMassString());
   // getRequestHandler()->preRequest<Teko::LinearOp>(getPCDString());
   // getRequestHandler()->preRequest<Teko::LinearOp>(getPressureLaplaceString());
   getRequestHandler()->preRequest<Teko::LinearOp>(Teko::RequestMesg(lapParams_));
   getRequestHandler()->preRequest<Teko::LinearOp>(Teko::RequestMesg(pcdParams_));
}
int main_(Teuchos::CommandLineProcessor &clp, int argc, char *argv[]) {
#include <MueLu_UseShortNames.hpp>
  using Teuchos::RCP;
  using Teuchos::rcp;
  using Teuchos::TimeMonitor;

  // =========================================================================
  // MPI initialization using Teuchos
  // =========================================================================
  Teuchos::GlobalMPISession mpiSession(&argc, &argv, NULL);

  RCP< const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
  int numProc = comm->getSize();
  int myRank  = comm->getRank();

  // =========================================================================
  // Parameters initialization
  // =========================================================================
  ::Xpetra::Parameters xpetraParameters(clp);

  bool runHeavyTests = false;
  clp.setOption("heavytests", "noheavytests",  &runHeavyTests, "whether to exercise tests that take a long time to run");

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

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

  // =========================================================================
  // Problem construction
  // =========================================================================
  ParameterList matrixParameters;
  matrixParameters.set("nx",         Teuchos::as<GO>(9999));
  matrixParameters.set("matrixType", "Laplace1D");
  RCP<Matrix>      A           = MueLuTests::TestHelpers::TestFactory<SC, LO, GO, NO>::Build1DPoisson(matrixParameters.get<GO>("nx"), lib);
  RCP<MultiVector> coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<SC,LO,GO,Map,MultiVector>("1D", A->getRowMap(), matrixParameters);

  std::string outDir = "Output/";

  std::vector<std::string> dirList;
  if (runHeavyTests) {
    dirList.push_back("EasyParameterListInterpreter-heavy/");
    dirList.push_back("FactoryParameterListInterpreter-heavy/");
  } else {
    dirList.push_back("EasyParameterListInterpreter/");
    dirList.push_back("FactoryParameterListInterpreter/");
  }
#if defined(HAVE_MPI) && defined(HAVE_MUELU_ISORROPIA) && defined(HAVE_AMESOS2_KLU2)
  // The ML interpreter have internal ifdef, which means that the resulting
  // output would depend on configuration (reguarl interpreter does not have
  // that). Therefore, we need to stabilize the configuration here.
  // In addition, we run ML parameter list tests only if KLU is available
  dirList.push_back("MLParameterListInterpreter/");
  dirList.push_back("MLParameterListInterpreter2/");
#endif
  int numLists = dirList.size();

  bool failed = false;
  Teuchos::Time timer("Interpreter timer");
  //double lastTime = timer.wallTime();
  for (int k = 0; k < numLists; k++) {
    Teuchos::ArrayRCP<std::string> fileList = MueLuTests::TestHelpers::GetFileList(dirList[k],
      (numProc == 1 ? std::string(".xml") : std::string("_np" + Teuchos::toString(numProc) + ".xml")));

    for (int i = 0; i < fileList.size(); i++) {
      // Set seed
      std::srand(12345);

      // Reset (potentially) cached value of the estimate
      A->SetMaxEigenvalueEstimate(-Teuchos::ScalarTraits<SC>::one());

      std::string xmlFile  = dirList[k] + fileList[i];
      std::string outFile  = outDir     + fileList[i];
      std::string baseFile = outFile.substr(0, outFile.find_last_of('.'));
      std::size_t found = baseFile.find("_np");
      if (numProc == 1 && found != std::string::npos) {
#ifdef HAVE_MPI
        baseFile = baseFile.substr(0, found);
#else
        std::cout << "Skipping \"" << xmlFile << "\" as MPI is not enabled" << std::endl;
        continue;
#endif
      }
      baseFile = baseFile + (lib == Xpetra::UseEpetra ? "_epetra" : "_tpetra");
      std::string goldFile = baseFile + ".gold";
      std::ifstream f(goldFile.c_str());
      if (!f.good()) {
        if (myRank == 0)
          std::cout << "Warning: comparison file " << goldFile << " not found.  Skipping test" << std::endl;
        continue;
      }

      std::filebuf    buffer;
      std::streambuf* oldbuffer = NULL;
      if (myRank == 0) {
        // Redirect output
        buffer.open((baseFile + ".out").c_str(), std::ios::out);
        oldbuffer = std::cout.rdbuf(&buffer);
      }

      // NOTE: we cannot use ParameterListInterpreter(xmlFile, comm), because we want to update the ParameterList
      // first to include "test" verbosity
      Teuchos::ParameterList paramList;
      Teuchos::updateParametersFromXmlFileAndBroadcast(xmlFile, Teuchos::Ptr<Teuchos::ParameterList>(&paramList), *comm);
      if      (dirList[k] == "EasyParameterListInterpreter/" || dirList[k] == "EasyParameterListInterpreter-heavy/")
        paramList.set("verbosity", "test");
      else if (dirList[k] == "FactoryParameterListInterpreter/" || dirList[k] == "FactoryParameterListInterpreter-heavy/")
        paramList.sublist("Hierarchy").set("verbosity", "Test");
      else if (dirList[k] == "MLParameterListInterpreter/")
        paramList.set("ML output",     42);
      else if (dirList[k] == "MLParameterListInterpreter2/")
        paramList.set("ML output",     10);

      try {
        timer.start();
        Teuchos::RCP<HierarchyManager> mueluFactory;

        // create parameter list interpreter
        // here we have to distinguish between the general MueLu parameter list interpreter
        // and the ML parameter list interpreter. Note that the ML paramter interpreter also
        // works with Tpetra matrices.
        if (dirList[k] == "EasyParameterListInterpreter/"         ||
            dirList[k] == "EasyParameterListInterpreter-heavy/"   ||
            dirList[k] == "FactoryParameterListInterpreter/"      ||
            dirList[k] == "FactoryParameterListInterpreter-heavy/") {
          mueluFactory = Teuchos::rcp(new ParameterListInterpreter(paramList));

        } else if (dirList[k] == "MLParameterListInterpreter/") {
          mueluFactory = Teuchos::rcp(new MLParameterListInterpreter(paramList));

        } else if (dirList[k] == "MLParameterListInterpreter2/") {
          //std::cout << "ML ParameterList: " << std::endl;
          //std::cout << paramList << std::endl;
          RCP<ParameterList> mueluParamList = Teuchos::getParametersFromXmlString(MueLu::ML2MueLuParameterTranslator::translate(paramList,"SA"));
          //std::cout << "MueLu ParameterList: " << std::endl;
          //std::cout << *mueluParamList << std::endl;
          mueluFactory = Teuchos::rcp(new ParameterListInterpreter(*mueluParamList));
        }

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

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

        if (dirList[k] == "MLParameterListInterpreter/") {
          // MLParameterInterpreter needs the nullspace information if rebalancing is active!
          // add default constant null space vector
          RCP<MultiVector> nullspace = MultiVectorFactory::Build(A->getRowMap(), 1);
          nullspace->putScalar(1.0);
          H->GetLevel(0)->Set("Nullspace", nullspace);
        }

        H->GetLevel(0)->Set("Coordinates", coordinates);

        mueluFactory->SetupHierarchy(*H);

        if (strncmp(fileList[i].c_str(), "reuse", 5) == 0) {
          // Build the Hierarchy the second time
          // Should be faster if we actually do the reuse
          A->SetMaxEigenvalueEstimate(-Teuchos::ScalarTraits<SC>::one());
          mueluFactory->SetupHierarchy(*H);
        }

        timer.stop();
      } catch (Teuchos::ExceptionBase& e) {
        std::string msg = e.what();
        msg = msg.substr(msg.find_last_of('\n')+1);

        if (myRank == 0) {
          std::cout << "Caught exception: " << msg << std::endl;

          // Redirect output back
          std::cout.rdbuf(oldbuffer);
          buffer.close();
        }

        if (msg == "Zoltan interface is not available" ||
            msg == "Zoltan2 interface is not available" ||
            msg == "MueLu::FactoryFactory:BuildFactory(): Cannot create a Zoltan2Interface object: Zoltan2 is disabled: HAVE_MUELU_ZOLTAN2 && HAVE_MPI == false.") {

          if (myRank == 0)
            std::cout << xmlFile << ": skipped (missing library)" << std::endl;

          continue;
        }
      }

      std::string cmd;
      if (myRank == 0) {
        // Redirect output back
        std::cout.rdbuf(oldbuffer);
        buffer.close();

        // Create a copy of outputs
        cmd = "cp -f ";
        system((cmd + baseFile + ".gold " + baseFile + ".gold_filtered").c_str());
        system((cmd + baseFile + ".out " + baseFile + ".out_filtered").c_str());

        // Tpetra produces different eigenvalues in Chebyshev due to using
        // std::rand() for generating random vectors, which may be initialized
        // using different seed, and may have different algorithm from one
        // gcc version to another, or to anogther compiler (like clang)
        // This leads to us always failing this test.
        // NOTE1 : Epetra, on the other hand, rolls out its out random number
        // generator, which always produces same results

        // Ignore the value of "lambdaMax"
        run_sed("'s/lambdaMax: [0-9]*.[0-9]*/lambdaMax = <ignored>/'", baseFile);

        // Ignore the value of "lambdaMin"
        run_sed("'s/lambdaMin: [0-9]*.[0-9]*/lambdaMin = <ignored>/'", baseFile);

        // Ignore the value of "chebyshev: max eigenvalue"
        // NOTE: we skip lines with default value ([default])
        run_sed("'/[default]/! s/chebyshev: max eigenvalue = [0-9]*.[0-9]*/chebyshev: max eigenvalue = <ignored>/'", baseFile);

        // Ignore the exact type of direct solver (it is selected semi-automatically
        // depending on how Trilinos was configured
        run_sed("'s/Amesos\\([2]*\\)Smoother{type = .*}/Amesos\\1Smoother{type = <ignored>}/'", baseFile);
        run_sed("'s/SuperLU solver interface, direct solve/<Direct> solver interface/'", baseFile);
        run_sed("'s/KLU2 solver interface/<Direct> solver interface/'", baseFile);
        run_sed("'s/Basker solver interface/<Direct> solver interface/'", baseFile);

        // Strip template args for some classes
        std::vector<std::string> classes;
        classes.push_back("Xpetra::Matrix");
        classes.push_back("MueLu::Constraint");
        classes.push_back("MueLu::SmootherPrototype");
        for (size_t q = 0; q < classes.size(); q++)
          run_sed("'s/" + classes[q] + "<.*>/" + classes[q] + "<ignored> >/'", baseFile);

#ifdef __APPLE__
        // Some Macs print outs ptrs as 0x0 instead of 0, fix that
        run_sed("'/RCP/ s/=0x0/=0/g'", baseFile);
#endif

        // Run comparison (ignoring whitespaces)
        cmd = "diff -u -w -I\"^\\s*$\" " + baseFile + ".gold_filtered " + baseFile + ".out_filtered";
        int ret = system(cmd.c_str());
        if (ret)
          failed = true;

        //std::ios_base::fmtflags ff(std::cout.flags());
        //std::cout.precision(2);
        //std::cout << xmlFile << " (" << std::setiosflags(std::ios::fixed)
        //          << timer.wallTime() - lastTime << " sec.) : " << (ret ? "failed" : "passed") << std::endl;
        //lastTime = timer.wallTime();
        //std::cout.flags(ff); // reset flags to whatever they were prior to printing time
        std::cout << xmlFile << " : " << (ret ? "failed" : "passed") << std::endl;
      }
    }
  }

  if (myRank == 0)
    std::cout << std::endl << "End Result: TEST " << (failed ? "FAILED" : "PASSED") << std::endl;

  return (failed ? EXIT_FAILURE : EXIT_SUCCESS);
}
Exemple #23
0
  void ParameterListInterpreter<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::UpdateFactoryManager(Teuchos::ParameterList& paramList,
        const Teuchos::ParameterList& defaultList, FactoryManager& manager) const {
    // NOTE: Factory::SetParameterList must be called prior to Factory::SetFactory, as
    // SetParameterList sets default values for non mentioned parameters, including factories

    // === Smoothing ===
    bool isCustomSmoother =
        paramList.isParameter("smoother: pre or post") ||
        paramList.isParameter("smoother: type")    || paramList.isParameter("smoother: pre type")    || paramList.isParameter("smoother: post type")   ||
        paramList.isSublist  ("smoother: params")  || paramList.isSublist  ("smoother: pre params")  || paramList.isSublist  ("smoother: post params") ||
        paramList.isParameter("smoother: sweeps")  || paramList.isParameter("smoother: pre sweeps")  || paramList.isParameter("smoother: post sweeps") ||
        paramList.isParameter("smoother: overlap") || paramList.isParameter("smoother: pre overlap") || paramList.isParameter("smoother: post overlap");;
    MUELU_READ_2LIST_PARAM(paramList, defaultList, "smoother: pre or post", std::string, "both", PreOrPost);
    if (PreOrPost == "none") {
      manager.SetFactory("Smoother", Teuchos::null);

    } else if (isCustomSmoother) {
      // FIXME: get default values from the factory
      // NOTE: none of the smoothers at the moment use parameter validation framework, so we
      // cannot get the default values from it.
#define TEST_MUTUALLY_EXCLUSIVE(arg1,arg2) \
      TEUCHOS_TEST_FOR_EXCEPTION(paramList.isParameter(#arg1) && paramList.isParameter(#arg2), \
                                 Exceptions::InvalidArgument, "You cannot specify both \""#arg1"\" and \""#arg2"\"");
#define TEST_MUTUALLY_EXCLUSIVE_S(arg1,arg2) \
      TEUCHOS_TEST_FOR_EXCEPTION(paramList.isSublist(#arg1) && paramList.isSublist(#arg2), \
                                 Exceptions::InvalidArgument, "You cannot specify both \""#arg1"\" and \""#arg2"\"");

      TEST_MUTUALLY_EXCLUSIVE  ("smoother: type",    "smoother: pre type");
      TEST_MUTUALLY_EXCLUSIVE  ("smoother: type",    "smoother: post type");
      TEST_MUTUALLY_EXCLUSIVE  ("smoother: sweeps",  "smoother: pre sweeps");
      TEST_MUTUALLY_EXCLUSIVE  ("smoother: sweeps",  "smoother: post sweeps");
      TEST_MUTUALLY_EXCLUSIVE  ("smoother: overlap", "smoother: pre overlap");
      TEST_MUTUALLY_EXCLUSIVE  ("smoother: overlap", "smoother: post overlap");
      TEST_MUTUALLY_EXCLUSIVE_S("smoother: params",  "smoother: pre params");
      TEST_MUTUALLY_EXCLUSIVE_S("smoother: params",  "smoother: post params");
      TEUCHOS_TEST_FOR_EXCEPTION(PreOrPost == "both" && (paramList.isParameter("smoother: pre type") != paramList.isParameter("smoother: post type")),
                                 Exceptions::InvalidArgument, "You must specify both \"smoother: pre type\" and \"smoother: post type\"");

      // Default values
      int overlap = 0;
      ParameterList defaultSmootherParams;
      defaultSmootherParams.set("relaxation: type",           "Symmetric Gauss-Seidel");
      defaultSmootherParams.set("relaxation: sweeps",         Teuchos::OrdinalTraits<LO>::one());
      defaultSmootherParams.set("relaxation: damping factor", Teuchos::ScalarTraits<Scalar>::one());

      RCP<SmootherPrototype> preSmoother = Teuchos::null, postSmoother = Teuchos::null;
      std::string            preSmootherType,             postSmootherType;
      ParameterList          preSmootherParams,           postSmootherParams;

      if (paramList.isParameter("smoother: overlap"))
        overlap = paramList.get<int>("smoother: overlap");

      if (PreOrPost == "pre" || PreOrPost == "both") {
        if (paramList.isParameter("smoother: pre type")) {
          preSmootherType = paramList.get<std::string>("smoother: pre type");
        } else {
          MUELU_READ_2LIST_PARAM(paramList, defaultList, "smoother: type", std::string, "RELAXATION", preSmootherTypeTmp);
          preSmootherType = preSmootherTypeTmp;
        }
        if (paramList.isParameter("smoother: pre overlap"))
          overlap = paramList.get<int>("smoother: pre overlap");

        if (paramList.isSublist("smoother: pre params"))
          preSmootherParams = paramList.sublist("smoother: pre params");
        else if (paramList.isSublist("smoother: params"))
          preSmootherParams = paramList.sublist("smoother: params");
        else if (defaultList.isSublist("smoother: params"))
          preSmootherParams = defaultList.sublist("smoother: params");
        else if (preSmootherType == "RELAXATION")
          preSmootherParams = defaultSmootherParams;

        preSmoother = rcp(new TrilinosSmoother(preSmootherType, preSmootherParams, overlap));
      }

      if (PreOrPost == "post" || PreOrPost == "both") {
        if (paramList.isParameter("smoother: post type"))
          postSmootherType = paramList.get<std::string>("smoother: post type");
        else {
          MUELU_READ_2LIST_PARAM(paramList, defaultList, "smoother: type", std::string, "RELAXATION", postSmootherTypeTmp);
          postSmootherType = postSmootherTypeTmp;
        }

        if (paramList.isSublist("smoother: post params"))
          postSmootherParams = paramList.sublist("smoother: post params");
        else if (paramList.isSublist("smoother: params"))
          postSmootherParams = paramList.sublist("smoother: params");
        else if (defaultList.isSublist("smoother: params"))
          postSmootherParams = defaultList.sublist("smoother: params");
        else if (postSmootherType == "RELAXATION")
          postSmootherParams = defaultSmootherParams;
        if (paramList.isParameter("smoother: post overlap"))
          overlap = paramList.get<int>("smoother: post overlap");

        if (postSmootherType == preSmootherType && areSame(preSmootherParams, postSmootherParams))
          postSmoother = preSmoother;
        else
          postSmoother = rcp(new TrilinosSmoother(postSmootherType, postSmootherParams, overlap));
      }

      manager.SetFactory("Smoother", rcp(new SmootherFactory(preSmoother, postSmoother)));
    }

    // === Coarse solver ===
    bool isCustomCoarseSolver =
        paramList.isParameter("coarse: type")   ||
        paramList.isParameter("coarse: params");
    if (paramList.isParameter("coarse: type") && paramList.get<std::string>("coarse: type") == "none") {
      manager.SetFactory("CoarseSolver", Teuchos::null);

    } else if (isCustomCoarseSolver) {
      // FIXME: get default values from the factory
      // NOTE: none of the smoothers at the moment use parameter validation framework, so we
      // cannot get the default values from it.
      MUELU_READ_2LIST_PARAM(paramList, defaultList, "coarse: type", std::string, "", coarseType);

      ParameterList coarseParams;
      if (paramList.isSublist("coarse: params"))
        coarseParams = paramList.sublist("coarse: params");
      else if (defaultList.isSublist("coarse: params"))
        coarseParams = defaultList.sublist("coarse: params");

      RCP<SmootherPrototype> coarseSmoother;
      // TODO: this is not a proper place to check. If we consider direct solver to be a special
      // case of smoother, we would like to unify Amesos and Ifpack2 smoothers in src/Smoothers, and
      // have a single factory responsible for those. Then, this check would belong there.
      if (coarseType == "RELAXATION" || coarseType == "CHEBYSHEV" ||
          coarseType == "ILUT" || coarseType == "ILU" || coarseType == "RILUK" || coarseType == "SCHWARZ")
        coarseSmoother = rcp(new TrilinosSmoother(coarseType, coarseParams));
      else
        coarseSmoother = rcp(new DirectSolver(coarseType, coarseParams));

      manager.SetFactory("CoarseSolver", rcp(new SmootherFactory(coarseSmoother)));
    }

    // === Aggregation ===
    // Aggregation graph
    RCP<CoalesceDropFactory> dropFactory = rcp(new CoalesceDropFactory());
    ParameterList dropParams;
    dropParams.set("lightweight wrap", true);
    MUELU_TEST_AND_SET_PARAM(dropParams, "algorithm",                     paramList, defaultList, "aggregation: drop scheme",         std::string);
    // Rename classical to original
    if (dropParams.isParameter("algorithm") && dropParams.get<std::string>("algorithm") == "classical")
      dropParams.set("algorithm", "original");
    MUELU_TEST_AND_SET_PARAM(dropParams, "aggregation threshold",         paramList, defaultList, "aggregation: drop tol",            double);
    MUELU_TEST_AND_SET_PARAM(dropParams, "Dirichlet detection threshold", paramList, defaultList, "aggregation: Dirichlet threshold", double);

    dropFactory->SetParameterList(dropParams);
    manager.SetFactory("Graph", dropFactory);

    // Aggregation sheme
    MUELU_READ_2LIST_PARAM(paramList, defaultList, "aggregation: type", std::string, "uncoupled", aggType);
    RCP<Factory> aggFactory;
    if      (aggType == "uncoupled") {
      aggFactory = rcp(new UncoupledAggregationFactory());
      ParameterList aggParams;
      MUELU_TEST_AND_SET_PARAM(aggParams, "mode",                 paramList, defaultList, "aggregation: mode",          std::string);
      MUELU_TEST_AND_SET_PARAM(aggParams, "MinNodesPerAggregate", paramList, defaultList, "aggregation: min agg size",  int);
      MUELU_TEST_AND_SET_PARAM(aggParams, "MaxNodesPerAggregate", paramList, defaultList, "aggregation: max agg size",  int);
      MUELU_TEST_AND_SET_PARAM(aggParams, "aggregation: preserve Dirichlet points", paramList, defaultList, "aggregation: preserve Dirichlet points", bool);
      aggFactory->SetParameterList(aggParams);

    } else if (aggType == "coupled") {
  std::string ML2MueLuParameterTranslator::SetParameterList(const Teuchos::ParameterList & paramList_in, const std::string& defaultVals) {
    Teuchos::ParameterList paramList = paramList_in;

    RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout)); // TODO: use internal out (GetOStream())

#if defined(HAVE_MUELU_ML) && defined(HAVE_MUELU_EPETRA)

    // TODO alternative with standard parameterlist from ML user guide?

    if (defaultVals != "") {
      TEUCHOS_TEST_FOR_EXCEPTION(defaultVals!="SA" && defaultVals!="NSSA", Exceptions::RuntimeError,
                                   "MueLu::MLParameterListInterpreter: only \"SA\" and \"NSSA\" allowed as options for ML default parameters.");
      Teuchos::ParameterList ML_defaultlist;
      ML_Epetra::SetDefaults(defaultVals,ML_defaultlist);

      // merge user parameters with default parameters
      MueLu::MergeParameterList(paramList_in, ML_defaultlist, true);
      paramList = ML_defaultlist;
    }
#else
    if (defaultVals != "") {
        // If no validator available: issue a warning and set parameter value to false in the output list
        *out << "Warning: MueLu_ENABLE_ML=OFF. No ML default values available." << std::endl;
    }
#endif // HAVE_MUELU_ML

    //
    // Move smoothers/aggregation/coarse parameters to sublists
    //

    // ML allows to have level-specific smoothers/aggregation/coarse parameters at the top level of the list or/and defined in sublists:
    // See also: ML Guide section 6.4.1, MueLu::CreateSublists, ML_CreateSublists
    ParameterList paramListWithSubList;
    MueLu::CreateSublists(paramList, paramListWithSubList);
    paramList = paramListWithSubList; // swap
    Teuchos::ParameterList adaptingParamList = paramList;    // copy of paramList which is used to removed already interpreted parameters

    //
    // Validate parameter list
    //
    {
      bool validate = paramList.get("ML validate parameter list", true); /* true = default in ML */
      if (validate) {

#if defined(HAVE_MUELU_ML) && defined(HAVE_MUELU_EPETRA)
        // Validate parameter list using ML validator
        int depth = paramList.get("ML validate depth", 5); /* 5 = default in ML */
        TEUCHOS_TEST_FOR_EXCEPTION(! ML_Epetra::ValidateMLPParameters(paramList, depth), Exceptions::RuntimeError,
                                   "ERROR: ML's Teuchos::ParameterList contains incorrect parameter!");
#else
        // If no validator available: issue a warning and set parameter value to false in the output list
        *out << "Warning: MueLu_ENABLE_ML=OFF. The parameter list cannot be validated." << std::endl;
        paramList.set("ML validate parameter list", false);

#endif // HAVE_MUELU_ML
      } // if(validate)
    } // scope

    // stringstream for concatenating xml parameter strings.
    std::stringstream mueluss;

    // create surrounding MueLu parameter list
    mueluss << "<ParameterList name=\"MueLu\">" << std::endl;

    // loop over all ML parameters in provided parameter list
    for (ParameterList::ConstIterator param = paramListWithSubList.begin(); param != paramListWithSubList.end(); ++param) {

      // extract ML parameter name
      const std::string & pname=paramListWithSubList.name(param);

      // extract corresponding (ML) value
      // remove ParameterList specific information from result string
      std::stringstream valuess;
      valuess << paramList.entry(param);
      std::string valuestr = valuess.str();
      replaceAll(valuestr, "[unused]", "");
      replaceAll(valuestr, "[default]", "");
      valuestr = trim(valuestr);

      // transform ML parameter to corresponding MueLu parameter and generate XML string
      std::string valueInterpreterStr = "\"" + valuestr + "\"";
      std::string ret = MasterList::interpretParameterName(MasterList::ML2MueLu(pname),valueInterpreterStr);

      // add XML string
      if (ret != "") {
        mueluss << ret << std::endl;

        // remove parameter from ML parameter list
        adaptingParamList.remove(pname,false);
      }

      // special handling for energy minimization
      // TAW: this is not optimal for symmetric problems but at least works.
      //      for symmetric problems the "energy minimization" parameter should not exist anyway...
      if (pname == "energy minimization: enable") {
        mueluss << "<Parameter name=\"problem: symmetric\"      type=\"bool\"     value=\"false\"/>" << std::endl;
        mueluss << "<Parameter name=\"transpose: use implicit\" type=\"bool\"     value=\"false\"/>" << std::endl;
      }

      // special handling for smoothers
      if (pname == "smoother: type") {

        mueluss << GetSmootherFactory(paramList, adaptingParamList, pname, valuestr);

      }

      // special handling for level-specific smoothers
      if (pname.find("smoother: list (level",0) == 0) {
        // Scan pname (ex: pname="smoother: type (level 2)")
        std::string type, option;
        int levelID=-1;
        {
          typedef Teuchos::ArrayRCP<char>::size_type size_type;
          Teuchos::Array<char> ctype  (size_type(pname.size()+1));
          Teuchos::Array<char> coption(size_type(pname.size()+1));

          int matched = sscanf(pname.c_str(),"%s %[^(](level %d)", ctype.getRawPtr(), coption.getRawPtr(), &levelID); // use [^(] instead of %s to allow for strings with white-spaces (ex: "ifpack list")
          type = std::string(ctype.getRawPtr());
          option = std::string(coption.getRawPtr()); option.resize(option.size () - 1); // remove final white-space

          if (matched != 3 || (type != "smoother:")) {
            TEUCHOS_TEST_FOR_EXCEPTION(true, MueLu::Exceptions::RuntimeError, "MueLu::CreateSublist(), Line " << __LINE__ << ". "
                                        << "Error in creating level-specific sublists" << std::endl
                                        << "Offending parameter: " << pname << std::endl);
          }

          mueluss << "<ParameterList name=\"level " << levelID << "\">" << std::endl;
          mueluss << GetSmootherFactory(paramList.sublist(pname),adaptingParamList.sublist(pname), "smoother: type", paramList.sublist(pname).get<std::string>("smoother: type"));
          mueluss << "</ParameterList>" << std::endl;
        }
      }

      // special handling for coarse level
      TEUCHOS_TEST_FOR_EXCEPTION(paramList.isParameter("coarse: type"), Exceptions::RuntimeError, "MueLu::MLParameterListInterpreter::Setup(): The parameter \"coarse: type\" should not exist but being stored in \"coarse: list\" instead.");
      if ( pname == "coarse: list" ) {

        // interpret smoother/coarse solver data.
        // Note, that we inspect the "coarse: list" sublist to define the "coarse" smoother/solver
        // Be aware, that MueLu::CreateSublists renames the prefix of the parameters in the "coarse: list" from "coarse" to "smoother".
        // Therefore, we have to check the values of the "smoother" parameters
        TEUCHOS_TEST_FOR_EXCEPTION(!paramList.sublist("coarse: list").isParameter("smoother: type"), Exceptions::RuntimeError, "MueLu::MLParameterListInterpreter::Setup(): no coarse grid solver defined.");
        mueluss << GetSmootherFactory(paramList.sublist("coarse: list"), adaptingParamList.sublist("coarse: list"), "coarse: type", paramList.sublist("coarse: list").get<std::string>("smoother: type"));


      }
    } // for

    mueluss << "</ParameterList>" << std::endl;

    return mueluss.str();
  }
Exemple #25
0
int main(int argc, char *argv[])
{
#ifdef HAVE_MPI
    Teuchos::GlobalMPISession mpiSession(&argc, &argv, 0);
    Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
    Epetra_SerialComm Comm;
#endif
    int nProcs, myPID ;
    Teuchos::ParameterList pLUList ;        // ParaLU parameters
    Teuchos::ParameterList isoList ;        // Isorropia parameters
    Teuchos::ParameterList shyLUList ;    // shyLU parameters
    Teuchos::ParameterList ifpackList ;    // shyLU parameters
    string ipFileName = "ShyLU.xml";       // TODO : Accept as i/p

    nProcs = mpiSession.getNProc();
    myPID = Comm.MyPID();

    if (myPID == 0)
    {
        cout <<"Parallel execution: nProcs="<< nProcs << endl;
    }

    // =================== Read input xml file =============================
    Teuchos::updateParametersFromXmlFile(ipFileName, &pLUList);
    isoList = pLUList.sublist("Isorropia Input");
    shyLUList = pLUList.sublist("ShyLU Input");
    shyLUList.set("Outer Solver Library", "AztecOO");
    // Get matrix market file name
    string MMFileName = Teuchos::getParameter<string>(pLUList, "mm_file");
    string prec_type = Teuchos::getParameter<string>(pLUList, "preconditioner");
    int maxiters = Teuchos::getParameter<int>(pLUList, "Outer Solver MaxIters");
    double tol = Teuchos::getParameter<double>(pLUList, "Outer Solver Tolerance");
    string rhsFileName = pLUList.get<string>("rhs_file", "");

    if (myPID == 0)
    {
        cout << "Input :" << endl;
        cout << "ParaLU params " << endl;
        pLUList.print(std::cout, 2, true, true);
        cout << "Matrix market file name: " << MMFileName << endl;
    }

    // ==================== Read input Matrix ==============================
    Epetra_CrsMatrix *A;
    Epetra_MultiVector *b1;

    int err = EpetraExt::MatrixMarketFileToCrsMatrix(MMFileName.c_str(), Comm,
                                                        A);
    //EpetraExt::MatlabFileToCrsMatrix(MMFileName.c_str(), Comm, A);
    //assert(err != 0);
    //cout <<"Done reading the matrix"<< endl;
    int n = A->NumGlobalRows();
    //cout <<"n="<< n << endl;

    // Create input vectors
    Epetra_Map vecMap(n, 0, Comm);
    if (rhsFileName != "")
    {
        err = EpetraExt::MatrixMarketFileToMultiVector(rhsFileName.c_str(),
                                         vecMap, b1);
    }
    else
    {
        b1 = new Epetra_MultiVector(vecMap, 1, false);
        b1->PutScalar(1.0);
    }

    Epetra_MultiVector x(vecMap, 1);
    //cout << "Created the vectors" << endl;

    // Partition the matrix with hypergraph partitioning and redisstribute
    Isorropia::Epetra::Partitioner *partitioner = new
                            Isorropia::Epetra::Partitioner(A, isoList, false);
    partitioner->partition();
    Isorropia::Epetra::Redistributor rd(partitioner);

    Epetra_CrsMatrix *newA;
    Epetra_MultiVector *newX, *newB; 
    rd.redistribute(*A, newA);
    delete A;
    A = newA;

    rd.redistribute(x, newX);
    rd.redistribute(*b1, newB);

    Epetra_LinearProblem problem(A, newX, newB);

    AztecOO solver(problem);

    ifpackList ;
    Ifpack_Preconditioner *prec;
    ML_Epetra::MultiLevelPreconditioner *MLprec;
    if (prec_type.compare("ShyLU") == 0)
    {
        prec = new Ifpack_ShyLU(A);
        prec->SetParameters(shyLUList);
        prec->Initialize();
        prec->Compute();
        //(dynamic_cast<Ifpack_ShyLU *>(prec))->JustTryIt();
        //cout << " Going to set it in solver" << endl ;
        solver.SetPrecOperator(prec);
        //cout << " Done setting the solver" << endl ;
    }
    else if (prec_type.compare("ILU") == 0)
    {
        ifpackList.set( "fact: level-of-fill", 1 );
        prec = new Ifpack_ILU(A);
        prec->SetParameters(ifpackList);
        prec->Initialize();
        prec->Compute();
        solver.SetPrecOperator(prec);
    }
    else if (prec_type.compare("ILUT") == 0)
    {
        ifpackList.set( "fact: ilut level-of-fill", 2 );
        ifpackList.set( "fact: drop tolerance", 1e-8);
        prec = new Ifpack_ILUT(A);
        prec->SetParameters(ifpackList);
        prec->Initialize();
        prec->Compute();
        solver.SetPrecOperator(prec);
    }
    else if (prec_type.compare("ML") == 0)
    {
        Teuchos::ParameterList mlList; // TODO : Take it from i/p
        MLprec = new ML_Epetra::MultiLevelPreconditioner(*A, mlList, true);
        solver.SetPrecOperator(MLprec);
    }

    solver.SetAztecOption(AZ_solver, AZ_gmres);
    solver.SetMatrixName(333);
    //solver.SetAztecOption(AZ_output, 1);
    //solver.SetAztecOption(AZ_conv, AZ_Anorm);
    //cout << "Going to iterate for the global problem" << endl;

    solver.Iterate(maxiters, tol);

    // compute ||Ax - b||
    double Norm;
    Epetra_MultiVector Ax(vecMap, 1);

    Epetra_MultiVector *newAx; 
    rd.redistribute(Ax, newAx);
    A->Multiply(false, *newX, *newAx);
    newAx->Update(1.0, *newB, -1.0);
    newAx->Norm2(&Norm);
    double ANorm = A->NormOne();

    cout << "|Ax-b |/|A| = " << Norm/ANorm << endl;

    delete newAx;
    if (prec_type.compare("ML") == 0)
    {
        delete MLprec;
    }
    else
    {
        delete prec;
    }

    delete b1;
    delete newX;
    delete newB;
    delete A;
    delete partitioner;
}
int main(int argc, char *argv[]) {

#ifdef HAVE_MPI
  MPI_Init(&argc, &argv);
  Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
  Epetra_SerialComm Comm;
#endif

  // initialize the random number generator

  int ml_one = 1;
  ML_srandom1(&ml_one);
  // ===================== //
  // create linear problem //
  // ===================== //

  ParameterList GaleriList;
  GaleriList.set("nx", 10);
  GaleriList.set("ny", 10);
  GaleriList.set("nz", 10 * Comm.NumProc());
  GaleriList.set("mx", 1);
  GaleriList.set("my", 1);
  GaleriList.set("mz", Comm.NumProc());

  Epetra_Map* Map = CreateMap("Cartesian3D", Comm, GaleriList);
  Epetra_CrsMatrix* Matrix = CreateCrsMatrix("Laplace3D", Map, GaleriList);
  Epetra_MultiVector* Coords = CreateCartesianCoordinates("3D",Map,GaleriList);

  Epetra_Vector LHS(*Map);
  Epetra_Vector RHS(*Map);

  Epetra_LinearProblem Problem(Matrix, &LHS, &RHS);

  Teuchos::ParameterList MLList;
  double TotalErrorResidual = 0.0, TotalErrorExactSol = 0.0;

  // ====================== //
  // default options for SA //
  // ====================== //

  if (Comm.MyPID() == 0) PrintLine();

  ML_Epetra::SetDefaults("SA",MLList);
  MLList.set("smoother: type", "Gauss-Seidel");
  char mystring[80];
  strcpy(mystring,"SA");
  TestMultiLevelPreconditioner(mystring, MLList, Problem,
                               TotalErrorResidual, TotalErrorExactSol);


  // ============================================== //
  // default options for SA, efficient symmetric GS //
  // ============================================== //

  if (Comm.MyPID() == 0) PrintLine();

  ML_Epetra::SetDefaults("SA",MLList);
  MLList.set("smoother: type", "Gauss-Seidel");
  MLList.set("smoother: Gauss-Seidel efficient symmetric",true);

  TestMultiLevelPreconditioner(mystring, MLList, Problem,
                               TotalErrorResidual, TotalErrorExactSol,true);

  // ============================== //
  // default options for SA, Jacobi //
  // ============================== //

  if (Comm.MyPID() == 0) PrintLine();

  ML_Epetra::SetDefaults("SA",MLList);
  MLList.set("smoother: type", "Jacobi");

  TestMultiLevelPreconditioner(mystring, MLList, Problem, TotalErrorResidual,
                               TotalErrorExactSol,true);

  // =========================== //
  // default options for SA, Cheby //
  // =========================== //

  if (Comm.MyPID() == 0) PrintLine();

  ML_Epetra::SetDefaults("SA",MLList);
  MLList.set("smoother: type", "Chebyshev");

  TestMultiLevelPreconditioner(mystring, MLList, Problem,
                               TotalErrorResidual, TotalErrorExactSol);



  // =========================== //
  // Specifying Ifpack coarse lists correctly
  // =========================== //
#ifdef HAVE_ML_IFPACK
  if (Comm.MyPID() == 0) PrintLine();
  ML_Epetra::SetDefaults("SA",MLList);

  if(!Comm.MyPID()) {
    MLList.set("ML print initial list",1);
    MLList.set("ML print final list",1);
  }

  MLList.set("smoother: type","ILU");
  MLList.set("coarse: type","ILUT");
  ParameterList &fList = MLList.sublist("smoother: ifpack list");
  fList.set("fact: level-of-fill",1);
  ParameterList &cList = MLList.sublist("coarse: ifpack list");
  cList.set("fact: ilut level-of-fill",1e-2);
  TestMultiLevelPreconditioner(mystring, MLList, Problem,
                               TotalErrorResidual, TotalErrorExactSol);
#endif


  // =========================== //
  // Specifying level sublists
  // =========================== //
  if (Comm.MyPID() == 0) PrintLine();
  ParameterList LevelList;
  ML_Epetra::SetDefaults("SA",LevelList);
  ParameterList &smList = LevelList.sublist("smoother: list (level 0)");
  smList.set("smoother: type","Jacobi");
  smList.set("smoother: sweeps",5);
  ParameterList &smList2 = LevelList.sublist("smoother: list (level 1)");
  smList2.set("smoother: type","symmetric Gauss-Seidel");
  smList2.set("smoother: sweeps",3);
  ParameterList &coarseList = LevelList.sublist("coarse: list");
  coarseList.set("smoother: type","symmetric Gauss-Seidel");
  TestMultiLevelPreconditioner(mystring, LevelList, Problem,
                               TotalErrorResidual, TotalErrorExactSol);


  // =========================== //
  // Ifpack G-S w/ L1
  // =========================== //
#ifdef HAVE_ML_IFPACK
  if (Comm.MyPID() == 0) PrintLine();
  ML_Epetra::SetDefaults("SA",MLList);
  MLList.set("smoother: use l1 Gauss-Seidel",true);
  MLList.set("smoother: type", "Gauss-Seidel");
  TestMultiLevelPreconditioner(mystring, MLList, Problem,
                               TotalErrorResidual, TotalErrorExactSol);
#endif

  // =========================== //
  // Ifpack SGS w/ L1
  // =========================== //
#ifdef HAVE_ML_IFPACK
  if (Comm.MyPID() == 0) PrintLine();
  ML_Epetra::SetDefaults("SA",MLList);
  MLList.set("smoother: use l1 Gauss-Seidel",true);
  MLList.set("smoother: type", "symmetric Gauss-Seidel");
  TestMultiLevelPreconditioner(mystring, MLList, Problem,
                               TotalErrorResidual, TotalErrorExactSol);
#endif


  // =========================== //
  // Autodetected Line SGS (trivial lines) 
  // =========================== //
  if (Comm.MyPID() == 0) PrintLine();
  ML_Epetra::SetDefaults("SA",MLList);
  MLList.set("smoother: type", "line Gauss-Seidel");
  MLList.set("smoother: line detection threshold",0.1);
  MLList.set("x-coordinates",(*Coords)[0]);
  MLList.set("y-coordinates",(*Coords)[1]);
  MLList.set("z-coordinates",(*Coords)[2]);
  TestMultiLevelPreconditioner(mystring, MLList, Problem,
                               TotalErrorResidual, TotalErrorExactSol);
  

  // ===================== //
  // print out total error //
  // ===================== //

  if (Comm.MyPID() == 0) {
    cout << endl;
    cout << "......Total error for residual        = " << TotalErrorResidual << endl;
    cout << "......Total error for exact solution  = " << TotalErrorExactSol << endl;
    cout << endl;
  }

  delete Matrix;
  delete Coords;
  delete Map;


  if (TotalErrorResidual > 1e-8) {
    cerr << "Error: `MultiLevelPrecoditioner_Sym.exe' failed!" << endl;
    exit(EXIT_FAILURE);
  }

#ifdef HAVE_MPI
  MPI_Finalize();
#endif

  if (Comm.MyPID() == 0)
    cerr << "`MultiLevelPrecoditioner_Sym.exe' passed!" << endl;

  return (EXIT_SUCCESS);
}
    bool SolverTrilinosML::Solve(INMOST::Sparse::Vector &RHS, INMOST::Sparse::Vector &SOL) {
        std::string name = Epetra_problem->first;
        Epetra_LinearProblem *Epetra_linear_problem = &Epetra_problem->second;
        Epetra_Vector VectorRHS(View, matrix->Map(), &*RHS.Begin());
        Epetra_Vector VectorSOL(View, matrix->Map(), &*SOL.Begin());
        Epetra_linear_problem->SetRHS(&VectorRHS);
        Epetra_linear_problem->SetLHS(&VectorSOL);

        bool have_params = parameters_file != "";
        const Teuchos::RCP<Teuchos::ParameterList> top_level_params = Teuchos::createParameterList();
        Teuchos::ParameterList local_list;
        if (have_params) {
            Teuchos::updateParametersFromXmlFileAndBroadcast(parameters_file, top_level_params.ptr(),
                                                             Teuchos::MpiComm<int>(Teuchos::opaqueWrapper(
                                                                     RHS.GetCommunicator())));
            if (!top_level_params->isSublist(name))
                have_params = false;
            else {
                local_list = top_level_params->sublist(name);
            }
        }

        AztecOO AztecSolver(*Epetra_linear_problem);

        if (have_params && local_list.isSublist("AztecOO")) {
            Teuchos::ParameterList AztecOOParams = local_list.sublist("AztecOO");
            if (AztecOOParams.isParameter("Max Iterations")) {
                maximum_iterations = AztecOOParams.get<int>("Max Iterations");

            }
            if (AztecOOParams.isParameter("Tolerance")) {
                rtol = AztecOOParams.get<double>("Tolerance");
            }
            if (AztecOOParams.isSublist("AztecOO Settings")) {
                AztecSolver.SetParameters(AztecOOParams.sublist("AztecOO Settings"));
            }
        } else {
            AztecSolver.SetAztecOption(AZ_diagnostics, AZ_none);
            AztecSolver.SetAztecOption(AZ_output, AZ_none);
            AztecSolver.SetAztecOption(AZ_solver, AZ_bicgstab);
            AztecSolver.SetAztecOption(AZ_overlap, schwartz_overlap);
        }

        Teuchos::ParameterList List;
        if (have_params && local_list.isSublist("ML") && local_list.sublist("ML").isSublist("ML Settings")) {
            List = local_list.sublist("ML").sublist("ML Settings");
        } else {
            ML_Epetra::SetDefaults("SA", List);
            List.set("max levels", 6);
            List.set("increasing or decreasing", "decreasing");
        }

        ML_Epetra::MultiLevelPreconditioner *Prec = new ML_Epetra::MultiLevelPreconditioner(*matrix, List, true);
        AztecSolver.SetPrecOperator(Prec);

        AztecSolver.Iterate(maximum_iterations, rtol);
        const double *stats = AztecSolver.GetAztecStatus();
        bool success = true;
        std::string reason = "";
        TrilinosCheckStatus(static_cast<int>(stats[AZ_why]), success, reason);
        lastIterations = static_cast<INMOST_DATA_ENUM_TYPE>(AztecSolver.NumIters());
        lastResidual = AztecSolver.TrueResidual();
        returnReason = reason;
        delete Prec;
        return success;
    }
Exemple #28
0
Teuchos::RCP< std::vector<std::string> > RBGen::genFileList( const Teuchos::ParameterList& params )
{
  Teuchos::RCP< std::vector< std::string > > filenames = Teuchos::rcp( new std::vector< std::string >() ); 

  // See if the "File I/O" sublist exists
  TEUCHOS_TEST_FOR_EXCEPTION(!params.isSublist( "File IO" ), std::invalid_argument, "File I/O sublist does not exist!");
  
  // Get the "File I/O" sublist.
  Teuchos::ParameterList& fileio_params = const_cast<Teuchos::ParameterList&>(params.sublist( "File IO" ) );
  
  // See if the "Data Filename Format" sublist exists 
  TEUCHOS_TEST_FOR_EXCEPTION(!fileio_params.isSublist( "Data Filename Format" ), std::invalid_argument, "Data Filename Format sublist does not exist!");
  
  // Get the "Data Filename Format" sublist.
  Teuchos::ParameterList& fileformat_params = fileio_params.sublist( "Data Filename Format" );
  
  // Get the string prepended to the numeric characters.
  std::string prepend = "";
  if ( fileformat_params.isParameter( "Prepend" ) ) {
    prepend = Teuchos::getParameter<std::string>( fileformat_params, "Prepend" );
  }

  // Get the string postpended to the numeric characters.
  std::string postpend = "";
  if ( fileformat_params.isParameter( "Postpend" ) ) {
    postpend = Teuchos::getParameter<std::string>( fileformat_params, "Postpend" );
  }

  // Get the string prepended to the numeric characters.
  std::string extension = "";
  if ( fileformat_params.isParameter( "Extension" ) ) {
    extension = Teuchos::getParameter<std::string>( fileformat_params, "Extension" );
  }
  
    // Get the base for the numeric count
  int base_num = 0;
  if ( fileformat_params.isParameter( "File Number Base" ) ) {
    base_num = Teuchos::getParameter<int>( fileformat_params, "File Number Base" );
  }

  std::string format_type = Teuchos::getParameter<std::string>( fileformat_params, "Type" );

  if ( format_type == "Single file" ) {

    // Get the file to process
    filenames->push_back( Teuchos::getParameter<std::string>( fileformat_params, "Data File" ) );
   
  } else

  if ( format_type == "Fixed length numeric" ) {
    
    // Get the number of files to process
    int num_files = Teuchos::getParameter<int>( fileformat_params, "Number of Files" );
    int max_num = base_num + num_files;
    int num_places = (int)::ceil( ::log10( (double)(max_num) ) );

    for (int i=base_num; i<max_num; i++) {

      // Generate the current filename
      std::string curr_filename = prepend;

      // Get the number of places needed for the current file number
      int curr_places = (int)::ceil( ::log10( (double)(i+1) ) );
      
      // Add zeros to pad the file number
      for (int j=curr_places; j<num_places; j++) {
	curr_filename += "0";
      }
	
      // Now add on the current file number, postpend string and extension
      filenames->push_back( curr_filename + Teuchos::Utils::toString( i ) + postpend + extension );
    }
    
  } else 

  if ( format_type == "Variable length numeric" ) {

    // Get the number of files to process
    int num_files = Teuchos::getParameter<int>( fileformat_params, "Number of Files" );
    int max_num = base_num + num_files;

    for (int i=base_num; i<max_num; i++) {
      filenames->push_back( prepend + Teuchos::Utils::toString( i ) + postpend + extension );
    }    
  } 

  else {
    std::string err_str = "File format type, 'Type = " + format_type + "', is not recognized!";
    TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, err_str);
  }
  
  return filenames;

}
Exemple #29
0
int main(int argc, char *argv[]) {

  typedef std::vector<RealT>               vector;
  typedef ROL::Vector<RealT>               V;
  typedef ROL::StdVector<RealT>            SV;
  typedef ROL::Objective<RealT>            OBJ;
  typedef ROL::EqualityConstraint<RealT>   EC;  

  typedef typename vector::size_type       uint;


  using Teuchos::RCP; using Teuchos::rcp;

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

  // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
  int iprint     = argc - 1;
  Teuchos::RCP<std::ostream> outStream;
  Teuchos::oblackholestream bhs; // outputs nothing
  if (iprint > 0)
    outStream = Teuchos::rcp(&std::cout, false);
  else
    outStream = Teuchos::rcp(&bhs, false);

  int errorFlag  = 0;

  // *** Example body.

  try {

    uint xdim = 4;
    uint cdim = 1;

    RCP<vector> x_exact_rcp = rcp( new vector(xdim), 0.0 );
    (*x_exact_rcp)[0] = 1.0;
    (*x_exact_rcp)[1] = 1.0;

    RCP<V> x     = rcp( new SV( rcp( new vector(xdim, 0.0) ) ) );
    RCP<V> d     = rcp( new SV( rcp( new vector(xdim, 0.0) ) ) );
    RCP<V> xtest = rcp( new SV( rcp( new vector(xdim, 0.0) ) ) );

    RCP<V> c1    = rcp( new SV( rcp( new vector(cdim, 1.0) ) ) );
    RCP<V> c2    = rcp( new SV( rcp( new vector(cdim, 1.0) ) ) );
    RCP<V> l1    = rcp( new SV( rcp( new vector(cdim, 1.0) ) ) );
    RCP<V> l2    = rcp( new SV( rcp( new vector(cdim, 1.0) ) ) );

    RCP<V> c    =  ROL::CreatePartitionedVector( c1, c2 );
    RCP<V> l    =  ROL::CreatePartitionedVector( l1, l2 );
  


    SV x_exact( x_exact_rcp );
 
    // Initial guess from H&S 39
    x->applyUnary(ROL::Elementwise::Fill<RealT>(2.0));
 
    ROL::RandomizeVector(*d, -1.0, 1.0 ); 
    ROL::RandomizeVector(*xtest, -1.0, 1.0 ); 
    
    RCP<OBJ> obj  = rcp( new ROL::ZOO::Objective_HS39<RealT>() );
    RCP<EC>  con1 = rcp( new ROL::ZOO::EqualityConstraint_HS39a<RealT>() );
    RCP<EC>  con2 = rcp( new ROL::ZOO::EqualityConstraint_HS39b<RealT>() );
   
    RCP<EC>  con = CreateEqualityConstraintPartitioned(con1, con2); 

    *outStream << "Checking objective" << std::endl;
    obj->checkGradient(*x,*d,true,*outStream); 

    *outStream << "\nChecking first equality constraint" << std::endl;
    con1->checkApplyJacobian( *xtest, *d, *c1 , true, *outStream );
    con1->checkApplyAdjointJacobian( *xtest, *l1, *c1, *d, true, *outStream );
    con1->checkApplyAdjointHessian( *xtest, *l1, *d, *xtest, true, *outStream );

    *outStream << "\nChecking second equality constraint" << std::endl;
    con2->checkApplyJacobian( *xtest, *d, *c2, true, *outStream );
    con2->checkApplyAdjointJacobian( *xtest, *l2, *c2, *d, true, *outStream );
    con2->checkApplyAdjointHessian( *xtest, *l2, *d, *xtest, true, *outStream );

    *outStream << "\nChecking partitioned equality constraint" << std::endl;
    con->checkApplyJacobian( *xtest, *d, *c, true, *outStream );
    con->checkApplyAdjointJacobian( *xtest, *l, *c, *d, true, *outStream );
    con->checkApplyAdjointHessian( *xtest, *l, *d, *xtest, true, *outStream );

    // Define algorithm.
    Teuchos::ParameterList parlist;
    std::string stepname = "Composite Step";
    parlist.sublist("Step").sublist(stepname).sublist("Optimality System Solver").set("Nominal Relative Tolerance",1.e-4);
    parlist.sublist("Step").sublist(stepname).sublist("Optimality System Solver").set("Fix Tolerance",true);
    parlist.sublist("Step").sublist(stepname).sublist("Tangential Subproblem Solver").set("Iteration Limit",20);
    parlist.sublist("Step").sublist(stepname).sublist("Tangential Subproblem Solver").set("Relative Tolerance",1e-2);
    parlist.sublist("Step").sublist(stepname).set("Output Level",0);
    parlist.sublist("Status Test").set("Gradient Tolerance",1.e-12);
    parlist.sublist("Status Test").set("Constraint Tolerance",1.e-12);
    parlist.sublist("Status Test").set("Step Tolerance",1.e-18);
    parlist.sublist("Status Test").set("Iteration Limit",100);
    ROL::Algorithm<RealT> algo(stepname, parlist);

    algo.run(*x,x->dual(),*l,*c,*obj,*con,true,*outStream);

    x->axpy(-1.0,x_exact);

    if( x->norm() > 1e-6 ) {
      ++errorFlag;  
    }

    }
  catch (std::logic_error err) {
    *outStream << err.what() << "\n";
    errorFlag = -1000;
  }; // end try

  if (errorFlag != 0)
    std::cout << "End Result: TEST FAILED\n";
  else
    std::cout << "End Result: TEST PASSED\n";

  return 0;

}
Exemple #30
0
int main(int argc, char* argv[]) {

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

  // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
  int iprint = argc - 1;
  Teuchos::RCP<std::ostream> outStream;
  Teuchos::oblackholestream bhs; // outputs nothing
  if (iprint > 0 && Teuchos::rank<int>(*comm)==0)
    outStream = Teuchos::rcp(&std::cout, false);
  else
    outStream = Teuchos::rcp(&bhs, false);

  int errorFlag  = 0;

  try {
    /**********************************************************************************************/
    /************************* CONSTRUCT ROL ALGORITHM ********************************************/
    /**********************************************************************************************/
    // Get ROL parameterlist
    std::string filename = "input.xml";
    Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
    // Build ROL algorithm
    parlist->sublist("Status Test").set("Gradient Tolerance",1.e-7);
    parlist->sublist("Status Test").set("Step Tolerance",1.e-14);
    parlist->sublist("Status Test").set("Iteration Limit",100);
    /**********************************************************************************************/
    /************************* CONSTRUCT VECTORS **************************************************/
    /**********************************************************************************************/
    // Build control vectors
    int nx = 256;
    // Construct storage for optimal solution
    Teuchos::RCP<std::vector<RealT> > z_rcp  = Teuchos::rcp(new std::vector<RealT>(nx+2,0));
    Teuchos::RCP<ROL::Vector<RealT> > zp  = Teuchos::rcp(new ROL::StdVector<RealT>(z_rcp));
    Teuchos::RCP<std::vector<RealT> > x1_rcp = Teuchos::rcp(new std::vector<RealT>(nx+2,0));
    Teuchos::RCP<ROL::Vector<RealT> > x1p = Teuchos::rcp(new ROL::StdVector<RealT>(x1_rcp));
    Teuchos::RCP<std::vector<RealT> > x2_rcp = Teuchos::rcp(new std::vector<RealT>(nx+2,0));
    Teuchos::RCP<ROL::Vector<RealT> > x2p = Teuchos::rcp(new ROL::StdVector<RealT>(x2_rcp));
    Teuchos::RCP<std::vector<RealT> > x3_rcp = Teuchos::rcp(new std::vector<RealT>(nx+2,0));
    Teuchos::RCP<ROL::Vector<RealT> > x3p = Teuchos::rcp(new ROL::StdVector<RealT>(x3_rcp));
    std::vector<Teuchos::RCP<ROL::Vector<RealT> > > xvec = {x1p, x2p, x3p};
    // Create vectors for derivative check
    Teuchos::RCP<std::vector<RealT> > xr_rcp = Teuchos::rcp(new std::vector<RealT>(nx+2,0));
    ROL::StdVector<RealT> xr(xr_rcp);
    Teuchos::RCP<std::vector<RealT> > d_rcp  = Teuchos::rcp(new std::vector<RealT>(nx+2,0));
    ROL::StdVector<RealT> d(d_rcp);
    for ( int i = 0; i < nx+2; i++ ) {
      (*xr_rcp)[i] = random<RealT>(comm);
      (*d_rcp)[i]  = random<RealT>(comm);
    }
    // Build state and adjoint vectors
    Teuchos::RCP<std::vector<RealT> > u_rcp = Teuchos::rcp(new std::vector<RealT>(nx,1));
    Teuchos::RCP<ROL::Vector<RealT> > up = Teuchos::rcp(new ROL::StdVector<RealT>(u_rcp));
    Teuchos::RCP<std::vector<RealT> > p_rcp = Teuchos::rcp(new std::vector<RealT>(nx,0));
    Teuchos::RCP<ROL::Vector<RealT> > pp = Teuchos::rcp(new ROL::StdVector<RealT>(p_rcp));
    /**********************************************************************************************/
    /************************* CONSTRUCT SOL COMPONENTS *******************************************/
    /**********************************************************************************************/
    // Build samplers
    int dim = 4, nSamp = 100;
    std::vector<RealT> tmp = {-1, 1};
    std::vector<std::vector<RealT> > bounds(dim,tmp);
    Teuchos::RCP<ROL::BatchManager<RealT> > bman
      = Teuchos::rcp(new ROL::StdTeuchosBatchManager<RealT,int>(comm));
    Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler
      = Teuchos::rcp(new ROL::MonteCarloGenerator<RealT>(nSamp,bounds,bman,false,false,100));
    /**********************************************************************************************/
    /************************* CONSTRUCT OBJECTIVE FUNCTION ***************************************/
    /**********************************************************************************************/
    // Build risk-averse objective function
    RealT alpha = 1.e-3;
    Teuchos::RCP<ROL::ParametrizedObjective_SimOpt<RealT> > pobjSimOpt
      = Teuchos::rcp(new Objective_BurgersControl<RealT>(alpha,nx));
    Teuchos::RCP<ROL::ParametrizedEqualityConstraint_SimOpt<RealT> > pconSimOpt
      = Teuchos::rcp(new EqualityConstraint_BurgersControl<RealT>(nx));
    pconSimOpt->setSolveParameters(*parlist);
    Teuchos::RCP<ROL::ParametrizedObjective<RealT> > pObj
      = Teuchos::rcp(new ROL::Reduced_ParametrizedObjective_SimOpt<RealT>(pobjSimOpt,pconSimOpt,up,pp));
    // Test parametrized objective functions
    *outStream << "Check Derivatives of Parametrized Objective Function\n";
    xvec[0]->set(xr);
    pObj->setParameter(sampler->getMyPoint(0));
    pObj->checkGradient(*xvec[0],d,true,*outStream);
    pObj->checkHessVec(*xvec[0],d,true,*outStream);
    /**********************************************************************************************/
    /************************* SMOOTHED CVAR 1.e-2, 1.e-4, 1.e-6 **********************************/
    /**********************************************************************************************/
    const RealT cl(0.9), cc(1), lb(-0.5), ub(0.5);
    const std::string ra = "Risk Averse", rm = "CVaR", dist = "Parabolic";
    const bool storage = true;
    RealT eps(1.e-2);
    std::vector<RealT> stat(3,0);
    Teuchos::RCP<ROL::Algorithm<RealT> > algo;
    Teuchos::RCP<ROL::StochasticProblem<RealT> > optProb;
    for (int i = 0; i < 3; ++i) {
      *outStream << "\nSOLVE SMOOTHED CONDITIONAL VALUE AT RISK WITH TRUST REGION\n";
      // Build CVaR risk measure
      Teuchos::ParameterList list;
      list.sublist("SOL").set("Stochastic Optimization Type",ra);
      list.sublist("SOL").set("Store Sampled Value and Gradient",storage);
      list.sublist("SOL").sublist("Risk Measure").set("Name",rm);
      list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Confidence Level",cl);
      list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Convex Combination Parameter",cc);
      list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Smoothing Parameter",eps);
      list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").set("Name",dist);
      list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").sublist(dist).set("Lower Bound",lb);
      list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").sublist(dist).set("Upper Bound",ub);
      // Build stochastic problem
      if ( i==0 ) { xvec[i]->zero();          }
      else        { xvec[i]->set(*xvec[i-1]); }
      optProb = Teuchos::rcp(new ROL::StochasticProblem<RealT>(list,pObj,sampler,xvec[i]));
      if ( i==0 ) { optProb->setSolutionStatistic(1);         }
      else        { optProb->setSolutionStatistic(stat[i-1]); }
      optProb->checkObjectiveGradient(d,true,*outStream);
      optProb->checkObjectiveHessVec(d,true,*outStream);
      // Run ROL algorithm
      algo = Teuchos::rcp(new ROL::Algorithm<RealT>("Trust Region",*parlist,false));
      clock_t start = clock();
      algo->run(*optProb,true,*outStream);
      *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n";
      // Get solution statistic
      stat[i] = optProb->getSolutionStatistic();
      // Update smoothing parameter
      eps *= static_cast<RealT>(1.e-2);
    }
    /**********************************************************************************************/
    /************************* NONSMOOTH PROBLEM **************************************************/
    /**********************************************************************************************/
    *outStream << "\nSOLVE NONSMOOTH CVAR PROBLEM WITH BUNDLE TRUST REGION\n";
    Teuchos::ParameterList list;
    list.sublist("SOL").set("Stochastic Optimization Type",ra);
    list.sublist("SOL").set("Store Sampled Value and Gradient",storage);
    list.sublist("SOL").sublist("Risk Measure").set("Name",rm);
    list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Confidence Level",cl);
    list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Convex Combination Parameter",cc);
    list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Smoothing Parameter",0.);
    list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").set("Name","Dirac");
    list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").sublist("Dirac").set("Location",0.);
    // Build stochastic problem
    zp->set(*xvec[2]);
    optProb = Teuchos::rcp(new ROL::StochasticProblem<RealT>(list,pObj,sampler,zp));
    optProb->setSolutionStatistic(stat[2]);
    optProb->checkObjectiveGradient(d,true,*outStream);
    optProb->checkObjectiveHessVec(d,true,*outStream);
    // Run ROL algorithm
    parlist->sublist("Status Test").set("Iteration Limit",1000);
    parlist->sublist("Step").sublist("Bundle").set("Epsilon Solution Tolerance",1.e-7);
    algo = Teuchos::rcp(new ROL::Algorithm<RealT>("Bundle",*parlist,false));
    clock_t start = clock();
    algo->run(*optProb,true,*outStream);
    *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n";
    /**********************************************************************************************/
    /************************* COMPUTE ERROR ******************************************************/
    /**********************************************************************************************/
    Teuchos::RCP<ROL::Vector<RealT> > cErr = zp->clone();
    RealT zstat = optProb->getSolutionStatistic();
    *outStream << "\nSUMMARY:\n";
    *outStream << "  ---------------------------------------------\n";
    *outStream << "    True Value-At-Risk    = " << zstat << "\n";
    *outStream << "  ---------------------------------------------\n";
    RealT VARerror  = std::abs(zstat-stat[0]);
    cErr->set(*xvec[0]); cErr->axpy(-1.0,*zp);
    RealT CTRLerror = cErr->norm();
    RealT TOTerror1 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
    *outStream << "    Value-At-Risk (1.e-2) = " <<   stat[0] << "\n";
    *outStream << "    Value-At-Risk Error   = " <<  VARerror << "\n";
    *outStream << "    Control Error         = " << CTRLerror << "\n";
    *outStream << "    Total Error           = " << TOTerror1 << "\n";
    *outStream << "  ---------------------------------------------\n";
    VARerror  = std::abs(zstat-stat[1]);
    cErr->set(*xvec[1]); cErr->axpy(-1.0,*zp);
    CTRLerror = cErr->norm();
    RealT TOTerror2 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
    *outStream << "    Value-At-Risk (1.e-4) = " <<   stat[1] << "\n";
    *outStream << "    Value-At-Risk Error   = " <<  VARerror << "\n";
    *outStream << "    Control Error         = " << CTRLerror << "\n";
    *outStream << "    Total Error           = " << TOTerror2 << "\n";
    *outStream << "  ---------------------------------------------\n";
    VARerror  = std::abs(zstat-stat[2]);
    cErr->set(*xvec[2]); cErr->axpy(-1.0,*zp);
    CTRLerror = cErr->norm();
    RealT TOTerror3 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
    *outStream << "    Value-At-Risk (1.e-6) = " <<   stat[2] << "\n";
    *outStream << "    Value-At-Risk Error   = " <<  VARerror << "\n";
    *outStream << "    Control Error         = " << CTRLerror << "\n";
    *outStream << "    Total Error           = " << TOTerror3 << "\n";
    *outStream << "  ---------------------------------------------\n\n";
    // Comparison
    errorFlag += ((TOTerror1 < 90.*TOTerror2) && (TOTerror2 < 90.*TOTerror3)) ? 1 : 0;

    // Output controls
    std::ofstream control;
    control.open("example04_control.txt");
    for (int n = 0; n < nx+2; n++) {
      control << std::scientific << std::setprecision(15)
              << std::setw(25) << static_cast<RealT>(n)/static_cast<RealT>(nx+1)
              << std::setw(25) << (*z_rcp)[n]
              << std::endl;
    }
    control.close();

  }
  catch (std::logic_error err) {
    *outStream << err.what() << "\n";
    errorFlag = -1000;
  }; // end try

  if (errorFlag != 0)
    std::cout << "End Result: TEST FAILED\n";
  else
    std::cout << "End Result: TEST PASSED\n";

  return 0;
}