MOOCHO (Single Doxygen Collection)  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MoochoPack_MoochoThyraSolver.cpp
Go to the documentation of this file.
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Moocho: Multi-functional Object-Oriented arCHitecture for Optimization
5 // Copyright (2003) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Roscoe A. Bartlett (rabartl@sandia.gov)
38 //
39 // ***********************************************************************
40 // @HEADER
41 
45 #include "Thyra_DefaultFiniteDifferenceModelEvaluator.hpp"
46 #include "Thyra_DefaultStateEliminationModelEvaluator.hpp"
47 #include "Thyra_DefaultEvaluationLoggerModelEvaluator.hpp"
48 #include "Thyra_DefaultInverseModelEvaluator.hpp"
49 #include "Thyra_DefaultLumpedParameterModelEvaluator.hpp"
50 #include "Thyra_DefaultSpmdMultiVectorFileIO.hpp"
51 #include "Thyra_DampenedNewtonNonlinearSolver.hpp"
52 #include "Thyra_ModelEvaluatorHelpers.hpp"
53 #include "Thyra_VectorStdOps.hpp"
56 
57 namespace {
58 
59 //
60 // ParameterList parameters and sublists
61 //
62 
63 const std::string SolveMode_name = "Solve Mode";
64 const Teuchos::RCP<
67  >
68 >
69 solveModeValidator = Teuchos::rcp(
71  Teuchos::tuple<std::string>(
72  "Forward Solve"
73  ,"Optimize"
74  )
75  ,Teuchos::tuple<std::string>(
76  "Only solve state equaitons f(x,p)=0 for states x\n"
77  "given fixed parameters values p."
78  ,"Solve the simulation constrained optimization problem\n"
79  " min g(x,p)\n"
80  " s.t. f(x,p)=0\n"
81  "for the state varaibles x and parameters p."
82  )
83  ,Teuchos::tuple<MoochoPack::MoochoThyraSolver::ESolveMode>(
86  )
87  ,""
88  )
89  );
90 const std::string SolveMode_default = "Optimize";
91 
92 const std::string NLPType_name = "NLP Type";
93 const Teuchos::RCP<
96  >
97  >
98 nlpTypeValidator = Teuchos::rcp(
100  Teuchos::tuple<std::string>(
101  "First Order"
102  ,"Direct"
103  )
104  ,Teuchos::tuple<std::string>(
105  "Support the NLPInterfacePack::NLPFirstOrder interface which assumes\n"
106  "that full adjoints for the objective and constraint derivatives are\n"
107  "available."
108  ,"Support the NLPInterfacePack::NLPDirect interface which only assumes\n"
109  "that forward or direct sensitivities and state solves are supported."
110  )
111  ,Teuchos::tuple<MoochoPack::MoochoThyraSolver::ENLPType>(
114  )
115  ,""
116  )
117  );
118 const std::string NLPType_default = "First Order";
119 
120 const std::string NonlinearlyEliminateStates_name = "Nonlinearly Eliminate States";
121 const bool NonlinearlyEliminateStates_default = false;
122 
123 const std::string UseFiniteDifferencesForObjective_name = "Use Finite Differences For Objective";
124 const bool UseFiniteDifferencesForObjective_default = false;
125 
126 const std::string ObjectiveFiniteDifferenceSettings_name = "Objective Finite Difference Settings";
127 
128 const std::string UseFiniteDifferencesForConstraints_name = "Use Finite Differences For Constraints";
129 const bool UseFiniteDifferencesForConstraints_default = false;
130 
131 const std::string ConstraintsFiniteDifferenceSettings_name = "Constraints Finite Difference Settings";
132 
133 const std::string FwdNewtonTol_name = "Forward Newton Tolerance";
134 const double FwdNewtonTol_default = -1.0;
135 
136 const std::string FwdNewtonMaxIters_name = "Forward Newton Max Iters";
137 const int FwdNewtonMaxIters_default = 20;
138 
139 const std::string ForwardNewtonDampening_name = "Forward Newton Dampening";
140 const bool ForwardNewtonDampening_default = true;
141 
142 const std::string FwdNewtonMaxLineSearchIters_name = "Forward Newton Max Line Search Iters";
143 const int FwdNewtonMaxLineSearchIters_default = 20;
144 
145 const std::string UseBuiltInInverseObjectiveFunction_name = "Use Built-in Inverse Objective Function";
146 const bool UseBuiltInInverseObjectiveFunction_default = false;
147 
148 const std::string InverseObjectiveFunctionSettings_name = "Inverse Objective Function Settings";
149 
150 const std::string UseParameterLumping_name = "Use Parameter Lumping";
151 const bool UseParameterLumping_default = false;
152 
153 const std::string LumpedParametersSettings_name = "Lumped Parameters Settings";
154 
155 const std::string OutputFileTag_name = "Output File Tag";
156 const std::string OutputFileTag_default = "";
157 
158 const std::string OutputOnAllProcesses_name = "Output On All Processes";
159 const bool OutputOnAllProcesses_default = false;
160 
161 const std::string ShowModelEvaluatorTrace_name = "Show Model Evaluator Trace";
162 const bool ShowModelEvaluatorTrace_default = "false";
163 
164 const std::string StateGuess_name = "State Guess";
165 
166 const std::string ParamGuess_name = "Parameter Guess";
167 
168 const std::string ParamLowerBounds_name = "Parameter Lower Bounds";
169 
170 const std::string ParamUpperBounds_name = "Parameter Upper Bounds";
171 
172 const std::string StateSoluFileBaseName_name = "State Solution File Base Name";
173 const std::string StateSoluFileBaseName_default = "";
174 
175 const std::string ParamSoluFileBaseName_name = "Parameters Solution File Base Name";
176 const std::string ParamSoluFileBaseName_default = "";
177 
178 } // namespace
179 
180 namespace MoochoPack {
181 
182 // Constructors/initialization
183 
185  const std::string &paramsXmlFileName
186  ,const std::string &extraParamsXmlString
187  ,const std::string &paramsUsedXmlOutFileName
188  ,const std::string &paramsXmlFileNameOption
189  ,const std::string &extraParamsXmlStringOption
190  ,const std::string &paramsUsedXmlOutFileNameOption
191  )
192  :paramsXmlFileName_(paramsXmlFileName)
193  ,extraParamsXmlString_(extraParamsXmlString)
194  ,paramsUsedXmlOutFileName_(paramsUsedXmlOutFileName)
195  ,paramsXmlFileNameOption_(paramsXmlFileNameOption)
196  ,extraParamsXmlStringOption_(extraParamsXmlStringOption)
197  ,paramsUsedXmlOutFileNameOption_(paramsUsedXmlOutFileNameOption)
198  ,stateVectorIO_(Teuchos::rcp(new Thyra::DefaultSpmdMultiVectorFileIO<value_type>))
199  ,parameterVectorIO_(Teuchos::rcp(new Thyra::DefaultSpmdMultiVectorFileIO<value_type>))
200  ,solveMode_(SOLVE_MODE_OPTIMIZE)
201  ,nlpType_(NLP_TYPE_FIRST_ORDER)
202  ,nonlinearlyElimiateStates_(false)
203  ,use_finite_diff_for_obj_(false)
204  ,use_finite_diff_for_con_(false)
205  ,fwd_newton_tol_(-1.0)
206  ,fwd_newton_max_iters_(20)
207  ,fwd_newton_dampening_(false)
208  ,fwd_newton_max_ls_iters_(20)
209  ,useInvObjFunc_(false)
210  ,useParameterLumping_(false)
211  ,outputFileTag_("")
212  ,showModelEvaluatorTrace_(false)
213  ,stateSoluFileBase_("")
214  ,paramSoluFileBase_("")
215 {}
216 
218 {}
219 
222  )
223 {
224  TEUCHOS_TEST_FOR_EXCEPT(0==clp);
226  clp->setOption(
227  paramsXmlFileNameOption().c_str(),&paramsXmlFileName_
228  ,"Name of an XML file containing parameters for linear solver options to be appended first."
229  );
230  clp->setOption(
231  extraParamsXmlStringOption().c_str(),&extraParamsXmlString_
232  ,"An XML string containing linear solver parameters to be appended second."
233  );
234  clp->setOption(
235  paramsUsedXmlOutFileNameOption().c_str(),&paramsUsedXmlOutFileName_
236  ,"Name of an XML file that can be written with the parameter list after it has been used on completion of this program."
237  );
238 }
239 
240 void MoochoThyraSolver::readParameters( std::ostream *out_arg )
241 {
243  out = Teuchos::getFancyOStream(Teuchos::rcp(out_arg,false));
244  Teuchos::OSTab tab(out);
245  if(out.get()) *out << "\nMoochoThyraSolver::readParameters(...):\n";
246  Teuchos::OSTab tab2(out);
248  paramList = this->getNonconstParameterList();
249  if(!paramList.get()) {
250  if(out.get()) *out << "\nCreating a new Teuchos::ParameterList ...\n";
251  paramList = Teuchos::rcp(new Teuchos::ParameterList("MoochoThyraSolver"));
252  }
253  if(paramsXmlFileName().length()) {
254  if(out.get()) *out << "\nReading parameters from XML file \""<<paramsXmlFileName()<<"\" ...\n";
255  Teuchos::updateParametersFromXmlFile(paramsXmlFileName(), paramList.ptr());
256  }
257  if(extraParamsXmlString().length()) {
258  if(out.get())
259  *out << "\nAppending extra parameters from the XML string \""<<extraParamsXmlString()<<"\" ...\n";
260  Teuchos::updateParametersFromXmlString(extraParamsXmlString(), paramList.ptr());
261  }
262  if( paramsXmlFileName().length() || extraParamsXmlString().length() ) {
264  if(out.get()) {
265  *out << "\nUpdated parameter list:\n";
266  paramList->print(
267  *out,PLPrintOptions().indent(2).showTypes(true)
268  );
269  }
270  this->setParameterList(paramList);
271  }
272 }
273 
274 // Overridden from ParameterListAcceptor
275 
277  Teuchos::RCP<Teuchos::ParameterList> const& paramList
278  )
279 {
280  typedef MoochoPack::MoochoSolver MS;
281  TEUCHOS_TEST_FOR_EXCEPT(!paramList.get());
282  paramList->validateParameters(*getValidParameters(),0); // Just validate my level!
283  paramList_ = paramList;
284  solveMode_ = solveModeValidator->getIntegralValue(
285  *paramList_,SolveMode_name,SolveMode_default);
286  nlpType_ = nlpTypeValidator->getIntegralValue(
287  *paramList_,NLPType_name,NLPType_default);
289  NonlinearlyEliminateStates_name,NonlinearlyEliminateStates_default);
291  UseFiniteDifferencesForObjective_name,UseFiniteDifferencesForObjective_default);
293  UseFiniteDifferencesForConstraints_name,UseFiniteDifferencesForConstraints_default);
295  FwdNewtonTol_name,FwdNewtonTol_default);
297  FwdNewtonMaxIters_name,FwdNewtonMaxIters_default);
299  ForwardNewtonDampening_name,ForwardNewtonDampening_default);
301  FwdNewtonMaxLineSearchIters_name,FwdNewtonMaxLineSearchIters_default);
303  UseBuiltInInverseObjectiveFunction_name,UseBuiltInInverseObjectiveFunction_default);
305  UseParameterLumping_name, UseParameterLumping_default);
306  outputFileTag_ = paramList->get(
307  OutputFileTag_name,OutputFileTag_default);
310  paramList_->get(OutputOnAllProcesses_name, OutputOnAllProcesses_default)
311  ? MS::OUTPUT_TO_BLACK_HOLE_FALSE
312  : MS::OUTPUT_TO_BLACK_HOLE_DEFAULT
313  );
314  showModelEvaluatorTrace_ = paramList->get(
315  ShowModelEvaluatorTrace_name,ShowModelEvaluatorTrace_default);
316  x_reader_.setParameterList(
317  sublist(paramList_,StateGuess_name)
318  );
319  p_reader_.setParameterList(
320  sublist(paramList_,ParamGuess_name)
321  );
322  p_l_reader_.setParameterList(
323  sublist(paramList_,ParamLowerBounds_name)
324  );
325  p_u_reader_.setParameterList(
326  sublist(paramList_,ParamUpperBounds_name)
327  );
329  StateSoluFileBaseName_name,StateSoluFileBaseName_default);
331  ParamSoluFileBaseName_name,ParamSoluFileBaseName_default);
332 #ifdef TEUCHOS_DEBUG
333  paramList->validateParameters(*getValidParameters(),0); // Just validate my level!
334 #endif
335 }
336 
339 {
340  return paramList_;
341 }
342 
345 {
348  return _paramList;
349 }
350 
353 {
354  return paramList_;
355 }
356 
359 {
361  if(pl.get()==NULL) {
363  pl->set(
364  SolveMode_name,SolveMode_default
365  ,"The type of solve to perform."
366  ,solveModeValidator
367  );
368  pl->set(
369  NLPType_name,NLPType_default
370  ,"The type of MOOCHO NLP subclass to use."
371  ,nlpTypeValidator
372  );
373  pl->set(
374  NonlinearlyEliminateStates_name,NonlinearlyEliminateStates_default
375  ,"If true, then the model's state equations and state variables\n"
376  "are nonlinearlly eliminated using a forward solver."
377  );
378  pl->set(
379  UseFiniteDifferencesForObjective_name,UseFiniteDifferencesForObjective_default
380  ,"Use finite differences for missing objective function derivatives (Direct NLP only).\n"
381  "See the options in the sublist \"" + ObjectiveFiniteDifferenceSettings_name + "\"."
382  );
383  {
384  Thyra::DirectionalFiniteDiffCalculator<Scalar> dfdcalc;
385  {
387  &fdSublist = pl->sublist(ObjectiveFiniteDifferenceSettings_name);
388  fdSublist.setParameters(*dfdcalc.getValidParameters());
389  }
390  pl->set(
391  UseFiniteDifferencesForConstraints_name,UseFiniteDifferencesForConstraints_default
392  ,"Use finite differences for missing constraint derivatives (Direct NLP only).\n"
393  "See the options in the sublist \"" + ConstraintsFiniteDifferenceSettings_name + "\"."
394  );
395  {
397  &fdSublist = pl->sublist(ConstraintsFiniteDifferenceSettings_name);
398  fdSublist.setParameters(*dfdcalc.getValidParameters());
399  }
400  }
401  pl->set(
402  FwdNewtonTol_name,FwdNewtonTol_default
403  ,"Tolarance used for the forward state solver in eliminating\n"
404  "the state equations/variables."
405  );
406  pl->set(
407  FwdNewtonMaxIters_name,FwdNewtonMaxIters_default
408  ,"Maximum number of iterations allowed for the forward state\n"
409  "solver in eliminating the state equations/variables."
410  );
411  pl->set(
412  ForwardNewtonDampening_name, ForwardNewtonDampening_default,
413  "If true, then the state elimination nonlinear solver will\n"
414  "use a dampened line search. Otherwise, it will just take fulls steps."
415  );
416  pl->set(
417  FwdNewtonMaxLineSearchIters_name, FwdNewtonMaxLineSearchIters_default,
418  "Maximum number of linea search iterations per newton iteration\n"
419  "allowed for the forward state solver in eliminating the state equations/variables."
420  );
421  pl->set(
422  UseBuiltInInverseObjectiveFunction_name,UseBuiltInInverseObjectiveFunction_default
423  ,"Use a built-in form of a simple inverse objection function instead\n"
424  "of a a response function contained in the underlying model evaluator\n"
425  "object itself. The settings are contained in the sublist\n"
426  "\""+InverseObjectiveFunctionSettings_name+"\".\n"
427  "Note that this feature allows the client to form a useful type\n"
428  "of optimization problem just with a model that supports only the\n"
429  "parameterized state function f(x,p)=0."
430  );
431  {
433  inverseModel = rcp(new Thyra::DefaultInverseModelEvaluator<Scalar>());
434  pl->sublist(
435  InverseObjectiveFunctionSettings_name,false
436  ,"Settings for the built-in inverse objective function.\n"
437  "See the outer parameter \""+UseBuiltInInverseObjectiveFunction_name+"\"."
438  ).setParameters(*inverseModel->getValidParameters());
439  }
440  pl->set(
441  UseParameterLumping_name,UseParameterLumping_default,
442  "Use a reduced basis to lump optimization parameters as\n"
443  "p_orig = P_basis * p. If set to true, then the settings\n"
444  "in \""+LumpedParametersSettings_name+"\" determine how the\n"
445  "parameter basis is set. This feature can be used to safely\n"
446  "regularize a problem if there are linearly dependent parameters\n"
447  "and will generally speed up the optimiztation algorithms."
448  );
449  {
451  lumpedParamModel = rcp(new Thyra::DefaultLumpedParameterModelEvaluator<Scalar>);
452  pl->sublist(
453  LumpedParametersSettings_name,false
454  ,"Settings for parameter lumping.\n"
455  "See the outer parameter \""+UseParameterLumping_name+"\"."
456  ).setParameters(*lumpedParamModel->getValidParameters());
457  }
458  pl->set(OutputFileTag_name,OutputFileTag_default,
459  "A tag that is attached to every output file that is created by the\n"
460  "solver. If empty \"\", then no tag is used. This option simply is\n"
461  "passed into the set_output_context(...) function on the underlying\n"
462  "MoochoPack::MoochoSolver object. Therefore, this same parameter\n"
463  "can be set in code as well without going through the parameter list.");
464  pl->set(OutputOnAllProcesses_name, OutputOnAllProcesses_default,
465  "If set to true, then the console output and all MOOCHO files will be\n"
466  "written for every process. This helps in debugging very hard\n"
467  "parallel problems.");
468  pl->set(ShowModelEvaluatorTrace_name,ShowModelEvaluatorTrace_default
469  ,"Determine if a trace of the objective function will be shown or not\n"
470  "when the NLP is evaluated."
471  );
472  if(this->get_stateVectorIO().get())
473  x_reader_.set_fileIO(this->get_stateVectorIO());
474  pl->sublist(StateGuess_name).setParameters(*x_reader_.getValidParameters());
475  if(this->get_parameterVectorIO().get()) {
476  p_reader_.set_fileIO(this->get_parameterVectorIO());
477  p_l_reader_.set_fileIO(this->get_parameterVectorIO());
478  p_u_reader_.set_fileIO(this->get_parameterVectorIO());
479  pl->sublist(ParamGuess_name).setParameters(*p_reader_.getValidParameters());
480  pl->sublist(ParamLowerBounds_name).setParameters(*p_l_reader_.getValidParameters());
481  pl->sublist(ParamUpperBounds_name).setParameters(*p_u_reader_.getValidParameters());
482  }
483  pl->set(
484  StateSoluFileBaseName_name,StateSoluFileBaseName_default
485  ,"If specified, a file with this basename will be written to with\n"
486  "the final value of the state variables. A different file for each\n"
487  "process will be created. Note that these files can be used for the\n"
488  "initial guess for the state variables."
489  );
490  pl->set(
491  ParamSoluFileBaseName_name,ParamSoluFileBaseName_default
492  ,"If specified, a file with this basename will be written to with\n"
493  "the final value of the parameters. A different file for each\n"
494  "process will be created. Note that these files can be used for the\n"
495  "initial guess for the parameters."
496  );
497  }
498  return pl;
499 }
500 
501 // Misc Access/Setup
502 
504 {
505  solveMode_ = solveMode;
506 }
507 
510 {
511  return solveMode_;
512 }
513 
515 {
516  return solver_;
517 }
518 
520 {
521  return solver_;
522 }
523 
524 // Model specification, setup, solve, and solution extraction.
525 
527  const Teuchos::RCP<Thyra::ModelEvaluator<value_type> > &origModel,
528  const int p_idx,
529  const int g_idx
530  )
531 {
532 
533  using Teuchos::rcp;
534  using Teuchos::sublist;
535  using NLPInterfacePack::NLP;
538 
539  origModel_ = origModel;
540  p_idx_ = p_idx;
541  g_idx_ = g_idx;
542 
543  //const int procRank = Teuchos::GlobalMPISession::getRank();
544  //const int numProcs = Teuchos::GlobalMPISession::getNProc();
545 
546  //
547  // Wrap the orginal model in different decorators
548  //
549 
551 
552  // Inverse objective (and parameter regularization)?
553  if (useInvObjFunc_) {
555  inverseModel = Thyra::defaultInverseModelEvaluator<Scalar>(outerModel_);
556  inverseModel->setVerbLevel(Teuchos::VERB_LOW);
557  inverseModel->set_observationTargetIO(get_stateVectorIO());
558  inverseModel->set_parameterBaseIO(get_parameterVectorIO());
559  inverseModel->setParameterList(
560  Teuchos::sublist(paramList_,InverseObjectiveFunctionSettings_name) );
561  outerModel_ = inverseModel;
562  g_idx_ = inverseModel->Ng()-1;
563  }
564 
565  // Evaluation loging
567  modelEvalLogOut = Teuchos::fancyOStream(
568  solver_.generate_output_file("ModelEvaluationLog")
569  );
571  loggerThyraModel
572  = rcp(
573  new Thyra::DefaultEvaluationLoggerModelEvaluator<Scalar>(
574  outerModel_,modelEvalLogOut
575  )
576  );
577  outerModel_ = loggerThyraModel;
578 
579  // Manipulating the nominal values
581  = rcp(
582  new Thyra::DefaultNominalBoundsOverrideModelEvaluator<Scalar>(outerModel_,Teuchos::null)
583  );
585 
586  // Capturing the final point
588  = rcp(
589  new Thyra::DefaultFinalPointCaptureModelEvaluator<value_type>(outerModel_)
590  );
592 
593  // Parameter lumping?
594  if (useParameterLumping_) {
596  lumpedParamModel = Thyra::defaultLumpedParameterModelEvaluator<Scalar>(outerModel_);
597  lumpedParamModel->setVerbLevel(Teuchos::VERB_LOW);
598  lumpedParamModel->setParameterList(
599  sublist(paramList_,LumpedParametersSettings_name));
600  outerModel_ = lumpedParamModel;
601  }
602  // Note, above we put parameter lumping on the very top so that everything
603  // like the final point capture and the nominal bounds overrider deal with
604  // the original parameters, not the lumped parameters.
605 
606  //
607  // Create the NLP
608  //
609 
610  Teuchos::RCP<NLP> nlp;
611 
612  switch(solveMode_) {
613  case SOLVE_MODE_FORWARD: {
615  nlpFirstOrder = rcp(
616  new NLPFirstOrderThyraModelEvaluator(outerModel_,-1,-1)
617  );
618  nlpFirstOrder->showModelEvaluatorTrace(showModelEvaluatorTrace_);
619  nlp = nlpFirstOrder;
620  break;
621  }
622  case SOLVE_MODE_OPTIMIZE: {
623  // Setup finite difference object
624  RCP<Thyra::DirectionalFiniteDiffCalculator<Scalar> > objDirecFiniteDiffCalculator;
626  objDirecFiniteDiffCalculator = rcp(new Thyra::DirectionalFiniteDiffCalculator<Scalar>());
627  if(paramList_.get())
628  objDirecFiniteDiffCalculator->setParameterList(
629  Teuchos::sublist(paramList_,ObjectiveFiniteDifferenceSettings_name)
630  );
631  }
632  RCP<Thyra::DirectionalFiniteDiffCalculator<Scalar> > conDirecFiniteDiffCalculator;
634  conDirecFiniteDiffCalculator = rcp(new Thyra::DirectionalFiniteDiffCalculator<Scalar>());
635  if(paramList_.get())
636  conDirecFiniteDiffCalculator->setParameterList(
637  Teuchos::sublist(paramList_,ConstraintsFiniteDifferenceSettings_name)
638  );
639  }
641  // Create a Thyra::NonlinearSolverBase object to solve and eliminate the
642  // state variables and the state equations
644  stateSolver = rcp(new Thyra::DampenedNewtonNonlinearSolver<Scalar>()); // ToDo: Replace with MOOCHO!
645  stateSolver->defaultTol(fwd_newton_tol_);
646  stateSolver->defaultMaxNewtonIterations(fwd_newton_max_iters_);
647  stateSolver->useDampenedLineSearch(fwd_newton_dampening_);
648  stateSolver->maxLineSearchIterations(fwd_newton_max_ls_iters_);
649  // Create the reduced Thyra::ModelEvaluator object for p -> g_hat(p)
651  reducedThyraModel = rcp(new Thyra::DefaultStateEliminationModelEvaluator<Scalar>(outerModel_,stateSolver));
653  finalReducedThyraModel;
655  // Create the finite-difference wrapped Thyra::ModelEvaluator object
657  fdReducedThyraModel = Thyra::defaultFiniteDifferenceModelEvaluator<Scalar>(
658  reducedThyraModel, objDirecFiniteDiffCalculator
659  );
660  finalReducedThyraModel = fdReducedThyraModel;
661  }
662  else {
663  finalReducedThyraModel = reducedThyraModel;
664  }
665  // Wrap the reduced NAND Thyra::ModelEvaluator object in an NLP object
667  nlpFirstOrder = rcp(
668  new NLPFirstOrderThyraModelEvaluator(finalReducedThyraModel,p_idx_,g_idx_)
669  );
670  nlpFirstOrder->showModelEvaluatorTrace(showModelEvaluatorTrace_);
671  nlp = nlpFirstOrder;
672  }
673  else {
674  switch(nlpType_) {
675  case NLP_TYPE_DIRECT: {
677  nlpDirect = rcp(
678  new NLPDirectThyraModelEvaluator(
680  ,objDirecFiniteDiffCalculator
681  ,conDirecFiniteDiffCalculator
682  )
683  );
684  nlpDirect->showModelEvaluatorTrace(showModelEvaluatorTrace_);
685  nlp = nlpDirect;
686  break;
687  }
688  case NLP_TYPE_FIRST_ORDER: {
690  nlpFirstOrder = rcp(
691  new NLPFirstOrderThyraModelEvaluator(outerModel_,p_idx_,g_idx_)
692  );
693  nlpFirstOrder->showModelEvaluatorTrace(showModelEvaluatorTrace_);
694  nlp = nlpFirstOrder;
695  break;
696  }
697  default:
699  }
700  }
701  break;
702  }
703  default:
705  }
706 
707  // Set the NLP
708  solver_.set_nlp(nlp);
709 
710 }
711 
714 {
715  return origModel_;
716 }
717 
720 {
721  return outerModel_;
722 }
723 
725  std::ostream *out_arg
726  )
727 {
728  using Teuchos::OSTab;
729  using Teuchos::RCP;
730  using Thyra::clone;
731  typedef Thyra::ModelEvaluatorBase MEB;
732 
734  out = Teuchos::getFancyOStream(Teuchos::rcp(out_arg,false));
736  initialGuess = clone(origModel_->getNominalValues()),
737  lowerBounds = clone(origModel_->getLowerBounds()),
738  upperBounds = clone(origModel_->getUpperBounds());
739 
741  x_space = origModel_->get_x_space();
742  if( 0 != x_space.get() ) {
743  x_reader_.set_vecSpc(origModel_->get_x_space());
744  if(this->get_stateVectorIO().get())
745  x_reader_.set_fileIO(this->get_stateVectorIO());
747  vots_x_reader(RCP<Thyra::ParameterDrivenMultiVectorInput<value_type> >(&x_reader_,false),out,Teuchos::VERB_LOW);
748  initialGuess->set_x(
749  readVectorOverride(
750  x_reader_,"initial guess for the state \'x\'",initialGuess->get_x()
751  )
752  );
753  }
754  if( origModel_->Np() > 0 ) {
755  p_reader_.set_vecSpc(origModel_->get_p_space(p_idx_));
756  p_l_reader_.set_vecSpc(p_reader_.get_vecSpc());
757  p_u_reader_.set_vecSpc(p_reader_.get_vecSpc());
758  if(this->get_parameterVectorIO().get()) {
759  p_reader_.set_fileIO(this->get_parameterVectorIO());
760  p_l_reader_.set_fileIO(p_reader_.get_fileIO());
761  p_u_reader_.set_fileIO(p_reader_.get_fileIO());
762  }
764  vots_p_reader(RCP<Thyra::ParameterDrivenMultiVectorInput<value_type> >(&p_reader_,false),out,Teuchos::VERB_LOW);
765  initialGuess->set_p(
766  p_idx_,
767  readVectorOverride(
768  p_reader_,"initial guess for the parameters \'p\'",
769  initialGuess->get_p(p_idx_)
770  )
771  );
772  lowerBounds->set_p(
773  p_idx_,
774  readVectorOverride(
775  p_l_reader_,"lower bounds for the parameters \'p\'",lowerBounds->get_p(p_idx_)
776  )
777  );
778  upperBounds->set_p(
779  p_idx_,
780  readVectorOverride(
781  p_u_reader_,"upper bounds for the parameters \'p\'",upperBounds->get_p(p_idx_)
782  )
783  );
784  }
785  nominalModel_->setNominalValues(initialGuess);
786  nominalModel_->setLowerBounds(lowerBounds);
787  nominalModel_->setUpperBounds(upperBounds);
788 }
789 
791  const Teuchos::RCP<const Thyra::ModelEvaluatorBase::InArgs<value_type> > &initialGuess
792  )
793 {
794  nominalModel_->setNominalValues(initialGuess);
795 }
796 
798  const Thyra::ModelEvaluatorBase::InArgs<value_type> &initialGuess
799  )
800 {
801  nominalModel_->setNominalValues(
802  Teuchos::rcp(new Thyra::ModelEvaluatorBase::InArgs<value_type>(initialGuess))
803  );
804 }
805 
807 {
808  using Teuchos::RCP; using Teuchos::null; using Teuchos::describe;
810  std::ostringstream os;
811  os
812  << "\n**********************************"
813  << "\n*** MoochoThyraSolver::solve() ***"
814  << "\n**********************************\n";
816  x_space = outerModel_->get_x_space(),
817  p_space = (
818  ( p_idx_ >= 0 && outerModel_->Np() > 0 )
819  ? outerModel_->get_p_space(p_idx_)
820  : null
821  );
822  if( !is_null(x_space) )
823  os << "\nx_space: " << describe(*x_space,Teuchos::VERB_MEDIUM);
824  if( !is_null(p_space) )
825  os << "\np_space: " << describe(*p_space,Teuchos::VERB_MEDIUM);
826  *solver_.get_console_out() << os.str();
827  *solver_.get_summary_out() << os.str();
828  *solver_.get_journal_out() << os.str();
829  outerModel_->setOStream(Teuchos::getFancyOStream(solver_.get_journal_out()));
830  return solver_.solve_nlp();
831 }
832 
833 const Thyra::ModelEvaluatorBase::InArgs<value_type>&
835 {
836  return finalPointModel_->getFinalPoint();
837 }
838 
840  std::ostream *out_arg
841  ) const
842 {
843  using Teuchos::OSTab;
845  out = Teuchos::getFancyOStream(Teuchos::rcp(out_arg,false));
846  if( stateSoluFileBase_ != "" && finalPointModel_->getFinalPoint().get_x().get() ) {
847  if(out.get())
848  *out << "\nWriting the state solution \'x\' to the file(s) with base name \""<<stateSoluFileBase_<<"\" ...\n";
849  stateVectorIO().writeMultiVectorToFile(
850  *finalPointModel_->getFinalPoint().get_x(),stateSoluFileBase_
851  );
852  }
853  if(
854  ( "" != paramSoluFileBase_ )
855  && ( origModel_->Np() > 0 )
856  && ( 0 != finalPointModel_->getFinalPoint().get_p(p_idx_).get() )
857  )
858  {
859  if(out.get())
860  *out << "\nWriting the parameter solution \'p\' to the file(s) with base name \""<<paramSoluFileBase_<<"\" ...\n";
861  parameterVectorIO().writeMultiVectorToFile(
862  *finalPointModel_->getFinalPoint().get_p(p_idx_),paramSoluFileBase_
863  );
864  }
865 }
866 
868  const std::string &outputXmlFileName
869  ) const
870 {
871  std::string xmlOutputFile
872  = ( outputXmlFileName.length() ? outputXmlFileName : paramsUsedXmlOutFileName() );
873  if( paramList_.get() && xmlOutputFile.length() ) {
874  Teuchos::writeParameterListToXmlFile(*paramList_,xmlOutputFile);
875  }
876 }
877 
878 } // namespace MoochoPack
const ostream_ptr_t & get_console_out() const
Get the non-const smart pointer to the set output stream for console outputting.
void setParameterList(RCP< Teuchos::ParameterList > const &paramList)
void setup_commandline_processor(Teuchos::CommandLineProcessor *clp)
Setup the commandline processor to process commandline options.
bool is_null(const boost::shared_ptr< T > &p)
RCP< Teuchos::ParameterList > unsetParameterList()
const RCP< Thyra::ModelEvaluator< value_type > > getOrigModel() const
void readParameters(std::ostream *out)
Force the parameters to be read from a file or from the commandline arguments.
Thyra::ParameterDrivenMultiVectorInput< value_type > x_reader_
RCP< Thyra::ModelEvaluator< value_type > > outerModel_
void setupCLP(Teuchos::CommandLineProcessor *clp)
Sets up the commandline for reading in the parameter list for this object (minus the options for Mooc...
T & get(ParameterList &l, const std::string &name)
ParameterList & set(std::string const &name, T const &value, std::string const &docString="", RCP< const ParameterEntryValidator > const &validator=null)
void set_output_context(const std::string &file_context_postfix, EOutputToBlackHole output_to_black_hole=OUTPUT_TO_BLACK_HOLE_DEFAULT, const int procRank=-1, const int numProcs=-1)
Setup the context for outputting.
RCP< Teuchos::ParameterList > paramList_
RCP< const Teuchos::ParameterList > getValidParameters() const
RCP< ParameterList > sublist(const RCP< ParameterList > &paramList, const std::string &name, bool mustAlreadyExist=false, const std::string &docString="")
T * get() const
MoochoThyraSolver(const std::string &paramsXmlFileName="", const std::string &extraParamsXmlString="", const std::string &paramsUsedXmlOutFileName="", const std::string &paramsXmlFileNameOption="moocho-thyra-params-file", const std::string &extraParamsXmlStringOption="extra-moocho-thyra-params", const std::string &paramsUsedXmlOutFileNameOption="moocho-thyra-params-used-file")
Construct with default settings.
void update_solver() const
Setup the state of the solver and get ready for a solve.
const ostream_ptr_t & get_summary_out() const
Get the non-const smart pointer to the set output stream for summary outputting.
MoochoSolver::ESolutionStatus solve()
basic_OSTab< char > OSTab
RCP< Thyra::DefaultFinalPointCaptureModelEvaluator< value_type > > finalPointModel_
const ostream_ptr_t & get_journal_out() const
Get the non-const smart pointer to the set output stream for journal outputting.
const RCP< Thyra::ModelEvaluator< value_type > > getOuterModel() const
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Thyra::ParameterDrivenMultiVectorInput< value_type > p_reader_
void setOption(const char option_true[], const char option_false[], bool *option_val, const char documentation[]=NULL)
void writeFinalSolution(std::ostream *out=NULL) const
Write the final solution to a file specified by the parameter list option ???.
RCP< Teuchos::ParameterList > getNonconstParameterList()
Ptr< T > ptr() const
std::ostream * out
Implement the NLPFirstOrder interface using a Thyra::ModelEvaluator object.
ParameterList::PrintOptions PLPrintOptions
RCP< Thyra::ModelEvaluator< value_type > > origModel_
void setSolveMode(const ESolveMode solveMode)
Universal interface to a MOOCHO solver.
Implement the NLPFirstOrder interface using a Thyra::ModelEvaluator object.
RCP< std::ostream > generate_output_file(const std::string &fileNameBase) const
Generate an output file given a base file name.
void validateParameters(ParameterList const &validParamList, int const depth=1000, EValidateUsed const validateUsed=VALIDATE_USED_ENABLED, EValidateDefaults const validateDefaults=VALIDATE_DEFAULTS_ENABLED) const
ParameterList & setParameters(const ParameterList &source)
NLP interface class {abstract}.
void writeParamsFile(const std::string &outputXmlFileName="") const
Write the parameters list for a this object to a file after the parameters are read in order to show ...
Solve an optimization problem for states and parameters.
void setModel(const RCP< Thyra::ModelEvaluator< value_type > > &origModel, const int p_idx=0, const int g_idx=0)
RCP< Thyra::DefaultNominalBoundsOverrideModelEvaluator< value_type > > nominalModel_
const Thyra::ModelEvaluatorBase::InArgs< value_type > & getFinalPoint() const
Return the final point.
ESolutionStatus solve_nlp() const
Solve the NLP.
void readInitialGuess(std::ostream *out=NULL)
AbstractLinAlgPack::value_type value_type
RCP< const Teuchos::ParameterList > getParameterList() const
void set_nlp(const nlp_ptr_t &nlp)
Set the NLP to be solved.
void set_output_file_tag(const std::string &)
Set a tag for output file names for all file names that are created internally.
Thyra::ParameterDrivenMultiVectorInput< value_type > p_u_reader_
void setInitialGuess(const RCP< const Thyra::ModelEvaluatorBase::InArgs< value_type > > &initialGuess)
#define TEUCHOS_TEST_FOR_EXCEPT(throw_exception_test)
Thyra::ParameterDrivenMultiVectorInput< value_type > p_l_reader_