Exemple #1
0
Teuchos::RCP<Anasazi::SolverManager<Scalar,MV,OP> >
build_eigsolver(const Teuchos::RCP<const Teuchos::Comm<int> > &comm,
             Teuchos::ParameterList& test_params,
             Teuchos::RCP<Anasazi::Eigenproblem<Scalar,MV,OP> > problem)
{
  typedef Anasazi::Eigenproblem<Scalar,MV,OP> AEigProb;
  Teuchos::RCP<Anasazi::SolverManager<Scalar,MV,OP> > solver;

  Teuchos::ParameterList aparams;
  if (test_params.isSublist("Anasazi")) {
    aparams = test_params.sublist("Anasazi");
  }

  std::string solver_type("not specified");
  Ifpack2::getParameter(test_params, "eigen_solver_type", solver_type);
  if (solver_type == "BlockKrylovSchur") {
    // if (comm->getRank() == 0) std::cout << aparams << std::endl;
    solver = Teuchos::rcp(new Anasazi::BlockKrylovSchurSolMgr<Scalar,MV,OP>(problem,aparams));
  }
  else if (solver_type == "not specified") {
    throw std::runtime_error("Error in build_eigsolver: solver_type not specified.");
  }
  else {
    std::ostringstream os;
    os << "Error in build_eigsolver: 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;
}
// ****************************************************************
// ****************************************************************
Teuchos::RCP<NOX::StatusTest::Generic> Thyra::NOXNonlinearSolver::
buildStatusTests(Teuchos::ParameterList& p)
{
  Teuchos::RCP<NOX::StatusTest::Generic> status_test;

  NOX::Utils utils(p.sublist("Printing"));

  if (p.isSublist("Status Tests")) {
    status_test =
      NOX::StatusTest::buildStatusTests(p.sublist("Status Tests"), utils);
  }
  else { // Default status test
    Teuchos::RCP<NOX::StatusTest::NormF> absresid =
      Teuchos::rcp(new NOX::StatusTest::NormF(1.0e-8));
    Teuchos::RCP<NOX::StatusTest::NormWRMS> wrms =
      Teuchos::rcp(new NOX::StatusTest::NormWRMS(1.0e-2, 1.0e-8));
    Teuchos::RCP<NOX::StatusTest::Combo> converged =
      Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::AND));
    converged->addStatusTest(absresid);
    converged->addStatusTest(wrms);
    Teuchos::RCP<NOX::StatusTest::MaxIters> maxiters =
      Teuchos::rcp(new NOX::StatusTest::MaxIters(20));
    Teuchos::RCP<NOX::StatusTest::FiniteValue> fv =
      Teuchos::rcp(new NOX::StatusTest::FiniteValue);
    Teuchos::RCP<NOX::StatusTest::Combo> combo =
      Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::OR));
    combo->addStatusTest(fv);
    combo->addStatusTest(converged);
    combo->addStatusTest(maxiters);

    status_test = combo;
  }

  return status_test;
}
Exemple #3
0
//=============================================================================
int Amesos_Klu::SetParameters( Teuchos::ParameterList &ParameterList ) {

  // ========================================= //
  // retrive KLU's parameters from list.       //
  // default values defined in the constructor //
  // ========================================= //

  // retrive general parameters

  SetStatusParameters( ParameterList );
  SetControlParameters( ParameterList );

  if (ParameterList.isParameter("TrustMe") ) 
    TrustMe_ = ParameterList.get<bool>( "TrustMe" );

#if 0

  unused for now

  if (ParameterList.isSublist("Klu") ) {
    Teuchos::ParameterList KluParams = ParameterList.sublist("Klu") ;
  }
#endif

  return 0;
}
Exemple #4
0
  void ParameterListInterpreter<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::SetParameterList(const Teuchos::ParameterList& paramList) {
    Cycle_     = Hierarchy::GetDefaultCycle();
    blockSize_ = 1;

    if (paramList.isSublist("Hierarchy"))
      SetFactoryParameterList(paramList);
    else
      SetEasyParameterList(paramList);
  }
Teuchos::RCP<Tpetra::Operator<Scalar,LocalOrdinal,GlobalOrdinal,Node> >
build_precond (Teuchos::ParameterList& test_params,
               const Teuchos::RCP<const Tpetra::CrsMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node> >& A)
{
  using Teuchos::FancyOStream;
  using Teuchos::getFancyOStream;
  using Teuchos::OSTab;
  using Teuchos::RCP;
  using Teuchos::rcpFromRef;
  using std::cout;
  using std::endl;
  typedef Tpetra::RowMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node> row_matrix_type;
  Teuchos::Time timer("precond");
  const int myRank = A->getRowMap ()->getComm ()->getRank ();

  RCP<FancyOStream> out = getFancyOStream (rcpFromRef (cout));

  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<row_matrix_type> (prec_name, A);

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

  if (myRank == 0) {
    *out << "Configuring, initializing, and computing Ifpack2 preconditioner" << endl;
  }
  {
    OSTab tab (*out);
    prec->setParameters (tif_params);
    prec->initialize ();
    {
      Teuchos::TimeMonitor timeMon (timer);
      prec->compute ();
    }
    if (myRank == 0) {
      *out << "Finished computing Ifpack2 preconditioner" << endl;
      OSTab tab2 (*out);
      *out << "Time (s): " << timer.totalElapsedTime () << endl;
    }
  }
  if (myRank == 0) {
    *out << "Preconditioner attributes:" << endl;
    OSTab tab (*out);
    prec->describe (*out, Teuchos::VERB_LOW);
  }

  return prec;
}
Exemple #6
0
void panzer::setupInitialConditionFieldManagers(WorksetContainer & wkstContainer,
						const std::vector<Teuchos::RCP<panzer::PhysicsBlock> >& physicsBlocks,
						const panzer::ClosureModelFactory_TemplateManager<panzer::Traits>& cm_factory,
						const Teuchos::ParameterList& ic_block_closure_models,
						const panzer::LinearObjFactory<panzer::Traits>& lo_factory,
						const Teuchos::ParameterList& user_data,
						const bool write_graphviz_file,
						const std::string& graphviz_file_prefix,
						std::map< std::string, Teuchos::RCP< PHX::FieldManager<panzer::Traits> > >& phx_ic_field_managers)
{
  std::vector<Teuchos::RCP<panzer::PhysicsBlock> >::const_iterator blkItr;
  for (blkItr=physicsBlocks.begin();blkItr!=physicsBlocks.end();++blkItr) {
    Teuchos::RCP<panzer::PhysicsBlock> pb = *blkItr;
    std::string blockId = pb->elementBlockID();

    // build a field manager object
    Teuchos::RCP<PHX::FieldManager<panzer::Traits> > fm 
          = Teuchos::rcp(new PHX::FieldManager<panzer::Traits>);
    
    // Choose model sublist for this element block
    std::string closure_model_name = "";
    if (ic_block_closure_models.isSublist(blockId))
      closure_model_name = blockId;
    else if (ic_block_closure_models.isSublist("Default"))
      closure_model_name = "Default";
    else 
      TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Failed to find initial condition for element block \"" << blockId << "\".  You must provide an initial condition for each element block or set a default!" << ic_block_closure_models);

    // use the physics block to register evaluators
    pb->buildAndRegisterInitialConditionEvaluators(*fm, cm_factory, closure_model_name, ic_block_closure_models, lo_factory, user_data);

    // build the setup data using passed in information
    Traits::SetupData setupData;
    setupData.worksets_ = wkstContainer.getVolumeWorksets(blockId);

    fm->postRegistrationSetup(setupData);
    phx_ic_field_managers[blockId] = fm;
    
    if (write_graphviz_file)
      fm->writeGraphvizFile(graphviz_file_prefix+"IC_"+blockId);
  }
}
  Teuchos::RCP<Method<Epetra_MultiVector,Epetra_Operator> > EpetraMVMethodFactory::create( const Teuchos::ParameterList& params )
  {
    TEUCHOS_TEST_FOR_EXCEPTION(!params.isSublist( "Reduced Basis Method" ), std::invalid_argument, "Reduced Basis Method sublist does not exist!");

    // Get the "Reduced Basis Method" sublist.
    const Teuchos::ParameterList& rbmethod_params = params.sublist( "Reduced Basis Method" );

    // Get the file format type
    std::string method = Teuchos::getParameter<std::string>( const_cast<Teuchos::ParameterList&>(rbmethod_params),
                                                             "Method" );

    Teuchos::RCP< Method<Epetra_MultiVector,Epetra_Operator> > RBMethod;

    // POD computed using exact SVD through LAPACK
    if ( method == "Lapack POD" ) {
      RBMethod = Teuchos::rcp( new LapackPOD() );
    } 
    // Inexact POD computed using inexact SVD through Anasazi
    // IncSVDPOD uses Anasazi utility classes, while AnasaziPOD uses Anasazi for the solution
    else if ( method == "IncSVD POD" ) {
      std::string incsvdmethod = rbmethod_params.get<std::string>("IncSVD Method");
      if ( incsvdmethod == "Single/UDV" ) {
        RBMethod = Teuchos::rcp( new ISVD_SingleUDV() );
      }
      else if ( incsvdmethod == "MultiCD/UDV" ) {
        RBMethod = Teuchos::rcp( new ISVD_MultiCDUDV() );
      }
      else if ( incsvdmethod == "MultiSDA/UDV" ) {
        RBMethod = Teuchos::rcp( new ISVD_MultiSDAUDV() );
      }
      else if ( incsvdmethod == "MultiSDB/UDV" ) {
        RBMethod = Teuchos::rcp( new ISVD_MultiSDBUDV() );
      }
    } 
    else if ( method == "StSVD/RTR") {
      RBMethod = Teuchos::rcp( new StSVDRTR() );
    }
    else if ( method == "Anasazi POD" ) {
      RBMethod = Teuchos::rcp( new AnasaziPOD() );
    } else 
    {
      std::string err_str = "Reduced basis method, 'Method = " + method + "', is not recognized!";
      TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, err_str);
    }
    //
    // Return the method created
    //
    return RBMethod;
  }  
