Tempus  Version of the Day
Time Integration
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
Tempus_DIRK_FSA.hpp
Go to the documentation of this file.
1 // @HEADER
2 // ****************************************************************************
3 // Tempus: Copyright (2017) Sandia Corporation
4 //
5 // Distributed under BSD 3-clause license (See accompanying file Copyright.txt)
6 // ****************************************************************************
7 // @HEADER
8 
9 #include "Teuchos_UnitTestHarness.hpp"
10 #include "Teuchos_XMLParameterListHelpers.hpp"
11 #include "Teuchos_TimeMonitor.hpp"
12 #include "Teuchos_DefaultComm.hpp"
13 
14 #include "Thyra_VectorStdOps.hpp"
15 #include "Thyra_MultiVectorStdOps.hpp"
16 
17 #include "Tempus_IntegratorBasic.hpp"
18 #include "Tempus_IntegratorForwardSensitivity.hpp"
19 
20 #include "Thyra_DefaultMultiVectorProductVector.hpp"
21 #include "Thyra_DefaultProductVector.hpp"
22 
23 #include "../TestModels/SinCosModel.hpp"
24 #include "../TestUtils/Tempus_ConvergenceTestUtils.hpp"
25 
26 #include <fstream>
27 #include <vector>
28 
29 namespace Tempus_Test {
30 
31 using Teuchos::RCP;
32 using Teuchos::ParameterList;
33 using Teuchos::sublist;
34 using Teuchos::getParametersFromXmlFile;
35 
39 
40 
41 // ************************************************************
42 // ************************************************************
43 void test_sincos_fsa(const std::string& method_name,
44  const bool use_combined_method,
45  const bool use_dfdp_as_tangent,
46  Teuchos::FancyOStream &out, bool &success)
47 {
48  std::vector<std::string> RKMethods;
49  RKMethods.push_back("General DIRK");
50  RKMethods.push_back("RK Backward Euler");
51  RKMethods.push_back("DIRK 1 Stage Theta Method");
52  RKMethods.push_back("RK Implicit 1 Stage 1st order Radau IA");
53  RKMethods.push_back("RK Implicit Midpoint");
54  RKMethods.push_back("SDIRK 2 Stage 2nd order");
55  RKMethods.push_back("RK Implicit 2 Stage 2nd order Lobatto IIIB");
56  RKMethods.push_back("SDIRK 2 Stage 3rd order");
57  RKMethods.push_back("EDIRK 2 Stage 3rd order");
58  RKMethods.push_back("EDIRK 2 Stage Theta Method");
59  RKMethods.push_back("SDIRK 3 Stage 4th order");
60  RKMethods.push_back("SDIRK 5 Stage 4th order");
61  RKMethods.push_back("SDIRK 5 Stage 5th order");
62  RKMethods.push_back("SDIRK 2(1) Pair");
63  RKMethods.push_back("RK Trapezoidal Rule");
64  RKMethods.push_back("RK Crank-Nicolson");
65 
66  // Check that method_name is valid
67  if (method_name != "") {
68  auto it = std::find(RKMethods.begin(), RKMethods.end(), method_name);
69  TEUCHOS_TEST_FOR_EXCEPTION(it == RKMethods.end(), std::logic_error,
70  "Invalid RK method name '" << method_name << "'");
71  }
72 
73  std::vector<double> RKMethodErrors;
74  if (use_combined_method) {
75  RKMethodErrors.push_back(0.000144507);
76  RKMethodErrors.push_back(0.0428449);
77  RKMethodErrors.push_back(0.000297933);
78  RKMethodErrors.push_back(0.0428449);
79  RKMethodErrors.push_back(0.000297933);
80  RKMethodErrors.push_back(0.000144507);
81  RKMethodErrors.push_back(0.000297933);
82  RKMethodErrors.push_back(8.65434e-06);
83  RKMethodErrors.push_back(1.3468e-06);
84  RKMethodErrors.push_back(0.000297933);
85  RKMethodErrors.push_back(5.44037e-07);
86  RKMethodErrors.push_back(2.77342e-09);
87  RKMethodErrors.push_back(1.21689e-10);
88  RKMethodErrors.push_back(0.000603848);
89  RKMethodErrors.push_back(0.000297933);
90  RKMethodErrors.push_back(0.000297933);
91  }
92  else {
93  RKMethodErrors.push_back(0.000125232);
94  RKMethodErrors.push_back(0.0428449);
95  RKMethodErrors.push_back(0.000221049);
96  RKMethodErrors.push_back(0.0383339);
97  RKMethodErrors.push_back(0.000221049);
98  RKMethodErrors.push_back(0.000125232);
99  RKMethodErrors.push_back(0.000272997);
100  RKMethodErrors.push_back(4.79475e-06);
101  RKMethodErrors.push_back(9.63899e-07);
102  RKMethodErrors.push_back(0.000297933);
103  RKMethodErrors.push_back(2.9362e-07);
104  RKMethodErrors.push_back(9.20081e-08);
105  RKMethodErrors.push_back(9.16252e-08);
106  RKMethodErrors.push_back(0.00043969);
107  RKMethodErrors.push_back(0.000297933);
108  RKMethodErrors.push_back(0.000297933);
109  }
110 
111  Teuchos::RCP<const Teuchos::Comm<int> > comm =
112  Teuchos::DefaultComm<int>::getComm();
113  Teuchos::RCP<Teuchos::FancyOStream> my_out =
114  Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
115  my_out->setProcRankAndSize(comm->getRank(), comm->getSize());
116  my_out->setOutputToRootOnly(0);
117 
118  for(std::vector<std::string>::size_type m = 0; m != RKMethods.size(); m++) {
119 
120  // If we were given a method to run, skip this method if it doesn't match
121  if (method_name != "" && RKMethods[m] != method_name)
122  continue;
123 
124  std::string RKMethod_ = RKMethods[m];
125  std::replace(RKMethod_.begin(), RKMethod_.end(), ' ', '_');
126  std::replace(RKMethod_.begin(), RKMethod_.end(), '/', '.');
127  std::vector<double> StepSize;
128  std::vector<double> ErrorNorm;
129  const int nTimeStepSizes = 3; // 7 for error plots
130  double dt = 0.05;
131  double order = 0.0;
132  for (int n=0; n<nTimeStepSizes; n++) {
133 
134  // Read params from .xml file
135  RCP<ParameterList> pList =
136  getParametersFromXmlFile("Tempus_DIRK_SinCos.xml");
137 
138  // Setup the SinCosModel
139  RCP<ParameterList> scm_pl = sublist(pList, "SinCosModel", true);
140  scm_pl->set("Use DfDp as Tangent", use_dfdp_as_tangent);
141  RCP<SinCosModel<double> > model =
142  Teuchos::rcp(new SinCosModel<double>(scm_pl));
143 
144  // Set the Stepper
145  RCP<ParameterList> pl = sublist(pList, "Tempus", true);
146  pl->sublist("Default Stepper").set("Stepper Type", RKMethods[m]);
147  if (RKMethods[m] == "SDIRK 2 Stage 2nd order") {
148  pl->sublist("Default Stepper").set("gamma", 0.2928932188134524);
149  } else if (RKMethods[m] == "SDIRK 2 Stage 3rd order") {
150  pl->sublist("Default Stepper")
151  .set<std::string>("Gamma Type", "3rd Order A-stable");
152  }
153 
154  dt /= 2;
155 
156  // Setup sensitivities
157  ParameterList& sens_pl = pl->sublist("Sensitivities");
158  if (use_combined_method)
159  sens_pl.set("Sensitivity Method", "Combined");
160  else
161  sens_pl.set("Sensitivity Method", "Staggered");
162  sens_pl.set("Use DfDp as Tangent", use_dfdp_as_tangent);
163  ParameterList& interp_pl =
164  pl->sublist("Default Integrator").sublist("Solution History").sublist("Interpolator");
165  interp_pl.set("Interpolator Type", "Lagrange");
166  interp_pl.set("Order", 4); // All RK methods here are at most 5th order
167 
168  // Setup the Integrator and reset initial time step
169  pl->sublist("Default Integrator")
170  .sublist("Time Step Control").set("Initial Time Step", dt);
171  RCP<Tempus::IntegratorForwardSensitivity<double> > integrator =
172  Tempus::integratorForwardSensitivity<double>(pl, model);
173  order = integrator->getStepper()->getOrder();
174 
175  // Initial Conditions
176  // During the Integrator construction, the initial SolutionState
177  // is set by default to model->getNominalVales().get_x(). However,
178  // the application can set it also by integrator->initializeSolutionHistory.
179  RCP<Thyra::VectorBase<double> > x0 =
180  model->getNominalValues().get_x()->clone_v();
181  const int num_param = model->get_p_space(0)->dim();
182  RCP<Thyra::MultiVectorBase<double> > DxDp0 =
183  Thyra::createMembers(model->get_x_space(), num_param);
184  for (int i=0; i<num_param; ++i)
185  Thyra::assign(DxDp0->col(i).ptr(),
186  *(model->getExactSensSolution(i, 0.0).get_x()));
187  integrator->initializeSolutionHistory(0.0, x0, Teuchos::null, Teuchos::null,
188  DxDp0, Teuchos::null, Teuchos::null);
189 
190  // Integrate to timeMax
191  bool integratorStatus = integrator->advanceTime();
192  TEST_ASSERT(integratorStatus)
193 
194  // Test if at 'Final Time'
195  double time = integrator->getTime();
196  double timeFinal = pl->sublist("Default Integrator")
197  .sublist("Time Step Control").get<double>("Final Time");
198  double tol = 100.0 * std::numeric_limits<double>::epsilon();
199  TEST_FLOATING_EQUALITY(time, timeFinal, tol);
200 
201  // Time-integrated solution and the exact solution
202  RCP<const Thyra::VectorBase<double> > x = integrator->getX();
203  RCP<const Thyra::MultiVectorBase<double> > DxDp = integrator->getDxDp();
204  RCP<const Thyra::VectorBase<double> > x_exact =
205  model->getExactSolution(time).get_x();
206  RCP<Thyra::MultiVectorBase<double> > DxDp_exact =
207  Thyra::createMembers(model->get_x_space(), num_param);
208  for (int i=0; i<num_param; ++i)
209  Thyra::assign(DxDp_exact->col(i).ptr(),
210  *(model->getExactSensSolution(i, time).get_x()));
211 
212  // Plot sample solution and exact solution
213  if (comm->getRank() == 0 && n == nTimeStepSizes-1) {
214  typedef Thyra::DefaultMultiVectorProductVector<double> DMVPV;
215 
216  std::ofstream ftmp("Tempus_"+RKMethod_+"_SinCos_Sens.dat");
217  RCP<const SolutionHistory<double> > solutionHistory =
218  integrator->getSolutionHistory();
219  RCP< Thyra::MultiVectorBase<double> > DxDp_exact_plot =
220  Thyra::createMembers(model->get_x_space(), num_param);
221  for (int i=0; i<solutionHistory->getNumStates(); i++) {
222  RCP<const SolutionState<double> > solutionState =
223  (*solutionHistory)[i];
224  double time_i = solutionState->getTime();
225  RCP<const DMVPV> x_prod_plot =
226  Teuchos::rcp_dynamic_cast<const DMVPV>(solutionState->getX());
227  RCP<const Thyra::VectorBase<double> > x_plot =
228  x_prod_plot->getMultiVector()->col(0);
229  RCP<const Thyra::MultiVectorBase<double> > DxDp_plot =
230  x_prod_plot->getMultiVector()->subView(Teuchos::Range1D(1,num_param));
231  RCP<const Thyra::VectorBase<double> > x_exact_plot =
232  model->getExactSolution(time_i).get_x();
233  for (int j=0; j<num_param; ++j)
234  Thyra::assign(DxDp_exact_plot->col(j).ptr(),
235  *(model->getExactSensSolution(j, time_i).get_x()));
236  ftmp << std::fixed << std::setprecision(7)
237  << time_i
238  << std::setw(11) << get_ele(*(x_plot), 0)
239  << std::setw(11) << get_ele(*(x_plot), 1);
240  for (int j=0; j<num_param; ++j)
241  ftmp << std::setw(11) << get_ele(*(DxDp_plot->col(j)), 0)
242  << std::setw(11) << get_ele(*(DxDp_plot->col(j)), 1);
243  ftmp << std::setw(11) << get_ele(*(x_exact_plot), 0)
244  << std::setw(11) << get_ele(*(x_exact_plot), 1);
245  for (int j=0; j<num_param; ++j)
246  ftmp << std::setw(11) << get_ele(*(DxDp_exact_plot->col(j)), 0)
247  << std::setw(11) << get_ele(*(DxDp_exact_plot->col(j)), 1);
248  ftmp << std::endl;
249  }
250  ftmp.close();
251  }
252 
253  // Calculate the error
254  RCP<Thyra::VectorBase<double> > xdiff = x->clone_v();
255  RCP<Thyra::MultiVectorBase<double> > DxDpdiff = DxDp->clone_mv();
256  Thyra::V_StVpStV(xdiff.ptr(), 1.0, *x_exact, -1.0, *(x));
257  Thyra::V_VmV(DxDpdiff.ptr(), *DxDp_exact, *DxDp);
258  StepSize.push_back(dt);
259  double L2norm = Thyra::norm_2(*xdiff);
260  L2norm *= L2norm;
261  Teuchos::Array<double> L2norm_DxDp(num_param);
262  Thyra::norms_2(*DxDpdiff, L2norm_DxDp());
263  for (int i=0; i<num_param; ++i)
264  L2norm += L2norm_DxDp[i]*L2norm_DxDp[i];
265  L2norm = std::sqrt(L2norm);
266  ErrorNorm.push_back(L2norm);
267 
268  //*my_out << " n = " << n << " dt = " << dt << " error = " << L2norm
269  // << std::endl;
270  }
271 
272  if (comm->getRank() == 0) {
273  std::ofstream ftmp("Tempus_"+RKMethod_+"_SinCos_Sens-Error.dat");
274  double error0 = 0.8*ErrorNorm[0];
275  for (int n=0; n<(int)StepSize.size(); n++) {
276  ftmp << StepSize[n] << " " << ErrorNorm[n] << " "
277  << error0*(pow(StepSize[n]/StepSize[0],order)) << std::endl;
278  }
279  ftmp.close();
280  }
281 
282  //if (RKMethods[m] == "SDIRK 5 Stage 4th order") {
283  // StepSize.pop_back(); StepSize.pop_back();
284  // ErrorNorm.pop_back(); ErrorNorm.pop_back();
285  //} else if (RKMethods[m] == "SDIRK 5 Stage 5th order") {
286  // StepSize.pop_back(); StepSize.pop_back(); StepSize.pop_back();
287  // ErrorNorm.pop_back(); ErrorNorm.pop_back(); ErrorNorm.pop_back();
288  //}
289 
290  // Check the order and intercept
291  double slope = computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
292  *my_out << " Stepper = " << RKMethods[m] << std::endl;
293  *my_out << " =========================" << std::endl;
294  *my_out << " Expected order: " << order << std::endl;
295  *my_out << " Observed order: " << slope << std::endl;
296  *my_out << " =========================" << std::endl;
297 
298  // Can only seem to get at most 4th order when using staggered method
299  double order_expected = use_combined_method ? order : std::min(order,4.0);
300  TEST_FLOATING_EQUALITY( slope, order_expected, 0.03 );
301  TEST_FLOATING_EQUALITY( ErrorNorm[0], RKMethodErrors[m], 5.0e-4 );
302 
303  }
304  Teuchos::TimeMonitor::summarize();
305 }
306 
307 } // namespace Tempus_Test
Sine-Cosine model problem from Rythmos. This is a canonical Sine-Cosine differential equation with a...
void test_sincos_fsa(const bool use_combined_method, const bool use_dfdp_as_tangent, Teuchos::FancyOStream &out, bool &success)
SolutionHistory is basically a container of SolutionStates. SolutionHistory maintains a collection of...
std::string method_name
Solution state for integrators and steppers. SolutionState contains the metadata for solutions and th...