RCP<OptConvergenceTestBase> OptConvergenceTestBuilder::createConvTest(const ParameterList& params, int verb) { Tabs tab(0); PLAYA_MSG1(verb, tab << "OptConvergenceTestBuilder::createConvTest()"); Tabs tab1; PLAYA_MSG2(verb, tab1 << "params=" << params); TEUCHOS_TEST_FOR_EXCEPTION(params.name() != "Convergence Test", std::runtime_error, "OptConvTestBuilder::createConvTest() expected parameter list named " "\"Convergence Test\", got name [" << params.name() << "]"); const std::string& ctType = getParameter<string>(params, "Type"); RCP<OptConvergenceTestBase> ct; if (ctType=="Default") { PLAYA_MSG2(verb, tab1 << "found Default convergence test"); ct = rcp(new DefaultOptConvergenceTest(params)); } TEUCHOS_TEST_FOR_EXCEPTION(ct.get()==0, std::runtime_error, "OptConvTestBuilder::createConvTest() could not construct a valid " "convergence test object from parameter list " << params); return ct; }
XMLObject XMLParameterListWriter::convertParameterList( const ParameterList& p, ParameterEntry::ParameterEntryID& idCounter, EntryIDsMap& entryIDsMap, const ValidatortoIDMap& validatorIDsMap) const { XMLObject rtn(getParameterListTagName()); for (ParameterList::ConstIterator i=p.begin(); i!=p.end(); ++i){ RCP<const ParameterEntry> entry = p.getEntryRCP(i->first); if(entry->isList()){ XMLObject newPL = convertParameterList( getValue<ParameterList>(entry), idCounter, entryIDsMap, validatorIDsMap); newPL.addAttribute( getNameAttributeName(), p.name(i)); newPL.addAttribute( ParameterEntryXMLConverter::getIdAttributeName(), idCounter); entryIDsMap.insert(EntryIDsMap::value_type(entry, idCounter)); rtn.addChild(newPL); ++idCounter; } else{ rtn.addChild(ParameterEntryXMLConverterDB::convertEntry( entry, p.name(i), idCounter, validatorIDsMap)); entryIDsMap.insert(EntryIDsMap::value_type(entry, idCounter)); ++idCounter; } } return rtn; }
/** Construct with a parameter list controlling the verbosity settings */ ParameterControlledObjectWithVerbosity(const std::string& objName, const ParameterList& p) : ObjectWithClassVerbosity<X>(), verbControlParams_() { RCP<ParameterList> defaults = VerbosityTraits<X>::defaultVerbParams(); TEUCHOS_TEST_FOR_EXCEPTION(defaults->name() != objName, std::runtime_error, "mismatched ParameterList names for verbosity control: expected " << defaults->name() << ", got " << objName); TEUCHOS_TEST_FOR_EXCEPTION(defaults->name() != p.name(), std::runtime_error, "mismatched ParameterList names for verbosity control: expected " << defaults->name() << ", got " << p.name()); verbControlParams_ = rcp(new ParameterList(mergeParams(*defaults, p))); }
bool Teuchos::haveSameValues( const ParameterList& list1, const ParameterList& list2 ) { // Check that the top-level names of the two parameter lists are the same //const std::string ¶mListName1 = list1.name(); //const std::string ¶mListName2 = list2.name(); //if ( paramListName1 != paramListName2 ) { // return false; //} ParameterList::ConstIterator itr1, itr2; for( itr1 = list1.begin(), itr2 = list2.begin(); itr1 != list1.end() && itr2 != list2.end(); ++itr1, ++itr2 ) { const std::string &entryName1 = list1.name(itr1); const std::string &entryName2 = list2.name(itr2); const ParameterEntry &entry1 = list1.entry(itr1); const ParameterEntry &entry2 = list2.entry(itr2); if( entryName1 != entryName2 ) { return false; } if( entry1.isList() && entry2.isList() ) { if ( !haveSameValues( getValue<ParameterList>(entry1), getValue<ParameterList>(entry2)) ) { // Note: Above we cast to a non-const ParameterList even through we // only need a const ParameterList. We have to do this since a // non-const ParameterList is always added initially which determines // the value. return false; } } else { if( entry1.getAny() != entry2.getAny() ) { return false; } } } // Check that the two parameter lists are the same length: if ((itr1 != list1.end()) || (itr2 != list2.end())) { return false; } return true; }
void getParameterLists(const string &inputFileName, queue<ParameterList> &problems, queue<ParameterList> &comparisons, const RCP<const Teuchos::Comm<int> > & comm) { int rank = comm->getRank(); // return a parameter list of problem definitions // and a parameter list for solution comparisons Teuchos::FileInputSource inputSource(inputFileName); if(rank == 0) cout << "input file source: " << inputFileName << endl; XMLObject xmlInput; // Try to get xmlObject from inputfile try{ xmlInput = inputSource.getObject(); } catch(exception &e) { EXC_ERRMSG("Test Driver error: reading", e); // error reading input } // get the parameter lists for each model for(int i = 0; i < xmlInput.numChildren(); i++) { ParameterList plist; xmlToModelPList(xmlInput.getChild(i), plist); if(plist.name() == "Comparison") comparisons.emplace(plist); else problems.emplace(plist); } }
XMLObject XMLParameterListWriter::toXML( const ParameterList& p, RCP<const DependencySheet> depSheet) const { EntryIDsMap entryIDsMap; ValidatortoIDMap validatorIDsMap; ParameterEntry::ParameterEntryID peIDCounter = 0; //We build an initial map full of validators that are located in the //parameter list. That way we can convert the parameter entries. buildInitialValidatorMap(p, validatorIDsMap); XMLObject toReturn = convertParameterList(p, peIDCounter, entryIDsMap, validatorIDsMap); toReturn.addAttribute(getNameAttributeName(), p.name()); if(!depSheet.is_null()){ XMLObject deps = convertDependencies(depSheet, entryIDsMap, validatorIDsMap); toReturn.addChild(deps); } //Validators must be done after depencneies because dependencies might add //entries to the validator map. KLN 09/20/2010 XMLObject validators = convertValidators(p, validatorIDsMap); toReturn.addChild(validators); return toReturn; }
bool deliverEmail::submitReport(QWidget* parent, const QString reportName, const QString fileName, const QString from, const QString to, const QString cc, const QString subject, const QString body, const bool emailHTML, ParameterList &rptParams) { if (to.isEmpty()) return false; q.prepare( "SELECT submitReportToBatch( :reportname, :fromEmail, :emailAddress, :ccAddress, :subject," " :emailBody, :fileName, CURRENT_TIMESTAMP, :emailHTML) AS batch_id;" ); q.bindValue(":reportname", reportName); q.bindValue(":fileName", fileName); q.bindValue(":fromEmail", from); q.bindValue(":emailAddress", to); q.bindValue(":ccAddress", cc); q.bindValue(":subject", subject); q.bindValue(":emailBody", body); q.bindValue(":emailHTML", emailHTML); q.exec(); if (q.first()) { int batch_id = q.value("batch_id").toInt(); int counter; q.prepare( "INSERT INTO batchparam " "( batchparam_batch_id, batchparam_order," " batchparam_name, batchparam_value ) " "VALUES " "( :batchparam_batch_id, :batchparam_order," " :batchparam_name, :batchparam_value );" ); q.bindValue(":batchparam_batch_id", batch_id); for (counter = 0; counter < rptParams.count(); counter++) { q.bindValue(":batchparam_order", counter+1); q.bindValue(":batchparam_name", rptParams.name(counter)); q.bindValue(":batchparam_value", rptParams.value(counter)); q.exec(); if (q.lastError().type() != QSqlError::NoError) { systemError(parent, q.lastError().databaseText(), __FILE__, __LINE__); return false; } } q.bindValue(":batchparam_batch_id", batch_id); q.bindValue(":batchparam_order", counter+2); q.bindValue(":batchparam_name", "title"); q.bindValue(":batchparam_value", "Emailed Customer Copy"); q.exec(); if (q.lastError().type() != QSqlError::NoError) { systemError(parent, q.lastError().databaseText(), __FILE__, __LINE__); return false; } } return true; }
// ParameterList Conversion functions QScriptValue ParameterListtoScriptValue(QScriptEngine *engine, const ParameterList ¶ms) { QScriptValue obj = engine->newObject(); for(int i = 0; i < params.count(); i++) { obj.setProperty(params.name(i), ScriptToolbox::variantToScriptValue(engine, params.value(i))); } return obj; }
void BCManager::run() { if (jacT != Teuchos::null) isAdjoint = true; typedef ParameterList::ConstIterator ParamIter; for (ParamIter i = bcParams.begin(); i != bcParams.end(); ++i) { std::string const& name = bcParams.name(i); Teuchos::ParameterEntry const& entry = bcParams.entry(i); assert(entry.isList()); applyBC(Teuchos::getValue<ParameterList>(entry)); } }
QString ExportHelper::generateXML(QString qtext, QString tableElemName, ParameterList ¶ms, QString &errmsg, int xsltmapid) { if (DEBUG) qDebug("ExportHelper::generateXML(%s..., %s, %d params, errmsg, %d) entered", qPrintable(qtext.left(80)), qPrintable(tableElemName), params.size(), xsltmapid); if (DEBUG) { QStringList plist; for (int i = 0; i < params.size(); i++) plist.append("\t" + params.name(i) + ":\t" + params.value(i).toString()); qDebug("generateXML parameters:\n%s", qPrintable(plist.join("\n"))); } QDomDocument xmldoc("xtupleimport"); QDomElement rootelem = xmldoc.createElement("xtupleimport"); xmldoc.appendChild(rootelem); if (! qtext.isEmpty()) { MetaSQLQuery mql(qtext); XSqlQuery qry = mql.toQuery(params); if (qry.first()) { do { QDomElement tableElem = xmldoc.createElement(tableElemName); if (DEBUG) qDebug("generateXML starting %s", qPrintable(tableElemName)); for (int i = 0; i < qry.record().count(); i++) { QDomElement fieldElem = xmldoc.createElement(qry.record().fieldName(i)); if (qry.record().value(i).isNull()) fieldElem.appendChild(xmldoc.createTextNode("[NULL]")); else fieldElem.appendChild(xmldoc.createTextNode(qry.record().value(i).toString())); tableElem.appendChild(fieldElem); } rootelem.appendChild(tableElem); } while (qry.next()); } if (qry.lastError().type() != QSqlError::NoError) errmsg = qry.lastError().text(); } if (xsltmapid < 0) return xmldoc.toString(); else return XSLTConvertString(xmldoc.toString(), xsltmapid, errmsg); }
bool Teuchos::operator==( const ParameterList& list1, const ParameterList& list2 ) { // Check that the top-level names of the two parameter lists are the same //const std::string ¶mListName1 = list1.name(); //const std::string ¶mListName2 = list2.name(); //if ( paramListName1 != paramListName2 ) { // return false; //} ParameterList::ConstIterator itr1, itr2; for( itr1 = list1.begin(), itr2 = list2.begin(); itr1 != list1.end() && itr2 != list2.end(); ++itr1, ++itr2 ) { const std::string &entryName1 = list1.name(itr1); const std::string &entryName2 = list2.name(itr2); const ParameterEntry &entry1 = list1.entry(itr1); const ParameterEntry &entry2 = list2.entry(itr2); if( entryName1 != entryName2 ) { return false; } else if( entry1 != entry2 ) { return false; } // Note that the above statement automatically recursively compare the // sublists since ParameterList objects are stored in the 'any' variable // held by the ParameterEntry object and this same comparison operator will // be used. } // Check that the two parameter lists are the same length: if ((itr1 != list1.end()) || (itr2 != list2.end())) { return false; } return true; }
/// \brief Analyze metrics for a problem based on a range of tolerances /// /// @param metricsPlist parameter list defining tolerances /// @param problem the problem whose metrics are to be analyzed /// @param comm an RCP for a communicator /// @param[out] msg_stream a std::ostringstream stream to return information from the analysis /// /// @return returns a boolean value indicated pass/failure. static bool analyzeMetrics( const ParameterList &metricsPlist, const RCP<const Zoltan2::EvaluatePartition <basic_id_t> > &metricObject, const RCP<const Comm<int>> &comm, std::ostringstream &msg_stream) { auto type = metricsPlist.name(); if (type == "Metrics") return MetricAnalyzer::analyzePartitionMetrics( metricsPlist, metricObject, comm, msg_stream); else if (type == "Graph Metrics") return MetricAnalyzer::analyzeGraphMetrics( metricsPlist, metricObject, comm, msg_stream); return false; }
static void LoadMetricInfo(std::vector<MetricAnalyzerInfo> & metricInfoSet, const RCP<const Zoltan2::EvaluatePartition <basic_id_t> > &metricObject, const ParameterList &metricsParameters) { // at this point we should be looking at a metricsPlist with the following format - note that weight is optional // <ParameterList name="metriccheck1"> // <Parameter name="check" type="string" value="imbalance"/> // <Parameter name="lower" type="double" value="0.99"/> // <Parameter name="upper" type="double" value="1.4"/> // </ParameterList> // <ParameterList name="metriccheck2"> // <Parameter name="check" type="string" value="imbalance"/> // <Parameter name="weight" type="int" value="0"/> // <Parameter name="lower" type="double" value="0.99"/> // <Parameter name="upper" type="double" value="1.4"/> // </ParameterList> // first let's get a list of all the headings, so "metriccheck1", "metriccheck2" in this case // I've currently got this enforcing those names strictly to make sure formatting is correct // But really the headings could just be any unique names and are arbitrary int headingIndex = 1; for (auto iterateArbitraryHeadingNames = metricsParameters.begin(); iterateArbitraryHeadingNames != metricsParameters.end(); ++iterateArbitraryHeadingNames) { auto headingName = metricsParameters.name(iterateArbitraryHeadingNames); // we could be flexible on these headers but for now let's enforce it to get any convention inconsistencies cleaned up std::string expectedHeadingName = "metriccheck" + std::to_string(headingIndex); if( expectedHeadingName != headingName) { throw std::logic_error( "The parameter list expected to find a heading with name '" + expectedHeadingName + "' but instead found '" + headingName ); } // get the parameters specific to the check we want to run const ParameterList & metricCheckParameters = metricsParameters.sublist(headingName); MetricAnalyzerInfo metricInfo = getMetricInfo(metricCheckParameters, metricObject); metricInfoSet.push_back(metricInfo); ++headingIndex; } }
int main(int argc, char *argv[]) { //////////////////////////////////////////////////////////// // (0) Set up MPI environment and timer //////////////////////////////////////////////////////////// Teuchos::GlobalMPISession session(&argc, &argv); RCP<const Comm<int> > comm = Teuchos::DefaultComm<int>::getComm(); int rank = comm->getRank(); // get rank //////////////////////////////////////////////////////////// // (1) Get and read the input file // the input file defines tests to be run //////////////////////////////////////////////////////////// string inputFileName(""); if(argc > 1) inputFileName = argv[1]; // user has provided an input file else{ if(rank == 0){ std::cout << "\nFAILED to specify xml input file!" << std::endl; ostringstream msg; msg << "\nStandard use of test_driver.cpp:\n"; msg << "mpiexec -n <procs> ./Zoltan2_test_driver.exe <input_file.xml>\n"; std::cout << msg.str() << std::endl; } return 1; } //////////////////////////////////////////////////////////// // (2) Get All Input Parameter Lists //////////////////////////////////////////////////////////// queue<ParameterList> problems, comparisons; getParameterLists(inputFileName,problems, comparisons, comm); //////////////////////////////////////////////////////////// // (3) Get Input Data Parameters //////////////////////////////////////////////////////////// // assumes that first block will always be // the input block const ParameterList inputParameters = problems.front(); if(inputParameters.name() != "InputParameters") { if(rank == 0) cout << "InputParameters not defined. Testing FAILED." << endl; return 1; } // get the user input for all tests UserInputForTests uinput(inputParameters,comm); problems.pop(); comm->barrier(); if(uinput.hasInput()) { //////////////////////////////////////////////////////////// // (4) Perform all tests //////////////////////////////////////////////////////////// // pamgen debugging // MyUtils::writeMesh(uinput,comm); // MyUtils::getConnectivityGraph(uinput, comm); RCP<ComparisonHelper> comparison_manager = rcp(new ComparisonHelper); while (!problems.empty()) { run(uinput, problems.front(), comparison_manager, comm); problems.pop(); } //////////////////////////////////////////////////////////// // (5) Compare solutions //////////////////////////////////////////////////////////// while (!comparisons.empty()) { comparison_manager->Compare(comparisons.front(),comm); comparisons.pop(); } }else{ if(rank == 0){ cout << "\nFAILED to load input data source."; cout << "\nSkipping all tests." << endl; } } return 0; }
void run(const UserInputForTests &uinput, const ParameterList &problem_parameters, RCP<ComparisonHelper> & comparison_helper, const RCP<const Teuchos::Comm<int> > & comm) { // Major steps in running a problem in zoltan 2 // 1. get an input adapter // 2. construct the problem // 3. solve the problem // 4. analyze metrics // 5. clean up int rank = comm->getRank(); if(!problem_parameters.isParameter("kind")) { if(rank == 0) std::cerr << "Problem kind not provided" << std::endl; return; } if(!problem_parameters.isParameter("InputAdapterParameters")) { if(rank == 0) std::cerr << "Input adapter parameters not provided" << std::endl; return; } if(!problem_parameters.isParameter("Zoltan2Parameters")) { if(rank == 0) std::cerr << "Zoltan2 problem parameters not provided" << std::endl; return; } if(rank == 0) cout << "\n\nRunning test: " << problem_parameters.name() << endl; //////////////////////////////////////////////////////////// // 0. add comparison source //////////////////////////////////////////////////////////// ComparisonSource * comparison_source = new ComparisonSource; comparison_helper->AddSource(problem_parameters.name(), comparison_source); comparison_source->addTimer("adapter construction time"); comparison_source->addTimer("problem construction time"); comparison_source->addTimer("solve time"); //////////////////////////////////////////////////////////// // 1. get basic input adapter //////////////////////////////////////////////////////////// const ParameterList &adapterPlist = problem_parameters.sublist("InputAdapterParameters"); comparison_source->timers["adapter construction time"]->start(); base_adapter_t * ia = AdapterForTests::getAdapterForInput(const_cast<UserInputForTests *>(&uinput), adapterPlist,comm); // a pointer to a basic type comparison_source->timers["adapter construction time"]->stop(); // if(rank == 0) cout << "Got input adapter... " << endl; if(ia == nullptr) { if(rank == 0) cout << "Get adapter for input failed" << endl; return; } //////////////////////////////////////////////////////////// // 2. construct a Zoltan2 problem //////////////////////////////////////////////////////////// string adapter_name = adapterPlist.get<string>("input adapter"); // If we are here we have an input adapter, no need to check for one. // get Zoltan2 partion parameters ParameterList zoltan2_parameters = const_cast<ParameterList &>(problem_parameters.sublist("Zoltan2Parameters")); //if(rank == 0){ // cout << "\nZoltan 2 parameters:" << endl; // zoltan2_parameters.print(std::cout); // cout << endl; //} comparison_source->timers["problem construction time"]->start(); std::string problem_kind = problem_parameters.get<std::string>("kind"); if (rank == 0) std::cout << "Creating a new " << problem_kind << " problem." << std::endl; #ifdef HAVE_ZOLTAN2_MPI base_problem_t * problem = Zoltan2_TestingFramework::ProblemFactory::newProblem(problem_kind, adapter_name, ia, &zoltan2_parameters, MPI_COMM_WORLD); #else base_problem_t * problem = Zoltan2_TestingFramework::ProblemFactory::newProblem(problem_kind, adapter_name, ia, &zoltan2_parameters); #endif if (problem == nullptr) { if (rank == 0) std::cerr << "Input adapter type: " + adapter_name + ", is unvailable, or misspelled." << std::endl; return; } //////////////////////////////////////////////////////////// // 3. Solve the problem //////////////////////////////////////////////////////////// comparison_source->timers["solve time"]->start(); if (problem_kind == "partitioning") { reinterpret_cast<partitioning_problem_t *>(problem)->solve(); } else if (problem_kind == "ordering") { reinterpret_cast<ordering_problem_t *>(problem)->solve(); } else if (problem_kind == "coloring") { reinterpret_cast<coloring_problem_t *>(problem)->solve(); } comparison_source->timers["solve time"]->stop(); if (rank == 0) cout << problem_kind + "Problem solved." << endl; //#define KDDKDD #ifdef KDDKDD { const base_adapter_t::gno_t *kddIDs = NULL; ia->getIDsView(kddIDs); for (size_t i = 0; i < ia->getLocalNumIDs(); i++) { std::cout << rank << " LID " << i << " GID " << kddIDs[i] << " PART " << reinterpret_cast<partitioning_problem_t *>(problem)->getSolution().getPartListView()[i] << std::endl; } } #endif //////////////////////////////////////////////////////////// // 4. Print problem metrics //////////////////////////////////////////////////////////// // An environment. This is usually created by the problem. // BDD unused, only applicable to partitioning problems // RCP<const Zoltan2::Environment> env = // reinterpret_cast<partitioning_problem_t *>(problem)->getEnvironment(); // get metric object RCP<EvaluatePartition<basic_id_t> >metricObject = rcp(Zoltan2_TestingFramework::EvaluatePartitionFactory:: newEvaluatePartition(reinterpret_cast<partitioning_problem_t*> (problem), adapter_name, ia, &zoltan2_parameters)); std::string metric_types[] = {"Metrics", "Graph Metrics"}; for (auto metric_type : metric_types) { if( problem_parameters.isParameter(metric_type)) { // calculate pass fail based on imbalance if(rank == 0) cout << "Analyzing " << metric_type << endl; if(rank == 0) { std::cout << metric_type << " for " << problem_kind << ":" << std::endl; if (metric_type == "Metrics") metricObject->printMetrics(cout); else if (metric_type == "Graph Metrics") metricObject->printGraphMetrics(cout); } std::ostringstream msg; auto metricsPlist = problem_parameters.sublist(metric_type); // get the metrics plist bool all_tests_pass = false; all_tests_pass = MetricAnalyzer::analyzeMetrics( metricsPlist, metricObject, comm, msg); std::cout << msg.str() << std::endl; if(rank == 0 && all_tests_pass) cout << "All " << metric_type << " tests PASSED." << endl; else if (rank == 0) cout << "One or more " << metric_type << " tests FAILED." << endl; } else if (rank == 0) cout << metric_type << " analysis unrequested. PASSED." << endl; } #define BDD #ifdef BDD if (problem_kind == "ordering") { std::cout << "\nLet's examine the solution..." << std::endl; auto solution = reinterpret_cast<ordering_problem_t *>(problem)->getSolution(); if (solution->haveSeparators() ) { std::ostringstream sol; sol << "Number of column blocks: " << solution->getNumSeparatorBlocks() << std::endl; if (solution->getPermutationSize() < 100) { if (solution->havePerm()) { sol << "permutation: {"; for (auto &x : solution->getPermutationRCPConst(false)) sol << " " << x; sol << "}" << std::endl; } if (solution->haveInverse()) { sol << "inverse permutation: {"; for (auto &x : solution->getPermutationRCPConst(true)) sol << " " << x; sol << "}" << std::endl; } if (solution->haveSeparatorRange()) { sol << "separator range: {"; for (auto &x : solution->getSeparatorRangeRCPConst()) sol << " " << x; sol << "}" << std::endl; } if (solution->haveSeparatorTree()) { sol << "separator tree: {"; for (auto &x : solution->getSeparatorTreeRCPConst()) sol << " " << x; sol << "}" << std::endl; } } std::cout << sol.str() << std::endl; } } #endif // 4b. timers // if(zoltan2_parameters.isParameter("timer_output_stream")) // reinterpret_cast<partitioning_problem_t *>(problem)->printTimers(); //////////////////////////////////////////////////////////// // 5. Add solution to map for possible comparison testing //////////////////////////////////////////////////////////// comparison_source->adapter = RCP<basic_id_t>(reinterpret_cast<basic_id_t *>(ia)); comparison_source->problem = RCP<base_problem_t>(reinterpret_cast<base_problem_t *>(problem)); comparison_source->metricObject = metricObject; comparison_source->problem_kind = problem_parameters.isParameter("kind") ? problem_parameters.get<string>("kind") : "?"; comparison_source->adapter_kind = adapter_name; // write mesh solution // auto sol = reinterpret_cast<partitioning_problem_t *>(problem)->getSolution(); // MyUtils::writePartionSolution(sol.getPartListView(), ia->getLocalNumIDs(), comm); //////////////////////////////////////////////////////////// // 6. Clean up //////////////////////////////////////////////////////////// }
static MetricAnalyzerInfo getMetricInfo( const ParameterList & metricCheckParameters, const RCP<const Zoltan2::EvaluatePartition <basic_id_t> > &metricObject) { MetricAnalyzerInfo result; // will fill these values for (auto iterateAllKeys = metricCheckParameters.begin(); iterateAllKeys != metricCheckParameters.end(); ++iterateAllKeys) { auto checkName = metricCheckParameters.name(iterateAllKeys); if ( checkName != WEIGHT_PARAMETER_NAME && checkName != KEYWORD_PARAMETER_NAME && checkName != UPPER_PARAMETER_NAME && checkName != LOWER_PARAMETER_NAME && checkName != NORMED_PARAMETER_NAME ) { throw std::logic_error( "Key name: '" + checkName + "' is not understood." ); } } // pick up the weight index - this parameter is optional so we check it first - this way we can communicate with EvaluatePartition properly in the next step int selectedWeightIndex = UNDEFINED_PARAMETER_INT_INDEX; // meaning not specified so default case if( metricCheckParameters.isParameter(WEIGHT_PARAMETER_NAME)) { selectedWeightIndex = metricCheckParameters.get<int>(WEIGHT_PARAMETER_NAME); if( selectedWeightIndex < 0 ) { throw std::logic_error( "Optional weight index was specified as: " + std::to_string(selectedWeightIndex) + " Weight index must be 0 or positive." ); // I think that's the best I can do for error checking weight index right now - we may want to specify the cap when we know it } } // pick up the norm index - this parameter is optional so we check it first - this way we can communicate with EvaluatePartition properly in the next step int selectedNormedSetting = UNDEFINED_PARAMETER_INT_INDEX; // meaning not specified so default case if( metricCheckParameters.isParameter(NORMED_PARAMETER_NAME)) { bool bNormSetting = metricCheckParameters.get<bool>(NORMED_PARAMETER_NAME); selectedNormedSetting = bNormSetting ? 1 : 0; if( selectedNormedSetting != 0 && selectedNormedSetting != 1 ) { throw std::logic_error( "Optional normed parameter was specified as: " + std::to_string(selectedNormedSetting) + " Normed parameter must be true or false." ); } } // one of the parameters called "check" should define a string which is a keyword which correlates to an EvaluatePartition API all // this area needs some consideration - how and where shall we map and define the naming conventions if( metricCheckParameters.isParameter(KEYWORD_PARAMETER_NAME)) { std::string theKeyWord = metricCheckParameters.get<std::string>(KEYWORD_PARAMETER_NAME); // this is going to need some consideration - how is the adapter scalar_t type to be properly handled? result.theValue = convertParameterChoicesToEvaluatePartitionAPICall(metricObject, theKeyWord, selectedWeightIndex, selectedNormedSetting ); // now we can obtain the upper and lower bounds for this test result.bFoundUpperBound = metricCheckParameters.isParameter(UPPER_PARAMETER_NAME); result.bFoundLowerBound = metricCheckParameters.isParameter(LOWER_PARAMETER_NAME); if (!result.bFoundUpperBound && !result.bFoundLowerBound) { throw std::logic_error( "The parameter list failed to find an entry for '" + std::string(UPPER_PARAMETER_NAME) + "' or '" + std::string(LOWER_PARAMETER_NAME) + "' and at least one is required." ); } else if (result.bFoundUpperBound && result.bFoundLowerBound) { result.lowerValue = metricCheckParameters.get<double>(LOWER_PARAMETER_NAME); result.upperValue = metricCheckParameters.get<double>(UPPER_PARAMETER_NAME); } else if (result.bFoundUpperBound) { result.upperValue = metricCheckParameters.get<double>(UPPER_PARAMETER_NAME); } else { result.lowerValue = metricCheckParameters.get<double>(LOWER_PARAMETER_NAME); } result.parameterDescription = theKeyWord; if( selectedWeightIndex != UNDEFINED_PARAMETER_INT_INDEX ) { result.parameterDescription = result.parameterDescription + " (weight: " + std::to_string(selectedWeightIndex) + ")"; } else if( selectedNormedSetting != UNDEFINED_PARAMETER_INT_INDEX ) { // throw above would catch the case where both of these were set result.parameterDescription = result.parameterDescription + " (normed: " + ( ( selectedNormedSetting == 0 ) ? "false" : "true" ) + ")"; } } return result; }
virtual QString toString(MetaSQLInfo * mif, const ParameterList & params, int * nBreaks = 0, bool * isContinue = 0) { //qDebug("MetaSQLBlock::toString()"); QString results = QString::null; MetaSQLOutput * output = 0; bool b = false, myContinue = false, found; int myBreaks = 0; int i = 0, n = 0, ii = 0; QList<QVariant> list; QVariant v, t; ParameterList pList; QString str; switch(_block) { case BlockIf: case BlockElseIf: //qDebug(" BlockIf/BlockEleseIf"); b = _if_func->toVariant(params, nBreaks, isContinue).toBool(); if(_if_not) b = !b; if(b) { //qDebug(" Expression evaluated TRUE"); for(i = 0; i < _items.size(); i++) { output = _items.at(i); results += output->toString(mif, params, nBreaks, isContinue); if(nBreaks && *nBreaks) break; } } else if(_alt) { //qDebug(" Expression evaluated FALSE"); results = _alt->toString(mif, params, nBreaks, isContinue); } break; case BlockForEach: //qDebug(" BlockForEach"); // HERE v = params.value(_loopVar, &found); if(found) { list = v.toList(); for(i = 0; i < list.count(); i++) { str = _loopVar + "__FOREACH_POS__"; // create a new params list with our special var added in pList.clear(); pList.append(str, i); for(n = 0; n < params.count(); n++) { if(params.name(n) != str) { pList.append(params.name(n), params.value(n)); } } myBreaks = 0; myContinue = false; // execute the block for(ii = 0; ii < _items.size(); ii++) { output = _items.at(ii); results += output->toString(mif, pList, &myBreaks, &myContinue); if(myBreaks) break; } if(myBreaks > 0) { myBreaks--; if(myBreaks > 0 || !myContinue) { if(nBreaks) *nBreaks = myBreaks; if(isContinue) *isContinue = myContinue; break; } } } } break; case BlockElse: case BlockGeneric: //qDebug(" BlockElse/BlockGeneric"); for(i = 0; i < _items.size(); i++) { output = _items.at(i); results += output->toString(mif, params, nBreaks, isContinue); if(nBreaks && *nBreaks) break; } break; default: qDebug("Encountered unknown Block type %d.", _block); }; return results; }
virtual QVariant toVariant(const ParameterList & params, int * nBreaks = 0, bool * isContinue = 0) { //qDebug("MetaSQLFunction::toVariant()"); QVariant val; if(_valid) { bool found; QString str; QRegExp re; QVariant t; int i = 0; switch(_func) { case FunctionValue: case FunctionLiteral: //qDebug(" FunctionValue"); str = _params[0]; val = params.value(str); if(val.type() == QVariant::List || val.type() == QVariant::StringList) { str += "__FOREACH_POS__"; t = params.value(str, &found); if(found) { val = (val.toList())[t.toInt()]; } else { // we are not in a loop or the loop we are in is not for // this list so just return the first value in the list val = val.toList().first(); } } break; case FunctionExists: //qDebug(" FunctionExists"); params.value(_params[0], &found); val = ( found ? _trueVariant : _falseVariant ); break; case FunctionReExists: //qDebug(" FunctionReExists"); //qDebug(" Pattern: %s", (const char*)_params[0]); re.setPattern(_params[0]); for(i = 0; i < params.count(); i++) { if(re.search(params.name(i)) != -1) { val = _trueVariant; break; } } break; case FunctionIsFirst: case FunctionIsLast: //qDebug(" FunctionIsFirst/FunctionIsLast"); val = _falseVariant; str = _params[0]; t = params.value(str, &found); if(found) { if(t.type() == QVariant::List || t.type() == QVariant::StringList) { str += "__FOREACH_POS__"; QVariant t2 = params.value(str, &found); int pos = 0; if(found) pos = t2.toInt(); QList<QVariant> l = t.toList(); if(l.size() > 0) { if((_func == FunctionIsFirst) && (pos == 0)) val = _trueVariant; else if((_func == FunctionIsLast) && ((pos + 1) == l.size())) val = _trueVariant; } } else { val = _trueVariant; } } break; case FunctionContinue: case FunctionBreak: //qDebug(" FunctionContinue/FunctionBreak"); if(nBreaks && isContinue) { *nBreaks = _nBreaks; *isContinue = (_func == FunctionContinue); } break; default: (*_parent->_logger) << "MetaSQLFunction::toVariant() encountered unknown Function Type " << (int)_func << "!" << endl; // how did we get here? }; } return val; }
void externalCCTransaction::getResults(ParameterList &pParams) { QVariant amount = pParams.value("amount"); int amountIndex; for (amountIndex = 0; amountIndex < pParams.size(); amountIndex++) if (pParams.name(amountIndex) == "amount") break; switch (_approved->currentIndex()) { case 0: pParams.append("approved", "APPROVED"); if (_transType->currentIndex() == 0) pParams.append("status", "A"); else if (_transType->currentIndex() == 4) pParams.append("status", "V"); else pParams.append("status", "C"); break; case 1: pParams.append("approved", "DECLINED"); pParams.append("status", "D"); if (amountIndex < pParams.size()) pParams.removeAt(amountIndex); pParams.append("amount", "0"); break; case 2: pParams.append("approved", "ERROR"); pParams.append("status", "X"); if (amountIndex < pParams.size()) pParams.removeAt(amountIndex); pParams.append("amount", "0"); break; case 3: pParams.append("approved", "HELDFORREVIEW"); if (_transType->currentIndex() == 0) pParams.append("status", "A"); else if (_transType->currentIndex() == 4) pParams.append("status", "V"); else pParams.append("status", "C"); break; default: pParams.append("status", "X"); if (amountIndex < pParams.size()) pParams.removeAt(amountIndex); pParams.append("amount", "0"); } pParams.append("code", _approvalCode->text()); pParams.append("xactionid",_transactionId->text()); pParams.append("avs", _passedAVS->isChecked() ? tr("passed") : tr("failed or not entered")); pParams.append("passedavs",QVariant(_passedAVS->isChecked())); pParams.append("passedcvv",QVariant(_passedCVV->isChecked())); //pParams.append("error", ); //pParams.append("shipping", ); //pParams.append("tax", ); //pParams.append("ref", ); //pParams.append("message", ); }
QString ExportHelper::generateDelimited(QString qtext, ParameterList ¶ms, QString &errmsg) { if (DEBUG) qDebug("ExportHelper::generateDelimited(%s..., %d params, errmsg) entered", qPrintable(qtext.left(80)), params.size()); if (qtext.isEmpty()) return QString::null; if (DEBUG) { QStringList plist; for (int i = 0; i < params.size(); i++) plist.append("\t" + params.name(i) + ":\t" + params.value(i).toString()); qDebug("generateDelimited parameters:\n%s", qPrintable(plist.join("\n"))); } bool valid; QString delim = params.value("delim", &valid).toString(); if (! valid) delim = ","; if (DEBUG) qDebug("generateDelimited(qtest, params, errmsg) delim = %s, valid = %d", qPrintable(delim), valid); QVariant includeheaderVar = params.value("includeHeaderLine", &valid); bool includeheader = (valid ? includeheaderVar.toBool() : false); if (DEBUG) qDebug("generateDelimited(qtest, params, errmsg) includeheader = %d, valid = %d", includeheader, valid); QStringList line; MetaSQLQuery mql(qtext); XSqlQuery qry = mql.toQuery(params); if (qry.first()) { QStringList field; int cols = qry.record().count(); if (includeheader) { for (int p = 0; p < cols; p++) field.append(qry.record().fieldName(p)); line.append(field.join(delim)); } QString tmp; do { field.clear(); for (int p = 0; p < cols; p++) { tmp = qry.value(p).toString(); if (tmp.contains(delim)) { tmp.replace("\"", "\"\""); tmp = "\"" + tmp + "\""; } field.append(tmp); } line.append(field.join(delim)); } while (qry.next()); } if (qry.lastError().type() != QSqlError::NoError) errmsg = qry.lastError().text(); return line.join("\n"); }
void ParameterListInterpreter<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::SetEasyParameterList(const Teuchos::ParameterList& constParamList) { // Create a non const copy of the parameter list // Working with a modifiable list is much much easier than with original one ParameterList paramList = constParamList; // Translate cycle type parameter if (paramList.isParameter("cycle type")) { std::map<std::string,CycleType> cycleMap; cycleMap["V"] = VCYCLE; cycleMap["W"] = WCYCLE; std::string cycleType = paramList.get<std::string>("cycle type"); TEUCHOS_TEST_FOR_EXCEPTION(cycleMap.count(cycleType) == 0, Exceptions::RuntimeError, "Invalid cycle type: \"" << cycleType << "\""); Cycle_ = cycleMap[cycleType]; } this->maxCoarseSize_ = paramList.get<int> ("coarse: max size", Hierarchy::GetDefaultMaxCoarseSize()); this->numDesiredLevel_ = paramList.get<int> ("max levels", Hierarchy::GetDefaultMaxLevels()); this->graphOutputLevel_ = paramList.get<int> ("debug: graph level", -1); blockSize_ = paramList.get<int> ("number of equations", 1); // Save level data if (paramList.isSublist("print")) { ParameterList printList = paramList.sublist("print"); if (printList.isParameter("A")) this->matricesToPrint_ = Teuchos::getArrayFromStringParameter<int>(printList, "A"); if (printList.isParameter("P")) this->prolongatorsToPrint_ = Teuchos::getArrayFromStringParameter<int>(printList, "P"); if (printList.isParameter("R")) this->restrictorsToPrint_ = Teuchos::getArrayFromStringParameter<int>(printList, "R"); } // Translate verbosity parameter this->verbosity_ = static_cast<MsgType>(Hierarchy::GetDefaultVerbLevel()); // cast int to enum if (paramList.isParameter("verbosity")) { std::map<std::string,MsgType> verbMap; verbMap["none"] = None; verbMap["low"] = Low; verbMap["medium"] = Medium; verbMap["high"] = High; verbMap["extreme"] = Extreme; verbMap["test"] = Test; std::string verbosityLevel = paramList.get<std::string>("verbosity"); TEUCHOS_TEST_FOR_EXCEPTION(verbMap.count(verbosityLevel) == 0, Exceptions::RuntimeError, "Invalid verbosity level: \"" << verbosityLevel << "\""); this->verbosity_ = verbMap[verbosityLevel]; this->SetVerbLevel(this->verbosity_); } // Detect if we need to transfer coordinates to coarse levels. We do that iff // - we use "laplacian" dropping on some level, or // - we use repartitioning on some level // This is not ideal, as we may have "repartition: enable" turned on by default // and not present in the list, but it is better than nothing. useCoordinates_ = false; if ((paramList.isParameter("repartition: enable") && paramList.get<bool>("repartition: enable") == true) || (paramList.isParameter("aggregation: drop scheme") && paramList.get<std::string>("aggregation: drop scheme") == "laplacian")) { useCoordinates_ = true; } else { for (int levelID = 0; levelID < this->numDesiredLevel_; levelID++) { std::string levelStr = "level" + toString(levelID); if (paramList.isSublist(levelStr)) { const ParameterList& levelList = paramList.sublist(levelStr); if ((levelList.isParameter("repartition: enable") && levelList.get<bool>("repartition: enable") == true) || (levelList.isParameter("aggregation: drop scheme") && levelList.get<std::string>("aggregation: drop scheme") == "laplacian")) { useCoordinates_ = true; break; } } } } // Detect if we do implicit P and R rebalance if (paramList.isParameter("repartition: enable") && paramList.get<bool>("repartition: enable") == true) this->doPRrebalance_ = paramList.get<bool>("repartition: rebalance P and R", Hierarchy::GetDefaultPRrebalance()); this->implicitTranspose_ = paramList.get<bool>("transpose: use implicit", Hierarchy::GetDefaultImplicitTranspose()); // Create default manager RCP<FactoryManager> defaultManager = rcp(new FactoryManager()); defaultManager->SetVerbLevel(this->verbosity_); UpdateFactoryManager(paramList, ParameterList(), *defaultManager); defaultManager->Print(); for (int levelID = 0; levelID < this->numDesiredLevel_; levelID++) { RCP<FactoryManager> levelManager; if (paramList.isSublist("level " + toString(levelID))) { // Some level specific parameters, update default manager bool mustAlreadyExist = true; ParameterList& levelList = paramList.sublist("level " + toString(levelID), mustAlreadyExist); levelManager = rcp(new FactoryManager(*defaultManager)); levelManager->SetVerbLevel(defaultManager->GetVerbLevel()); UpdateFactoryManager(levelList, paramList, *levelManager); } else { // No level specific parameter, use default manager levelManager = defaultManager; } this->AddFactoryManager(levelID, 1, levelManager); } if (paramList.isParameter("strict parameter checking") && paramList.get<bool> ("strict parameter checking")) { ParameterList unusedParamList; // Check for unused parameters that aren't lists for (ParameterList::ConstIterator itr = paramList.begin(); itr != paramList.end(); ++itr) { const ParameterEntry& entry = paramList.entry(itr); if (!entry.isList() && !entry.isUsed()) unusedParamList.setEntry(paramList.name(itr), entry); } #if 0 // Check for unused parameters in level-specific sublists for (int levelID = 0; levelID < this->numDesiredLevel_; levelID++) { std::string levelStr = "level" + toString(levelID); if (paramList.isSublist(levelStr)) { const ParameterList& levelList = paramList.sublist(levelStr); for (ParameterList::ConstIterator itr = levelList.begin(); itr != levelList.end(); ++itr) { const ParameterEntry& entry = levelList.entry(itr); if (!entry.isList() && !entry.isUsed()) unusedParamList.sublist(levelStr).setEntry(levelList.name(itr), entry); } } } #endif if (unusedParamList.numParams() > 0) { std::ostringstream unusedParamsStream; int indent = 4; unusedParamList.print(unusedParamsStream, indent); TEUCHOS_TEST_FOR_EXCEPTION_PURE_MSG(true, Teuchos::Exceptions::InvalidParameter, "WARNING: Unused parameters were detected. Please check spelling and type." << std::endl << unusedParamsStream.str()); } } // FIXME: parameters passed to packages, like Ifpack2, are not touched by us, resulting in "[unused]" flag // being displayed. On the other hand, we don't want to simply iterate through them touching. I don't know // what a good solution looks like this->GetOStream(static_cast<MsgType>(Runtime1 | Test), 0) << paramList << std::endl; }
QString ExportHelper::generateXML(const int qryheadid, ParameterList ¶ms, QString &errmsg, int xsltmapid) { if (DEBUG) qDebug("ExportHelper::generateXML(%d, %d params, errmsg, %d) entered", qryheadid, params.size(), xsltmapid); if (DEBUG) { QStringList plist; for (int i = 0; i < params.size(); i++) plist.append("\t" + params.name(i) + ":\t" + params.value(i).toString()); qDebug("generateXML parameters:\n%s", qPrintable(plist.join("\n"))); } QDomDocument xmldoc("xtupleimport"); QDomElement rootelem = xmldoc.createElement("xtupleimport"); xmldoc.appendChild(rootelem); XSqlQuery itemq; QString tableElemName; QString schemaName; itemq.prepare("SELECT * FROM qryitem WHERE qryitem_qryhead_id=:id ORDER BY qryitem_order;"); itemq.bindValue(":id", qryheadid); itemq.exec(); while (itemq.next()) { QString qtext; tableElemName = itemq.value("qryitem_name").toString(); if (itemq.value("qryitem_src").toString() == "REL") { schemaName = itemq.value("qryitem_group").toString(); qtext = "SELECT * FROM " + (schemaName.isEmpty() ? QString("") : schemaName + QString(".")) + itemq.value("qryitem_detail").toString(); } else if (itemq.value("qryitem_src").toString() == "MQL") { QString tmpmsg; bool valid; qtext = MQLUtil::mqlLoad(itemq.value("qryitem_group").toString(), itemq.value("qryitem_detail").toString(), tmpmsg, &valid); if (! valid) errmsg = tmpmsg; } else if (itemq.value("qryitem_src").toString() == "CUSTOM") qtext = itemq.value("qryitem_detail").toString(); if (! qtext.isEmpty()) { MetaSQLQuery mql(qtext); XSqlQuery qry = mql.toQuery(params); if (qry.first()) { do { QDomElement tableElem = xmldoc.createElement(tableElemName); if (DEBUG) qDebug("exportXML starting %s", qPrintable(tableElemName)); if (! schemaName.isEmpty()) tableElem.setAttribute("schema", schemaName); for (int i = 0; i < qry.record().count(); i++) { QDomElement fieldElem = xmldoc.createElement(qry.record().fieldName(i)); if (qry.record().value(i).isNull()) fieldElem.appendChild(xmldoc.createTextNode("[NULL]")); else fieldElem.appendChild(xmldoc.createTextNode(qry.record().value(i).toString())); tableElem.appendChild(fieldElem); } rootelem.appendChild(tableElem); } while (qry.next()); } if (qry.lastError().type() != QSqlError::NoError) errmsg = qry.lastError().text(); } } if (itemq.lastError().type() != QSqlError::NoError) errmsg = itemq.lastError().text(); if (xsltmapid < 0) return xmldoc.toString(); else return XSLTConvertString(xmldoc.toString(), xsltmapid, errmsg); }
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(); }
void ParameterList::validateParametersAndSetDefaults( ParameterList const& validParamList, int const depth ) { typedef std::deque<ListPlusValidList> sublist_list_t; #ifdef TEUCHOS_PARAMETER_LIST_SHOW_TRACE RCP<FancyOStream> out = VerboseObjectBase::getDefaultOStream(); OSTab tab(out); *out << "\n*** Entering ParameterList::validateParametersAndSetDefaults(...) " "for this->name()=\""<<this->name()<<"\"...\n"; #endif // // A) loop through and validate the parameters at this level. // // Here we generate a list of sublists that we will search next // sublist_list_t sublist_list; { Iterator itr; for (itr = this->nonconstBegin(); itr != this->nonconstEnd(); ++itr) { const std::string &entryName = this->name(itr); ParameterEntry &theEntry = this->nonconstEntry(itr); #ifdef TEUCHOS_PARAMETER_LIST_SHOW_TRACE OSTab tab(out); *out << "\nentryName=\""<<entryName<<"\"\n"; #endif const ParameterEntry *validEntry = validParamList.getEntryPtr(entryName); TEUCHOS_TEST_FOR_EXCEPTION_PURE_MSG( !validEntry, Exceptions::InvalidParameterName ,"Error, the parameter {name=\""<<entryName<<"\"," "type=\""<<theEntry.getAny(false).typeName()<<"\"" ",value=\""<<filterValueToString(theEntry)<<"\"}" "\nin the parameter (sub)list \""<<this->name()<<"\"" "\nwas not found in the list of valid parameters!" "\n\nThe valid parameters and types are:\n" <<validParamList.currentParametersString() ); RCP<const ParameterEntryValidator> validator; if (nonnull(validator=validEntry->validator())) { validator->validateAndModify(entryName, this->name(), &theEntry); theEntry.setValidator(validator); } else { const bool validType = ( validEntry!=NULL ? theEntry.getAny(false).type() == validEntry->getAny(false).type() : false ); TEUCHOS_TEST_FOR_EXCEPTION_PURE_MSG( !validType, Exceptions::InvalidParameterType ,"Error, the parameter {name=\""<<entryName<<"\"," "type=\""<<theEntry.getAny(false).typeName()<<"\"" ",value=\""<<filterValueToString(theEntry)<<"\"}" "\nin the parameter (sub)list \""<<this->name()<<"\"" "\nexists in the list of valid parameters but has the wrong type." "\n\nThe correct type is \"" << validEntry->getAny(false).typeName() << "\"." ); // Note: If there is no validator for this item, then we can not // validate the value of the parameter, only its type! } if( theEntry.isList() && depth > 0 ) { sublist_list.push_back( ListPlusValidList( &getValue<ParameterList>(theEntry), &getValue<ParameterList>(*validEntry) ) ); } } } // // B) Loop through the valid parameters at this level that are not set in // *this, and set their defaults. // { ConstIterator itr; for (itr = validParamList.begin(); itr != validParamList.end(); ++itr) { const std::string &validEntryName = validParamList.name(itr); const ParameterEntry &validEntry = validParamList.entry(itr); const ParameterEntry *theEntry = this->getEntryPtr(validEntryName); if (!theEntry) { // This entry does not exist, so add it. Here we will only set the // value of the entry and its validator and and leave off the // documentation. The reason that the validator is set is so that it // can be used to extract and validate entries in the transformed list // *this without having to refer back to the valid parameter list. ParameterEntry newEntry; newEntry.setAnyValue( validEntry.getAny(), true // isDefault ); newEntry.setValidator(validEntry.validator()); this->setEntry(validEntryName,newEntry); } } } // // C) Loop through the sublists and validate their parameters and set their // defaults! // for ( sublist_list_t::iterator sl_itr = sublist_list.begin(); sl_itr != sublist_list.end(); ++sl_itr ) { if (!sl_itr->validList->disableRecursiveValidation_) { sl_itr->list->validateParametersAndSetDefaults(*sl_itr->validList,depth-1); } } #ifdef TEUCHOS_PARAMETER_LIST_SHOW_TRACE *out << "\n*** Existing ParameterList::validateParametersAndSetDefaults(...) " "for this->name()=\""<<this->name()<<"\"...\n"; #endif }