Exemple #8
0
//=============================================================================
// Default values are defined in the constructor.
int Amesos_Lapack::SetParameters( Teuchos::ParameterList &ParameterList ) 
{
  // retrive general parameters
  SetStatusParameters( ParameterList );

  SetControlParameters( ParameterList );

  bool Equilibrate = true;
  if (ParameterList.isSublist("Lapack") ) {
    const Teuchos::ParameterList& LAPACKParams = ParameterList.sublist("Lapack") ;
    if ( LAPACKParams.isParameter("Equilibrate") )
      Equilibrate = LAPACKParams.get<bool>("Equilibrate");
  }
  DenseSolver_.FactorWithEquilibration(Equilibrate);

  return(0);
}
Exemple #9
0
Teuchos::RCP<Belos::SolverManager<Scalar,MV,OP> >
build_solver(Teuchos::ParameterList& test_params,
             Teuchos::RCP<Belos::LinearProblem<Scalar,MV,OP> > problem)
{
  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::rcp(&bparams,false);

  std::string solver_type("not specified");
  Ifpack2::getParameter(test_params, "solver_type", solver_type);
  if (solver_type == "PseudoBlockCG") {
    solver = Teuchos::rcp(new Belos::PseudoBlockCGSolMgr<Scalar,MV,OP>(problem,rcpparams));
  }
  else if (solver_type == "BlockCG") {
    solver = Teuchos::rcp(new Belos::BlockCGSolMgr<Scalar,MV,OP>(problem,rcpparams));
  }
// PseudoBlockGmres does not work right now with QD
#ifndef USING_QD
  else if (solver_type == "PseudoBlockGmres") {
    solver = Teuchos::rcp(new Belos::PseudoBlockGmresSolMgr<Scalar,MV,OP>(problem,rcpparams));
  }
#endif
  else if (solver_type == "BlockGmres") {
    solver = Teuchos::rcp(new Belos::BlockGmresSolMgr<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, BlockCG, PesudoBlockGmres, BlockGmres, TFQMR.";
    std::string str = os.str();
    throw std::runtime_error(str);
  }

  return solver;
}
Exemple #10
0
Teuchos::RCP<Tpetra::Operator<Scalar,LocalOrdinal,GlobalOrdinal,Node> >
build_precond(Teuchos::ParameterList& test_params,
              const Teuchos::RCP<const Tpetra::CrsMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node,LocalMatVec,LocalMatSolve> >& 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;
}
Exemple #11
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 #12
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);
  }
  
}
Exemple #13
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< std::vector< Teuchos::RCP<PHX::Evaluator<panzer::Traits> > > > 
Example::ModelFactory<EvalT>::
buildClosureModels(const std::string& model_id,
		   const Teuchos::ParameterList& models, 
		   const panzer::FieldLayoutLibrary& fl,
		   const Teuchos::RCP<panzer::IntegrationRule>& ir,
		   const Teuchos::ParameterList& default_params,
		   const Teuchos::ParameterList& user_data,
		   const Teuchos::RCP<panzer::GlobalData>& global_data,
		   PHX::FieldManager<panzer::Traits>& fm) const
{
  using std::string;
  using std::vector;
  using Teuchos::RCP;
  using Teuchos::rcp;
  using Teuchos::ParameterList;
  using PHX::Evaluator;

  RCP< vector< RCP<Evaluator<panzer::Traits> > > > evaluators = 
    rcp(new vector< RCP<Evaluator<panzer::Traits> > > );

  if (!models.isSublist(model_id)) {
    models.print(std::cout);
    std::stringstream msg;
    msg << "Falied to find requested model, \"" << model_id 
	<< "\", for equation set:\n" << std::endl;
    TEUCHOS_TEST_FOR_EXCEPTION(!models.isSublist(model_id), std::logic_error, msg.str());
  }

  std::vector<Teuchos::RCP<const panzer::PureBasis> > bases;
  fl.uniqueBases(bases);

  const ParameterList& my_models = models.sublist(model_id);

  for (ParameterList::ConstIterator model_it = my_models.begin(); 
       model_it != my_models.end(); ++model_it) {
    
    bool found = false;
    
    const std::string key = model_it->first;
    ParameterList input;
    const Teuchos::ParameterEntry& entry = model_it->second;
    const ParameterList& plist = Teuchos::getValue<Teuchos::ParameterList>(entry);

    if (plist.isType<double>("Value")) {
      { // at IP
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	input.set("Data Layout", ir->dl_scalar);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new panzer::Constant<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      
      for (std::vector<Teuchos::RCP<const panzer::PureBasis> >::const_iterator basis_itr = bases.begin();
	   basis_itr != bases.end(); ++basis_itr) { // at BASIS
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	Teuchos::RCP<const panzer::BasisIRLayout> basis = basisIRLayout(*basis_itr,*ir);
	input.set("Data Layout", basis->functional);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new panzer::Constant<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      found = true;
    }

    if (plist.isType<std::string>("Type")) {
      const std::string type = plist.get<std::string>("Type");
      if (type == "SIMPLE SOURCE") {
	RCP<Evaluator<panzer::Traits> > e = rcp(new Example::SimpleSource<EvalT,panzer::Traits>(key, *ir));
	evaluators->push_back(e);
        found = true;
      } else if (type == "EXACT") {
        RCP<Evaluator<panzer::Traits> > e = rcp(new Example::Solution<EvalT,panzer::Traits>(key, *ir));
        evaluators->push_back(e);
        found = true;
      } else if (type == "EXACT nonlinear Robin") {
        RCP<Evaluator<panzer::Traits> > e = rcp(new Example::Solution<EvalT,panzer::Traits>(key, *ir, false));
        evaluators->push_back(e);
        found = true;
      } else if (type == "ERROR_CALC") {
        {
          std::vector<std::string> values(2);
          values[0] = plist.get<std::string>("Field A");
          values[1] = plist.get<std::string>("Field B");
  
          std::vector<double> scalars(2); 
          scalars[0] = 1.0; 
          scalars[1] = -1.0;
  
          Teuchos::ParameterList p;
          p.set("Sum Name", key + "_DIFF");
          p.set<RCP<std::vector<std::string> > >("Values Names", Teuchos::rcpFromRef(values));
          p.set<RCP<const std::vector<double> > >("Scalars", Teuchos::rcpFromRef(scalars));
          p.set("Data Layout", ir->dl_scalar);
  
          RCP<Evaluator<panzer::Traits> > e = rcp(new panzer::Sum<EvalT,panzer::Traits>(p));
          evaluators->push_back(e);
        }
        {
          std::vector<std::string> values(2);
          values[0] = key + "_DIFF";
          values[1] = key + "_DIFF";
  
          Teuchos::ParameterList p;
          p.set("Product Name",key);
          p.set<RCP<std::vector<std::string> > >("Values Names",Teuchos::rcpFromRef(values));
          p.set("Data Layout",ir->dl_scalar);
  
          RCP<Evaluator<panzer::Traits> > e = rcp(new panzer::Product<EvalT,panzer::Traits>(p));
          evaluators->push_back(e);
        }
        found = true;
      }
    }

    if ( ! found) {
      std::stringstream msg;
      msg << "ClosureModelFactory failed to build evaluator for key \"" << key 
	  << "\"\nin model \"" << model_id 
	  << "\".  Please correct the type or add support to the \nfactory." <<std::endl;
      TEUCHOS_TEST_FOR_EXCEPTION(!found, std::logic_error, msg.str());
    }

  }

  return evaluators;
}
    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 #16
0
void NOX::Utils::reset(Teuchos::ParameterList& p)
{
    using namespace Teuchos;

    // "Output Information" may be stored as a sublist, an int, or as
    // a NOX::Utils::MsgType
    if (p.isSublist("Output Information")) {

        ParameterList& printList = p.sublist("Output Information");
        typedef std::map<std::string, NOX::Utils::MsgType> OptionMap;
        OptionMap output_options;
        output_options["Error"] = NOX::Utils::Error;
        output_options["Warning"] = NOX::Utils::Warning;
        output_options["Outer Iteration"] = NOX::Utils::OuterIteration;
        output_options["Inner Iteration"] = NOX::Utils::InnerIteration;
        output_options["Parameters"] = NOX::Utils::Parameters;
        output_options["Details"] = NOX::Utils::Details;
        output_options["Outer Iteration StatusTest"] = NOX::Utils::OuterIterationStatusTest;
        output_options["Linear Solver Details"] = NOX::Utils::LinearSolverDetails;
        output_options["Test Details"] = NOX::Utils::TestDetails;
        output_options["Stepper Iteration"] = NOX::Utils::StepperIteration;
        output_options["Stepper Details"] = NOX::Utils::StepperDetails;
        output_options["Stepper Parameters"] = NOX::Utils::StepperParameters;
        output_options["Debug"] = NOX::Utils::Debug;

        bool add_test = false;
        OptionMap::const_iterator start = output_options.begin();
        OptionMap::const_iterator stop = output_options.end();
        for (OptionMap::const_iterator i = start; i != stop; ++i) {
            add_test = printList.get(i->first, false);
            if (add_test)
                printTest += i->second;
        }
    }
    else if (isParameterType<NOX::Utils::MsgType>(p, "Output Information"))
        printTest = get<NOX::Utils::MsgType>(p, "Output Information");
    else
        printTest = p.get("Output Information", 0xf);

#ifdef HAVE_MPI
    if (p.isParameter("MyPID"))
        myPID = p.get("MyPID", 0);
    else {
        // We have to check to ensure MPI has been initialized before calling
        // MPI_Comm_rank. Relates to bug 2566. - KL, 17 Sept 2006.
        int mpiIsRunning = 0;
        MPI_Initialized(&mpiIsRunning);
        if (mpiIsRunning)
        {
            MPI_Comm_rank(MPI_COMM_WORLD, &myPID);
        }
        else
        {
            myPID=0;
        }
        // Set the default in the parameter list
        p.get("MyPID", myPID);
    }
#else
    myPID = p.get("MyPID", 0);
#endif
    printProc = p.get("Output Processor", 0);
    precision = p.get("Output Precision", 3);

    // Output streams
    blackholeStream = Teuchos::rcp(new Teuchos::oblackholestream);

    if (p.INVALID_TEMPLATE_QUALIFIER
            isType< Teuchos::RCP<std::ostream> >("Output Stream"))
        printStream =
            (p).INVALID_TEMPLATE_QUALIFIER
            get< Teuchos::RCP<std::ostream> >("Output Stream");
    else
        printStream = Teuchos::rcp(&(std::cout), false);
    myStream = (myPID == printProc) ? printStream : blackholeStream;

    if (p.INVALID_TEMPLATE_QUALIFIER
            isType< Teuchos::RCP<std::ostream> >("Error Stream"))
        errorStream =
            (p).INVALID_TEMPLATE_QUALIFIER
            get< Teuchos::RCP<std::ostream> >("Error Stream");
    else
        errorStream = Teuchos::rcp(&(std::cerr), false);
}
Exemple #17
0
//=============================================================================
int Amesos_Mumps::SetParameters( Teuchos::ParameterList & ParameterList)
{
  // ========================================= //
  // retrive MUMPS' parameters from list.      //
  // default values defined in the constructor //
  // ========================================= //
  
  // retrive general parameters

  SetStatusParameters(ParameterList);

  SetControlParameters(ParameterList);

  if (ParameterList.isParameter("NoDestroy"))
    NoDestroy_ = ParameterList.get<bool>("NoDestroy");
  
  // can be use using mumps sublist, via "ICNTL(2)"
  //  if (debug_) 
  //    MDS.ICNTL(2) = 6; // Turn on Mumps verbose output 

  // retrive MUMPS' specific parameters
  
  if (ParameterList.isSublist("mumps")) 
  {
    Teuchos::ParameterList MumpsParams = ParameterList.sublist("mumps") ;

    // ICNTL
    for (int i = 1 ; i <= 40 ; ++i)
    {
      char what[80];
      sprintf(what, "ICNTL(%d)", i);
      if (MumpsParams.isParameter(what)) 
        SetICNTL(i, MumpsParams.get<int>(what));
    }

    // CNTL
    for (int i = 1 ; i <= 5 ; ++i)
    {
      char what[80];
      sprintf(what, "CNTL(%d)", i);
      if (MumpsParams.isParameter(what)) 
        SetCNTL(i, MumpsParams.get<double>(what));
    }

    // ordering
     if (MumpsParams.isParameter("PermIn")) 
     {
      int* PermIn = 0;
      PermIn = MumpsParams.get<int*>("PermIn");
      if (PermIn) SetOrdering(PermIn);
     }
     // Col scaling
     if (MumpsParams.isParameter("ColScaling")) 
     {
       double * ColSca = 0;
       ColSca = MumpsParams.get<double *>("ColScaling");
       if (ColSca) SetColScaling(ColSca);
     }
     // Row scaling
     if (MumpsParams.isParameter("RowScaling")) 
     {
       double * RowSca = 0;
       RowSca = MumpsParams.get<double *>("RowScaling");
       if (RowSca) SetRowScaling(RowSca);
     }
     // that's all folks
  }  

  return(0);
}
Exemple #18
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;

}
Teuchos::RCP< std::vector< Teuchos::RCP<PHX::Evaluator<panzer::Traits> > > >
user_app::MyModelFactory<EvalT>::
buildClosureModels(const std::string& model_id,
                   const Teuchos::ParameterList& models,
                   const panzer::FieldLayoutLibrary& fl,
                   const Teuchos::RCP<panzer::IntegrationRule>& ir,
                   const Teuchos::ParameterList& default_params,
                   const Teuchos::ParameterList& user_data,
                   const Teuchos::RCP<panzer::GlobalData>& global_data,
                   PHX::FieldManager<panzer::Traits>& fm) const
{

    using std::string;
    using std::vector;
    using Teuchos::RCP;
    using Teuchos::rcp;
    using Teuchos::ParameterList;
    using PHX::Evaluator;

    RCP< vector< RCP<Evaluator<panzer::Traits> > > > evaluators =
        rcp(new vector< RCP<Evaluator<panzer::Traits> > > );

    if (!models.isSublist(model_id)) {
        models.print(std::cout);
        std::stringstream msg;
        msg << "Falied to find requested model, \"" << model_id
            << "\", for equation set:\n" << std::endl;
        TEUCHOS_TEST_FOR_EXCEPTION(!models.isSublist(model_id), std::logic_error, msg.str());
    }

    std::vector<Teuchos::RCP<const panzer::PureBasis> > bases;
    fl.uniqueBases(bases);

    const ParameterList& my_models = models.sublist(model_id);

    for (ParameterList::ConstIterator model_it = my_models.begin();
            model_it != my_models.end(); ++model_it) {

        bool found = false;

        const std::string key = model_it->first;
        ParameterList input;
        const Teuchos::ParameterEntry& entry = model_it->second;
        const ParameterList& plist = Teuchos::getValue<Teuchos::ParameterList>(entry);

        if (plist.isType<std::string>("Type")) {

            if (plist.get<std::string>("Type") == "Parameter") {
                TEUCHOS_ASSERT(!plist.isParameter("Value"));
                // Defaults for backward compatibility
                std::string parameter_name = key;
                std::string field_name = key;
                if (plist.isType<std::string>("Parameter Name"))
                    parameter_name = plist.get<std::string>("Parameter Name");
                if (plist.isType<std::string>("Field Name"))
                    field_name = plist.get<std::string>("Field Name");

                {   // at IP
                    RCP< Evaluator<panzer::Traits> > e =
                        rcp(new panzer::Parameter<EvalT,panzer::Traits>(parameter_name,field_name,ir->dl_scalar,*global_data->pl));
                    evaluators->push_back(e);
                }

                for (std::vector<Teuchos::RCP<const panzer::PureBasis> >::const_iterator basis_itr = bases.begin();
                        basis_itr != bases.end(); ++basis_itr) { // at BASIS
                    Teuchos::RCP<const panzer::BasisIRLayout> basis = basisIRLayout(*basis_itr,*ir);
                    RCP< Evaluator<panzer::Traits> > e =
                        rcp(new panzer::Parameter<EvalT,panzer::Traits>(parameter_name,field_name,basis->functional,*global_data->pl));
                    evaluators->push_back(e);
                }

                found = true;

                continue;
            }
            else if (plist.get<std::string>("Type") == "Distributed Parameter") {
                // sanity check
                TEUCHOS_ASSERT(distr_param_lof!=Teuchos::null);

                // build a nodal basis
                Teuchos::RCP<const panzer::PureBasis> nodal_basis
                    = Teuchos::rcp(new panzer::PureBasis("HGrad",1,bases[0]->numCells(),
                                   bases[0]->getCellTopology()));

                {
                    Teuchos::RCP<std::vector<std::string> > dof_names = Teuchos::rcp(new std::vector<std::string>);
                    dof_names->push_back(key);

                    ParameterList p("Gather");
                    p.set("Basis", nodal_basis);
                    p.set("DOF Names", dof_names);
                    p.set("Indexer Names", dof_names);
                    p.set("Sensitivities Name", key);
                    p.set("Disable Sensitivities", false);
                    p.set("Gather Seed Index", 0);
                    p.set("Global Data Key", key);

                    RCP< PHX::Evaluator<panzer::Traits> > e = distr_param_lof->buildGatherDomain<EvalT>(p);

                    evaluators->push_back(e);
                }

                {
                    ParameterList p;
                    p.set("Name", key);
                    p.set("Basis", basisIRLayout(nodal_basis,*ir));
                    p.set("IR", ir);

                    RCP< PHX::Evaluator<panzer::Traits> > e = rcp(new panzer::DOF<EvalT,panzer::Traits>(p));

                    evaluators->push_back(e);
                }

                found = true;
            }
            else if (plist.get<std::string>("Type") == "Product") {
                RCP<std::vector<std::string> > valuesNames = rcp(new std::vector<std::string>);
                // Tokenize a string, put tokens in a vector
                panzer::StringTokenizer(*valuesNames,plist.get<std::string>("Term Names"));
                double scaling = 1.0;
                if(plist.isType<double>("Scaling"))
                    scaling = plist.get<double>("Scaling");

                {
                    Teuchos::ParameterList input;
                    input.set("Scaling", scaling);
                    input.set("Product Name", key);
                    input.set("Values Names", valuesNames);
                    input.set("Data Layout", ir->dl_scalar);

                    RCP< panzer::Product<EvalT,panzer::Traits> > e =
                        rcp(new panzer::Product<EvalT,panzer::Traits>(input));
                    evaluators->push_back(e);
                }

                found = true;
            }

        }
        else if (plist.isType<double>("Value")) {
            {   // at IP
                input.set("Name", key);
                input.set("Value", plist.get<double>("Value"));
                input.set("Data Layout", ir->dl_scalar);
                RCP< Evaluator<panzer::Traits> > e =
                    rcp(new panzer::Constant<EvalT,panzer::Traits>(input));
                evaluators->push_back(e);
            }
            // at BASIS
            for (std::vector<Teuchos::RCP<const panzer::PureBasis> >::const_iterator basis_itr = bases.begin();
                    basis_itr != bases.end(); ++basis_itr) {
                input.set("Name", key);
                input.set("Value", plist.get<double>("Value"));
                Teuchos::RCP<const panzer::BasisIRLayout> basis = basisIRLayout(*basis_itr,*ir);
                input.set("Data Layout", basis->functional);
                RCP< Evaluator<panzer::Traits> > e =
                    rcp(new panzer::Constant<EvalT,panzer::Traits>(input));
                evaluators->push_back(e);
            }
            found = true;
        }

        if (plist.isType<std::string>("Value")) {

            const std::string value = plist.get<std::string>("Value");

            if (key == "Global Statistics") {
                if (typeid(EvalT) == typeid(panzer::Traits::Residual)) {
                    input.set("Comm", user_data.get<Teuchos::RCP<const Teuchos::Comm<int> > >("Comm"));
                    input.set("Names", value);
                    input.set("IR", ir);
                    input.set("Global Data", global_data);
                    RCP< panzer::GlobalStatistics<EvalT,panzer::Traits> > e =
                        rcp(new panzer::GlobalStatistics<EvalT,panzer::Traits>(input));
                    evaluators->push_back(e);

                    // Require certain fields be evaluated
                    fm.template requireField<EvalT>(e->getRequiredFieldTag());
                }
                found = true;
            }
            else if(value=="Field Spy") {
                const std::string & source = plist.get<std::string>("Source Field");

                RCP<panzer::FieldSpy<EvalT,panzer::Traits> > e =
                    rcp(new panzer::FieldSpy<EvalT,panzer::Traits>(source,ir->dl_scalar));
                evaluators->push_back(e);

                fm.template requireField<EvalT>(e->getRequiredFieldTag());

                found = true;
            }
            else if(value=="Field Spy Basis") {
                const std::string & source = plist.get<std::string>("Source Field");

                RCP<panzer::FieldSpy<EvalT,panzer::Traits> > e =
                    rcp(new panzer::FieldSpy<EvalT,panzer::Traits>(source,bases[0]->functional));
                evaluators->push_back(e);

                fm.template requireField<EvalT>(e->getRequiredFieldTag());

                found = true;
            }

        }

        if (key == "Volume Integral") {

            {
                ParameterList input;
                input.set("Name", "Unit Value");
                input.set("Value", 1.0);
                input.set("Data Layout", ir->dl_scalar);
                RCP< Evaluator<panzer::Traits> > e =
                    rcp(new panzer::Constant<EvalT,panzer::Traits>(input));
                evaluators->push_back(e);
            }

            {
                ParameterList input;
                input.set("Integral Name", "Volume_Integral");
                input.set("Integrand Name", "Unit Value");
                input.set("IR", ir);

                RCP< Evaluator<panzer::Traits> > e =
                    rcp(new panzer::Integrator_Scalar<EvalT,panzer::Traits>(input));
                evaluators->push_back(e);
            }

            found = true;
        }

        if (key == "Coordinates") {
            std::string dim_str[3] = {"X","Y","Z"};
            panzer::CellData cell_data(ir->workset_size,ir->topology);
            panzer::PureBasis basis("HGrad",1,cell_data);

            for(int i=0; i<basis.dimension(); i++) {
                ParameterList input;
                input.set("Field Name", "COORD"+dim_str[i]);
                input.set("Data Layout", basis.functional);
                input.set("Dimension", i);

                RCP< Evaluator<panzer::Traits> > e =
                    rcp(new panzer::CoordinatesEvaluator<EvalT,panzer::Traits>(input));
                evaluators->push_back(e);
            }

            found = true;
        }


        if (!found) {
            std::stringstream msg;
            msg << "ClosureModelFactory failed to build evaluator for key \"" << key
                << "\"\nin model \"" << model_id
                << "\".  Please correct the type or add support to the \nfactory." <<std::endl;
            TEUCHOS_TEST_FOR_EXCEPTION(!found, std::logic_error, msg.str());
        }

    }

    return evaluators;
}
  void AdaptiveSaMLParameterListInterpreter<Scalar, LocalOrdinal, GlobalOrdinal, Node>::SetParameterList(const Teuchos::ParameterList & paramList_in) {
    Teuchos::ParameterList paramList = paramList_in;

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

    //
    // Read top-level of the parameter list
    //

    // hard-coded default values == ML defaults according to the manual
    MUELU_READ_PARAM(paramList, "ML output",                                int,                   0,       verbosityLevel);
    MUELU_READ_PARAM(paramList, "max levels",                               int,                  10,       maxLevels);
    MUELU_READ_PARAM(paramList, "PDE equations",                            int,                   1,       nDofsPerNode);

    MUELU_READ_PARAM(paramList, "coarse: max size",                         int,                 128,       maxCoarseSize);

    MUELU_READ_PARAM(paramList, "aggregation: type",                std::string,         "Uncoupled",       agg_type);
    //MUELU_READ_PARAM(paramList, "aggregation: threshold",                double,                 0.0,       agg_threshold);
    MUELU_READ_PARAM(paramList, "aggregation: damping factor",           double, (double)4/(double)3,       agg_damping);
    //MUELU_READ_PARAM(paramList, "aggregation: smoothing sweeps",            int,                   1,       agg_smoothingsweeps);
    MUELU_READ_PARAM(paramList, "aggregation: nodes per aggregate",         int,                   1,       minPerAgg);

    MUELU_READ_PARAM(paramList, "null space: type",                 std::string,   "default vectors",       nullspaceType);
    MUELU_READ_PARAM(paramList, "null space: dimension",                    int,                  -1,       nullspaceDim); // TODO: ML default not in documentation
    MUELU_READ_PARAM(paramList, "null space: vectors",                   double*,               NULL,       nullspaceVec); // TODO: ML default not in documentation

    MUELU_READ_PARAM(paramList, "energy minimization: enable",             bool,               false,       bEnergyMinimization);


    //
    // 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

    // std::cout << std::endl << "Parameter list after CreateSublists" << std::endl;
    // std::cout << paramListWithSubList << std::endl;

    int maxNbrAlreadySelected = 0;

    // Matrix option
    this->blksize_ = nDofsPerNode;

    // Translate verbosity parameter
    Teuchos::EVerbosityLevel eVerbLevel = Teuchos::VERB_NONE;
    if (verbosityLevel == 0) eVerbLevel = Teuchos::VERB_NONE;
    if (verbosityLevel >  0) eVerbLevel = Teuchos::VERB_LOW;
    if (verbosityLevel >  4) eVerbLevel = Teuchos::VERB_MEDIUM;
    if (verbosityLevel >  7) eVerbLevel = Teuchos::VERB_HIGH;
    if (verbosityLevel >  9) eVerbLevel = Teuchos::VERB_EXTREME;

    TEUCHOS_TEST_FOR_EXCEPTION(agg_type != "Uncoupled" && agg_type != "Coupled", Exceptions::RuntimeError, "MueLu::MLParameterListInterpreter::Setup(): parameter \"aggregation: type\": only 'Uncoupled' or 'Coupled' aggregation is supported.");

    // Create MueLu factories
    // RCP<NullspaceFactory>     nspFact = rcp(new NullspaceFactory());
    RCP<CoalesceDropFactory> dropFact = rcp(new CoalesceDropFactory());
    //dropFact->SetVerbLevel(toMueLuVerbLevel(eVerbLevel));

    RCP<FactoryBase> CoupledAggFact = Teuchos::null;
    if(agg_type == "Uncoupled") {
      // Uncoupled aggregation
      RCP<UncoupledAggregationFactory> CoupledAggFact2 = rcp(new UncoupledAggregationFactory());
      CoupledAggFact2->SetMinNodesPerAggregate(minPerAgg); //TODO should increase if run anything other than 1D
      CoupledAggFact2->SetMaxNeighAlreadySelected(maxNbrAlreadySelected);
      CoupledAggFact2->SetOrdering("natural");
      CoupledAggFact = CoupledAggFact2;
    } else {
      // Coupled Aggregation (default)
      RCP<CoupledAggregationFactory> CoupledAggFact2 = rcp(new CoupledAggregationFactory());
      CoupledAggFact2->SetMinNodesPerAggregate(minPerAgg); //TODO should increase if run anything other than 1D
      CoupledAggFact2->SetMaxNeighAlreadySelected(maxNbrAlreadySelected);
      CoupledAggFact2->SetOrdering("natural");
      CoupledAggFact2->SetPhase3AggCreation(0.5);
      CoupledAggFact = CoupledAggFact2;
    }
    if (verbosityLevel > 3) { // TODO fix me: Setup is a static function: we cannot use GetOStream without an object...
      *out << "========================= Aggregate option summary  =========================" << std::endl;
      *out << "min Nodes per aggregate :               " << minPerAgg << std::endl;
      *out << "min # of root nbrs already aggregated : " << maxNbrAlreadySelected << std::endl;
      *out << "aggregate ordering :                    natural" << std::endl;
      *out << "=============================================================================" << std::endl;
    }

    RCP<Factory> PFact;
    RCP<Factory> RFact;
    RCP<Factory> PtentFact = rcp( new TentativePFactory() );
    if (agg_damping == 0.0 && bEnergyMinimization == false) {
      // tentative prolongation operator (PA-AMG)
      PFact = PtentFact;
      RFact = rcp( new TransPFactory() );
    } else if (agg_damping != 0.0 && bEnergyMinimization == false) {
      // smoothed aggregation (SA-AMG)
      RCP<SaPFactory> SaPFact =  rcp( new SaPFactory() );
      SaPFact->SetParameter("sa: damping factor", ParameterEntry(agg_damping));
      PFact  = SaPFact;
      RFact  = rcp( new TransPFactory() );
    } else if (bEnergyMinimization == true) {
      // Petrov Galerkin PG-AMG smoothed aggregation (energy minimization in ML)
      PFact  = rcp( new PgPFactory() );
      RFact  = rcp( new GenericRFactory() );
    }

    RCP<RAPFactory> AcFact = rcp( new RAPFactory() );
    for (size_t i = 0; i<TransferFacts_.size(); i++) {
      AcFact->AddTransferFactory(TransferFacts_[i]); // THIS WILL BE REPLACED with a call to the MLParamterListInterpreter
    }

    //
    // Nullspace factory
    //

    // Set fine level nullspace
    // extract pre-computed nullspace from ML parameter list
    // store it in nullspace_ and nullspaceDim_
    if (nullspaceType != "default vectors") {
      TEUCHOS_TEST_FOR_EXCEPTION(nullspaceType != "pre-computed", Exceptions::RuntimeError, "MueLu::MLParameterListInterpreter: no valid nullspace (no pre-computed null space). error.");
      TEUCHOS_TEST_FOR_EXCEPTION(nullspaceDim  == -1,             Exceptions::RuntimeError, "MueLu::MLParameterListInterpreter: no valid nullspace (nullspace dim == -1). error.");
      TEUCHOS_TEST_FOR_EXCEPTION(nullspaceVec  == NULL,           Exceptions::RuntimeError, "MueLu::MLParameterListInterpreter: no valid nullspace (nullspace == NULL). You have to provide a valid fine-level nullspace in \'null space: vectors\'");

      nullspaceDim_ = nullspaceDim;
      nullspace_    = nullspaceVec;
    }

    Teuchos::RCP<NullspaceFactory> nspFact = Teuchos::rcp(new NullspaceFactory());
    nspFact->SetFactory("Nullspace", PtentFact);

    //
    // Hierarchy + FactoryManager
    //

    // Hierarchy options
    this->SetVerbLevel(toMueLuVerbLevel(eVerbLevel));
    this->numDesiredLevel_ = maxLevels;
    this->maxCoarseSize_   = maxCoarseSize;

    // init smoother
    RCP<SmootherFactory> initSmootherFact = Teuchos::null;
    if(paramList.isSublist("init smoother")) {
      ParameterList& initList = paramList.sublist("init smoother"); // TODO move this before for loop
      initSmootherFact = MLParameterListInterpreter::GetSmootherFactory(initList); // TODO: missing AFact input arg.
    } else {
      std::string ifpackType = "RELAXATION";
      Teuchos::ParameterList smootherParamList;
      smootherParamList.set("relaxation: type", "symmetric Gauss-Seidel");
      smootherParamList.set("smoother: sweeps", 1);
      smootherParamList.set("smoother: damping factor", 1.0);
      RCP<SmootherPrototype> smooProto = rcp( new TrilinosSmoother(ifpackType, smootherParamList, 0) );

      initSmootherFact = rcp( new SmootherFactory() );
      initSmootherFact->SetSmootherPrototypes(smooProto, smooProto);
    }

    //
    // Coarse Smoother
    //
    ParameterList& coarseList = paramList.sublist("coarse: list");
    //    coarseList.get("smoother: type", "Amesos-KLU"); // set default
    //RCP<SmootherFactory> coarseFact = this->GetSmootherFactory(coarseList);
    RCP<SmootherFactory> coarseFact = MLParameterListInterpreter::GetSmootherFactory(coarseList);

    // Smoothers Top Level Parameters

    RCP<ParameterList> topLevelSmootherParam = ExtractSetOfParameters(paramList, "smoother");
    // std::cout << std::endl << "Top level smoother parameters:" << std::endl;
    // std::cout << *topLevelSmootherParam << std::endl;

    //

    // Prepare factory managers
    // TODO: smootherFact can be reuse accross level if same parameters/no specific parameterList

    for (int levelID=0; levelID < maxLevels; levelID++) {

      //
      // Level FactoryManager
      //

      RCP<FactoryManager> manager = rcp(new FactoryManager());
      RCP<FactoryManager> initmanager = rcp(new FactoryManager());

      //
      // Smoothers
      //

      {
        // Merge level-specific parameters with global parameters. level-specific parameters takes precedence.
        // TODO: unit-test this part alone

        ParameterList levelSmootherParam = GetMLSubList(paramList, "smoother", levelID); // copy
        MergeParameterList(*topLevelSmootherParam, levelSmootherParam, false); /* false = do no overwrite levelSmootherParam parameters by topLevelSmootherParam parameters */
        // std::cout << std::endl << "Merged List for level  " << levelID << std::endl;
        // std::cout << levelSmootherParam << std::endl;

        //RCP<SmootherFactory> smootherFact = this->GetSmootherFactory(levelSmootherParam); // TODO: missing AFact input arg.
        RCP<SmootherFactory> smootherFact = MLParameterListInterpreter::GetSmootherFactory(levelSmootherParam); // TODO: missing AFact input arg.
        manager->SetFactory("Smoother", smootherFact);
        smootherFact->DisableMultipleCallCheck();

        initmanager->SetFactory("Smoother", initSmootherFact);
        initmanager->SetFactory("CoarseSolver", initSmootherFact);
        initSmootherFact->DisableMultipleCallCheck();

      }

      //
      // Misc
      //

      Teuchos::rcp_dynamic_cast<PFactory>(PFact)->DisableMultipleCallCheck();
      Teuchos::rcp_dynamic_cast<PFactory>(PtentFact)->DisableMultipleCallCheck();
      Teuchos::rcp_dynamic_cast<TwoLevelFactoryBase>(RFact)->DisableMultipleCallCheck();
      Teuchos::rcp_dynamic_cast<SingleLevelFactoryBase>(coarseFact)->DisableMultipleCallCheck();
      Teuchos::rcp_dynamic_cast<SingleLevelFactoryBase>(dropFact)->DisableMultipleCallCheck();
      Teuchos::rcp_dynamic_cast<SingleLevelFactoryBase>(CoupledAggFact)->DisableMultipleCallCheck();
      Teuchos::rcp_dynamic_cast<TwoLevelFactoryBase>(AcFact)->DisableMultipleCallCheck();
      Teuchos::rcp_dynamic_cast<SingleLevelFactoryBase>(nspFact)->DisableMultipleCallCheck();

      manager->SetFactory("CoarseSolver", coarseFact); // TODO: should not be done in the loop
      manager->SetFactory("Graph", dropFact);
      manager->SetFactory("Aggregates", CoupledAggFact);
      manager->SetFactory("DofsPerNode", dropFact);
      manager->SetFactory("A", AcFact);
      manager->SetFactory("P", PFact);
      manager->SetFactory("Ptent", PtentFact);
      manager->SetFactory("R", RFact);
      manager->SetFactory("Nullspace", nspFact);

      //initmanager->SetFactory("CoarseSolver", coarseFact);
      initmanager->SetFactory("Graph", dropFact);
      initmanager->SetFactory("Aggregates", CoupledAggFact);
      initmanager->SetFactory("DofsPerNode", dropFact);
      initmanager->SetFactory("A", AcFact);
      initmanager->SetFactory("P", PtentFact); // use nonsmoothed transfers
      initmanager->SetFactory("Ptent", PtentFact);
      initmanager->SetFactory("R", RFact);
      initmanager->SetFactory("Nullspace", nspFact);

      this->AddFactoryManager(levelID, 1, manager);
      this->AddInitFactoryManager(levelID, 1, initmanager);
    } // for (level loop)
  }
Teuchos::RCP< std::vector< Teuchos::RCP<PHX::Evaluator<panzer::Traits> > > > 
user_app::MyModelFactory<EvalT>::
buildClosureModels(const std::string& model_id,
		   const Teuchos::ParameterList& models, 
		   const panzer::FieldLayoutLibrary& fl,
		   const Teuchos::RCP<panzer::IntegrationRule>& ir,
		   const Teuchos::ParameterList& default_params,
		   const Teuchos::ParameterList& user_data,
		   const Teuchos::RCP<panzer::GlobalData>& global_data,
		   PHX::FieldManager<panzer::Traits>& fm) const
{

  using std::string;
  using std::vector;
  using Teuchos::RCP;
  using Teuchos::rcp;
  using Teuchos::ParameterList;
  using PHX::Evaluator;

  RCP< vector< RCP<Evaluator<panzer::Traits> > > > evaluators = 
    rcp(new vector< RCP<Evaluator<panzer::Traits> > > );

  if (!models.isSublist(model_id)) {
    models.print(std::cout);
    std::stringstream msg;
    msg << "Falied to find requested model, \"" << model_id 
	<< "\", for equation set:\n" << std::endl;
    TEUCHOS_TEST_FOR_EXCEPTION(!models.isSublist(model_id), std::logic_error, msg.str());
  }

  std::vector<Teuchos::RCP<const panzer::PureBasis> > bases;
  fl.uniqueBases(bases);

  const ParameterList& my_models = models.sublist(model_id);

  for (ParameterList::ConstIterator model_it = my_models.begin(); 
       model_it != my_models.end(); ++model_it) {
    
    bool found = false;
    
    const std::string key = model_it->first;
    ParameterList input;
    const Teuchos::ParameterEntry& entry = model_it->second;
    const ParameterList& plist = Teuchos::getValue<Teuchos::ParameterList>(entry);

    #ifdef HAVE_STOKHOS
    if (plist.isType<double>("Value") && plist.isType<double>("UQ") 
                           && plist.isParameter("Expansion")
                           && (typeid(EvalT)==typeid(panzer::Traits::SGResidual) || 
                               typeid(EvalT)==typeid(panzer::Traits::SGJacobian)) ) {
      { // at IP
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	input.set("UQ", plist.get<double>("UQ"));
	input.set("Expansion", plist.get<Teuchos::RCP<Stokhos::OrthogPolyExpansion<int,double> > >("Expansion"));
	input.set("Data Layout", ir->dl_scalar);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new user_app::ConstantModel<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      
      for (std::vector<Teuchos::RCP<const panzer::PureBasis> >::const_iterator basis_itr = bases.begin();
	   basis_itr != bases.end(); ++basis_itr) { // at BASIS
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	input.set("UQ", plist.get<double>("UQ"));
	input.set("Expansion", plist.get<Teuchos::RCP<Stokhos::OrthogPolyExpansion<int,double> > >("Expansion"));
	Teuchos::RCP<const panzer::BasisIRLayout> basis = basisIRLayout(*basis_itr,*ir);
	input.set("Data Layout", basis->functional);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new user_app::ConstantModel<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      found = true;
    }
    else 
    #endif
    if (plist.isType<std::string>("Type")) {
      
      if (plist.get<std::string>("Type") == "Parameter") {
	{ // at IP
	  RCP< Evaluator<panzer::Traits> > e = 
	    rcp(new panzer::Parameter<EvalT,panzer::Traits>(key,ir->dl_scalar,plist.get<double>("Value"),*global_data->pl));
	  evaluators->push_back(e);
	}
	
	for (std::vector<Teuchos::RCP<const panzer::PureBasis> >::const_iterator basis_itr = bases.begin();
	   basis_itr != bases.end(); ++basis_itr) { // at BASIS
	  Teuchos::RCP<const panzer::BasisIRLayout> basis = basisIRLayout(*basis_itr,*ir);
	  RCP< Evaluator<panzer::Traits> > e = 
	    rcp(new panzer::Parameter<EvalT,panzer::Traits>(key,basis->functional,plist.get<double>("Value"),*global_data->pl));
	  evaluators->push_back(e);
	}
	
	found = true;
      }
  
    }
    else if (plist.isType<double>("Value")) {
      { // at IP
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	input.set("Data Layout", ir->dl_scalar);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new user_app::ConstantModel<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      // at BASIS
      for (std::vector<Teuchos::RCP<const panzer::PureBasis> >::const_iterator basis_itr = bases.begin();
	   basis_itr != bases.end(); ++basis_itr) {
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	Teuchos::RCP<const panzer::BasisIRLayout> basis = basisIRLayout(*basis_itr,*ir);
	input.set("Data Layout", basis->functional);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new user_app::ConstantModel<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      found = true;
    }

    if (plist.isType<std::string>("Value")) {
    
      const std::string value = plist.get<std::string>("Value");

      if (key == "Global Statistics") {
	if (typeid(EvalT) == typeid(panzer::Traits::Residual)) {
	  input.set("Comm", user_data.get<Teuchos::RCP<const Teuchos::Comm<int> > >("Comm"));
	  input.set("Names", value);
	  input.set("IR", ir);
	  input.set("Global Data", global_data);
	  RCP< panzer::GlobalStatistics<EvalT,panzer::Traits> > e = 
	    rcp(new panzer::GlobalStatistics<EvalT,panzer::Traits>(input));
	  evaluators->push_back(e);
	  
	  // Require certain fields be evaluated
	  fm.template requireField<EvalT>(e->getRequiredFieldTag());
	}
	found = true;
      }

    }

    if (key == "Volume Integral") {

        {
           ParameterList input;
	   input.set("Name", "Unit Value");
	   input.set("Value", 1.0);
	   input.set("Data Layout", ir->dl_scalar);
	   RCP< Evaluator<panzer::Traits> > e = 
   	     rcp(new user_app::ConstantModel<EvalT,panzer::Traits>(input));
   	   evaluators->push_back(e);
        }

        {
           ParameterList input;
	   input.set("Integral Name", "Volume_Integral");
	   input.set("Integrand Name", "Unit Value");
	   input.set("IR", ir);

	   RCP< Evaluator<panzer::Traits> > e = 
   	     rcp(new panzer::Integrator_Scalar<EvalT,panzer::Traits>(input));
   	   evaluators->push_back(e);
        }

	found = true;
    }

    if (key == "Coordinates") {
      std::string dim_str[3] = {"X","Y","Z"};
      panzer::CellData cell_data(ir->workset_size,ir->topology);
      panzer::PureBasis basis("HGrad",1,cell_data);

      for(int i=0;i<basis.dimension();i++) {
        ParameterList input;
        input.set("Field Name", "COORD"+dim_str[i]);
        input.set("Data Layout", basis.functional);
        input.set("Dimension", i);

        RCP< Evaluator<panzer::Traits> > e = 
          rcp(new panzer::CoordinatesEvaluator<EvalT,panzer::Traits>(input));
        evaluators->push_back(e);
      }

      found = true;
    }


    if (!found) {
      std::stringstream msg;
      msg << "ClosureModelFactory failed to build evaluator for key \"" << key 
	  << "\"\nin model \"" << model_id 
	  << "\".  Please correct the type or add support to the \nfactory." <<std::endl;
      TEUCHOS_TEST_FOR_EXCEPTION(!found, std::logic_error, msg.str());
    }

  }

  return evaluators;
}
Teuchos::RCP< std::vector< Teuchos::RCP<PHX::Evaluator<panzer::Traits> > > > 
user_app::MyModelFactory<EvalT>::
buildClosureModels(const std::string& model_id,
		   const Teuchos::ParameterList& models,
		   const panzer::FieldLayoutLibrary& fl,
		   const Teuchos::RCP<panzer::IntegrationRule>& ir, 
		   const Teuchos::ParameterList& default_params,
		   const Teuchos::ParameterList& user_data,
                   const Teuchos::RCP<panzer::GlobalData>& global_data,
		   PHX::FieldManager<panzer::Traits>& fm) const
{

  using std::string;
  using std::vector;
  using Teuchos::RCP;
  using Teuchos::rcp;
  using Teuchos::ParameterList;
  using PHX::Evaluator;

  RCP< vector< RCP<Evaluator<panzer::Traits> > > > evaluators = 
    rcp(new vector< RCP<Evaluator<panzer::Traits> > > );

  if (!models.isSublist(model_id)) {
    std::stringstream msg;
    msg << "Falied to find requested model, \"" << model_id 
	<< "\", for equation set:\n" << std::endl;
    TEUCHOS_TEST_FOR_EXCEPTION(!models.isSublist(model_id), std::logic_error, msg.str());
  }

  std::vector<Teuchos::RCP<const panzer::PureBasis> > bases;
  fl.uniqueBases(bases);

  const ParameterList& my_models = models.sublist(model_id);

  for (ParameterList::ConstIterator model_it = my_models.begin(); 
       model_it != my_models.end(); ++model_it) {
    
    bool found = false;
    
    const std::string key = model_it->first;
    ParameterList input;
    const Teuchos::ParameterEntry& entry = model_it->second;
    const ParameterList& plist = Teuchos::getValue<Teuchos::ParameterList>(entry);
    
    if (plist.isType<double>("Value")) {
      { // at IP
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	input.set("Data Layout", ir->dl_scalar);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new panzer::Constant<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      for (std::vector<Teuchos::RCP<const panzer::PureBasis> >::const_iterator basis_itr = bases.begin();
	   basis_itr != bases.end(); ++basis_itr) { // at BASIS
	input.set("Name", key);
	input.set("Value", plist.get<double>("Value"));
	Teuchos::RCP<const panzer::BasisIRLayout> basis = basisIRLayout(*basis_itr,*ir);
	input.set("Data Layout", basis->functional);
	RCP< Evaluator<panzer::Traits> > e = 
	  rcp(new panzer::Constant<EvalT,panzer::Traits>(input));
	evaluators->push_back(e);
      }
      found = true;
    }

    if (plist.isType<std::string>("Value")) {
    
      const std::string value = plist.get<std::string>("Value");

      if (key == "Global Statistics") {
	if (typeid(EvalT) == typeid(panzer::Traits::Residual)) {
	  input.set("Comm", user_data.get<Teuchos::RCP<const Teuchos::Comm<int> > >("Comm"));
	  input.set("Names", value);
	  input.set("IR", ir);
	  input.set("Global Data", global_data);
	  RCP< panzer::GlobalStatistics<EvalT,panzer::Traits> > e = 
	    rcp(new panzer::GlobalStatistics<EvalT,panzer::Traits>(input));
	  evaluators->push_back(e);
	  
	  // Require certain fields be evaluated
	  fm.template requireField<EvalT>(e->getRequiredFieldTag());
	}
	found = true;
      }



    }

    if (!found) {
      std::stringstream msg;
      msg << "ClosureModelFactory failed to build evaluator for key \"" << key 
	  << "\"\nin model \"" << model_id 
	  << "\".  Please correct the type or add support to the \nfactory." <<std::endl;
      TEUCHOS_TEST_FOR_EXCEPTION(!found, std::logic_error, msg.str());
    }

  }

  return evaluators;
}
void Operator<Node>::paramsToUpper(Teuchos::ParameterList &plist, int &changed, bool rmUnderscore)
{
  changed = 0;

  // get a list of all parameter names in the list

  std::vector<std::string> paramNames ;
  Teuchos::ParameterList::ConstIterator pIter;

  pIter = plist.begin();

  while (1){
    //////////////////////////////////////////////////////////////////////
    // Compiler considered this while statement an error
    // for ( pIter = plist.begin() ; pIter != plist.end() ; pIter++ ){
    // }
    //////////////////////////////////////////////////////////////////////
    if (pIter == plist.end()) break;
    const std::string & nm = plist.name(pIter);
    paramNames.push_back(nm);
    pIter++;
  }

  // Change parameter names and values to upper case

  for (unsigned int i=0; i < paramNames.size(); i++){

    std::string origName(paramNames[i]);
    int paramNameChanged = 0;
    stringToUpper(paramNames[i], paramNameChanged, rmUnderscore);

    if (plist.isSublist(origName)){
      Teuchos::ParameterList &sublist = plist.sublist(origName);

      int sublistChanged=0;
      paramsToUpper(sublist, sublistChanged, false);

      if (paramNameChanged){

        // this didn't work, so I need to remove the old sublist
        // and create a new one
        //
        //sublist.setName(paramNames[i]);

        Teuchos::ParameterList newlist(sublist);
        plist.remove(origName);
        plist.set(paramNames[i], newlist);
      }
    }
    else if (plist.isParameter(origName)){

      std::string paramVal(plist.get<std::string>(origName));

      int paramValChanged=0;
      stringToUpper(paramVal, paramValChanged);

      if (paramNameChanged || paramValChanged){
        if (paramNameChanged){
          plist.remove(origName);
        }
        plist.set(paramNames[i], paramVal);
        changed++;
      }
    }
  } // next parameter or sublist
}
Exemple #24
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") {
QCAD::MeshRegion<EvalT, Traits>::
MeshRegion(std::string coordVecName, std::string weightsName,
	   Teuchos::ParameterList& p, 
	   const Teuchos::RCP<QCAD::MaterialDatabase> matDB,
	   const Teuchos::RCP<Albany::Layouts>& dl_ )
{
  materialDB = matDB;
  coordVecFieldname = coordVecName;
  weightsFieldname = weightsName;

  // number of quad points per cell and dimension of space
  std::vector<PHX::DataLayout::size_type> dims;
  dl = dl_;
  dl->qp_vector->dimensions(dims);
  numQPs  = dims[1];
  numDims = dims[2];

  // Restriction to element blocks
  std::string ebNameStr = p.get<std::string>("Element Block Name","");
  if(ebNameStr.length() == 0) ebNameStr = p.get<std::string>("Element Block Names","");
  if(ebNameStr.length() > 0) Albany::splitStringOnDelim(ebNameStr,',',ebNames);
  bQuantumEBsOnly = p.get<bool>("Quantum Element Blocks Only",false);

  // Restriction to coordinate ranges
  limitX = limitY = limitZ = false;
  if( p.isParameter("x min") && p.isParameter("x max") ) {
    limitX = true; TEUCHOS_TEST_FOR_EXCEPT(numDims <= 0);
    xmin = p.get<double>("x min");
    xmax = p.get<double>("x max");
  }
  if( p.isParameter("y min") && p.isParameter("y max") ) {
    limitY = true; TEUCHOS_TEST_FOR_EXCEPT(numDims <= 1);
    ymin = p.get<double>("y min");
    ymax = p.get<double>("y max");
  }
  if( p.isParameter("z min") && p.isParameter("z max") ) {
    limitZ = true; TEUCHOS_TEST_FOR_EXCEPT(numDims <= 2);
    zmin = p.get<double>("z min");
    zmax = p.get<double>("z max");
  }

  //Restriction to xy polygon
  const int polyPtDim = 2; //expect (x,y) coordinates
  int nPts = 0; 
  if( p.isSublist("XY Polygon") ) {
    Teuchos::Array<double> ar;
    Teuchos::ParameterList& polyList = p.sublist("XY Polygon");
    nPts = polyList.get<int>("Number of Points",0);
    xyPolygon.resize(nPts);

    for(int i=0; i<nPts; i++) {
      xyPolygon[i].resize(numDims);
      ar = polyList.get<Teuchos::Array<double> >( Albany::strint("Point",i) );
      TEUCHOS_TEST_FOR_EXCEPTION (ar.size() != (int)polyPtDim, Teuchos::Exceptions::InvalidParameter, std::endl 
				  << "XY-polygon point does not have " << polyPtDim << " elements" << std::endl); 
      for(std::size_t k=0; k<polyPtDim; k++) xyPolygon[i][k] = ar[k];
    }
  }
  bRestrictToXYPolygon = (nPts >= 3); //need at least three points to restrict to a polygon

  // Restriction to a level set of a field
  levelSetFieldname = p.get<std::string>("Level Set Field Name","");
  levelSetFieldMin = p.get<double>("Level Set Field Minimum", -1e100);
  levelSetFieldMax = p.get<double>("Level Set Field Maximum", +1e100);
  bRestrictToLevelSet = (levelSetFieldname.length() > 0);

}
Exemple #26
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_));
}
Exemple #27
0
  Teuchos::RCP<MueLu::TpetraOperator<Scalar,LocalOrdinal,GlobalOrdinal,Node> >
  CreateTpetraPreconditioner(const Teuchos::RCP<Tpetra::CrsMatrix  <Scalar, LocalOrdinal, GlobalOrdinal, Node> >& inA,
                             Teuchos::ParameterList& paramList,
                             const Teuchos::RCP<Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& inCoords    = Teuchos::null,
                             const Teuchos::RCP<Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& inNullspace = Teuchos::null)
  {
    typedef Scalar          SC;
    typedef LocalOrdinal    LO;
    typedef GlobalOrdinal   GO;
    typedef Node            NO;

    typedef Xpetra::MultiVector<SC,LO,GO,NO>            MultiVector;
    typedef Xpetra::Matrix<SC,LO,GO,NO>                 Matrix;
    typedef Hierarchy<SC,LO,GO,NO>                      Hierarchy;
    typedef HierarchyManager<SC,LO,GO,NO>               HierarchyManager;

    bool hasParamList = paramList.numParams();

    RCP<HierarchyManager> mueLuFactory;
    RCP<Hierarchy>        H;
    if (hasParamList) {
      mueLuFactory = rcp(new ParameterListInterpreter<SC,LO,GO,NO>(paramList));

      H = mueLuFactory->CreateHierarchy();

    } else {
      H = rcp(new Hierarchy());
    }

    // Wrap A
    RCP<Matrix> A = TpetraCrs_To_XpetraMatrix<SC,LO,GO,NO>(inA);
    H->GetLevel(0)->Set("A", A);

    // Wrap coordinates if available
    if (inCoords != Teuchos::null) {
      RCP<MultiVector> coordinates = TpetraMultiVector_To_XpetraMultiVector<SC,LO,GO,NO>(inCoords);
      H->GetLevel(0)->Set("Coordinates", coordinates);
    }

    // Wrap nullspace if available, otherwise use constants
    RCP<MultiVector> nullspace;
    if (inNullspace != Teuchos::null) {
      nullspace = TpetraMultiVector_To_XpetraMultiVector<SC,LO,GO,NO>(inNullspace);

    } else {
      int nPDE = 1;
      if (paramList.isSublist("Matrix")) {
        const Teuchos::ParameterList& operatorList = paramList.sublist("Matrix");
        if (operatorList.isParameter("PDE equations"))
          nPDE = operatorList.get<int>("PDE equations");
      }

      nullspace = Xpetra::MultiVectorFactory<SC,LO,GO,NO>::Build(A->getDomainMap(), nPDE);
      if (nPDE == 1) {
        nullspace->putScalar(Teuchos::ScalarTraits<SC>::one());

      } else {
        for (int i = 0; i < nPDE; i++) {
          Teuchos::ArrayRCP<SC> nsData = nullspace->getDataNonConst(i);
          for (int j = 0; j < nsData.size(); j++) {
            GO GID = A->getDomainMap()->getGlobalElement(j) - A->getDomainMap()->getIndexBase();

            if ((GID-i) % nPDE == 0)
              nsData[j] = Teuchos::ScalarTraits<SC>::one();
          }
        }
      }
    }
    H->GetLevel(0)->Set("Nullspace", nullspace);

    if (hasParamList)
      mueLuFactory->SetupHierarchy(*H);
    else
      H->Setup();

    return rcp(new TpetraOperator<SC,LO,GO,NO>(H));
  }