Tempus Version of the Day
Time Integration
Loading...
Searching...
No Matches
Tempus_ExplicitRK_ASA.cpp
Go to the documentation of this file.
1//@HEADER
2// *****************************************************************************
3// Tempus: Time Integration and Sensitivity Analysis Package
4//
5// Copyright 2017 NTESS and the Tempus contributors.
6// SPDX-License-Identifier: BSD-3-Clause
7// *****************************************************************************
8//@HEADER
9
10#include "Teuchos_UnitTestHarness.hpp"
11#include "Teuchos_XMLParameterListHelpers.hpp"
12#include "Teuchos_TimeMonitor.hpp"
13#include "Teuchos_DefaultComm.hpp"
14
15#include "Thyra_VectorStdOps.hpp"
16#include "Thyra_MultiVectorStdOps.hpp"
17
18#include "Tempus_IntegratorBasic.hpp"
19#include "Tempus_IntegratorAdjointSensitivity.hpp"
20
21#include "Thyra_DefaultMultiVectorProductVector.hpp"
22#include "Thyra_DefaultProductVector.hpp"
23
24#include "../TestModels/SinCosModel.hpp"
27
28#include <fstream>
29#include <vector>
30
31namespace Tempus_Test {
32
33using Teuchos::getParametersFromXmlFile;
34using Teuchos::ParameterList;
35using Teuchos::RCP;
36using Teuchos::sublist;
37
38using Tempus::IntegratorBasic;
39using Tempus::SolutionHistory;
40using Tempus::SolutionState;
41
42// ************************************************************
43// ************************************************************
44TEUCHOS_UNIT_TEST(ExplicitRK, SinCos_ASA)
45{
46 std::vector<std::string> RKMethods;
47 RKMethods.push_back("RK Forward Euler");
48 RKMethods.push_back("RK Explicit 4 Stage");
49 RKMethods.push_back("RK Explicit 3/8 Rule");
50 RKMethods.push_back("RK Explicit 4 Stage 3rd order by Runge");
51 RKMethods.push_back("RK Explicit 5 Stage 3rd order by Kinnmark and Gray");
52 RKMethods.push_back("RK Explicit 3 Stage 3rd order");
53 RKMethods.push_back("RK Explicit 3 Stage 3rd order TVD");
54 RKMethods.push_back("RK Explicit 3 Stage 3rd order by Heun");
55 RKMethods.push_back("RK Explicit Midpoint");
56 RKMethods.push_back("RK Explicit Trapezoidal");
57 RKMethods.push_back("Heuns Method");
58 RKMethods.push_back("General ERK");
59
60 std::vector<double> RKMethodErrors;
61 RKMethodErrors.push_back(0.154904);
62 RKMethodErrors.push_back(4.55982e-06);
63 RKMethodErrors.push_back(4.79132e-06);
64 RKMethodErrors.push_back(0.000113603);
65 RKMethodErrors.push_back(4.98796e-05);
66 RKMethodErrors.push_back(0.00014564);
67 RKMethodErrors.push_back(0.000121968);
68 RKMethodErrors.push_back(0.000109495);
69 RKMethodErrors.push_back(0.00559871);
70 RKMethodErrors.push_back(0.00710492);
71 RKMethodErrors.push_back(0.00710492);
72 RKMethodErrors.push_back(4.55982e-06);
73
74 Teuchos::RCP<const Teuchos::Comm<int> > comm =
75 Teuchos::DefaultComm<int>::getComm();
76
77 for (std::vector<std::string>::size_type m = 0; m != RKMethods.size(); m++) {
78 std::string RKMethod_ = RKMethods[m];
79 std::replace(RKMethod_.begin(), RKMethod_.end(), ' ', '_');
80 std::replace(RKMethod_.begin(), RKMethod_.end(), '/', '.');
81 std::vector<double> StepSize;
82 std::vector<double> ErrorNorm;
83 const int nTimeStepSizes = 6;
84 double dt = 0.2;
85 double order = 0.0;
86 for (int n = 0; n < nTimeStepSizes; n++) {
87 // Read params from .xml file
88 RCP<ParameterList> pList =
89 getParametersFromXmlFile("Tempus_ExplicitRK_SinCos.xml");
90
91 // Setup the SinCosModel
92 RCP<ParameterList> scm_pl = sublist(pList, "SinCosModel", true);
93 RCP<SinCosModel<double> > model =
94 Teuchos::rcp(new SinCosModel<double>(scm_pl));
95
96 // Set the Stepper
97 RCP<ParameterList> pl = sublist(pList, "Tempus", true);
98 if (RKMethods[m] == "General ERK") {
99 pl->sublist("Demo Integrator").set("Stepper Name", "Demo Stepper 2");
100 pl->sublist("Demo Stepper 2")
101 .set("Initial Condition Consistency", "None");
102 pl->sublist("Demo Stepper 2")
103 .set("Initial Condition Consistency Check", false);
104 }
105 else {
106 pl->sublist("Demo Stepper").set("Stepper Type", RKMethods[m]);
107 pl->sublist("Demo Stepper")
108 .set("Initial Condition Consistency", "None");
109 pl->sublist("Demo Stepper")
110 .set("Initial Condition Consistency Check", false);
111 }
112
113 dt /= 2;
114
115 // Setup sensitivities
116 ParameterList& sens_pl = pl->sublist("Sensitivities");
117 sens_pl.set("Mass Matrix Is Identity", true); // Necessary for explicit
118 ParameterList& interp_pl = pl->sublist("Demo Integrator")
119 .sublist("Solution History")
120 .sublist("Interpolator");
121 interp_pl.set("Interpolator Type", "Lagrange");
122 interp_pl.set("Order", 3); // All RK methods here are at most 4th order
123
124 // Setup the Integrator and reset initial time step
125 pl->sublist("Demo Integrator")
126 .sublist("Time Step Control")
127 .set("Initial Time Step", dt);
128 RCP<Tempus::IntegratorAdjointSensitivity<double> > integrator =
130 order = integrator->getStepper()->getOrder();
131
132 // Initial Conditions
133 double t0 = pl->sublist("Demo Integrator")
134 .sublist("Time Step Control")
135 .get<double>("Initial Time");
136 // RCP<const Thyra::VectorBase<double> > x0 =
137 // model->getExactSolution(t0).get_x()->clone_v();
138 RCP<Thyra::VectorBase<double> > x0 =
139 model->getNominalValues().get_x()->clone_v();
140 const int num_param = model->get_p_space(0)->dim();
141 RCP<Thyra::MultiVectorBase<double> > DxDp0 =
142 Thyra::createMembers(model->get_x_space(), num_param);
143 for (int i = 0; i < num_param; ++i)
144 Thyra::assign(DxDp0->col(i).ptr(),
145 *(model->getExactSensSolution(i, t0).get_x()));
146 integrator->initializeSolutionHistory(t0, x0, Teuchos::null,
147 Teuchos::null, DxDp0, Teuchos::null,
148 Teuchos::null);
149
150 // Integrate to timeMax
151 bool integratorStatus = integrator->advanceTime();
152 TEST_ASSERT(integratorStatus)
153
154 // Test if at 'Final Time'
155 double time = integrator->getTime();
156 double timeFinal = pl->sublist("Demo Integrator")
157 .sublist("Time Step Control")
158 .get<double>("Final Time");
159 TEST_FLOATING_EQUALITY(time, timeFinal, 1.0e-14);
160
161 // Time-integrated solution and the exact solution along with
162 // sensitivities (relying on response g(x) = x). Note we must transpose
163 // dg/dp since the integrator returns it in gradient form.
164 RCP<const Thyra::VectorBase<double> > x = integrator->getX();
165 RCP<const Thyra::MultiVectorBase<double> > DgDp = integrator->getDgDp();
166 RCP<Thyra::MultiVectorBase<double> > DxDp =
167 Thyra::createMembers(model->get_x_space(), num_param);
168 {
169 Thyra::ConstDetachedMultiVectorView<double> dgdp_view(*DgDp);
170 Thyra::DetachedMultiVectorView<double> dxdp_view(*DxDp);
171 const int num_g = DgDp->domain()->dim();
172 for (int i = 0; i < num_g; ++i)
173 for (int j = 0; j < num_param; ++j) dxdp_view(i, j) = dgdp_view(j, i);
174 }
175 RCP<const Thyra::VectorBase<double> > x_exact =
176 model->getExactSolution(time).get_x();
177 RCP<Thyra::MultiVectorBase<double> > DxDp_exact =
178 Thyra::createMembers(model->get_x_space(), num_param);
179 for (int i = 0; i < num_param; ++i)
180 Thyra::assign(DxDp_exact->col(i).ptr(),
181 *(model->getExactSensSolution(i, time).get_x()));
182
183 // Plot sample solution, exact solution, and adjoint solution
184 if (comm->getRank() == 0 && n == nTimeStepSizes - 1) {
185 typedef Thyra::DefaultProductVector<double> DPV;
186 typedef Thyra::DefaultMultiVectorProductVector<double> DMVPV;
187
188 std::ofstream ftmp("Tempus_" + RKMethod_ + "_SinCos_AdjSens.dat");
189 RCP<const SolutionHistory<double> > solutionHistory =
190 integrator->getSolutionHistory();
191 for (int i = 0; i < solutionHistory->getNumStates(); i++) {
192 RCP<const SolutionState<double> > solutionState =
193 (*solutionHistory)[i];
194 const double time_i = solutionState->getTime();
195 RCP<const DPV> x_prod_plot =
196 Teuchos::rcp_dynamic_cast<const DPV>(solutionState->getX());
197 RCP<const Thyra::VectorBase<double> > x_plot =
198 x_prod_plot->getVectorBlock(0);
199 RCP<const DMVPV> adjoint_prod_plot =
200 Teuchos::rcp_dynamic_cast<const DMVPV>(
201 x_prod_plot->getVectorBlock(1));
202 RCP<const Thyra::MultiVectorBase<double> > adjoint_plot =
203 adjoint_prod_plot->getMultiVector();
204 RCP<const Thyra::VectorBase<double> > x_exact_plot =
205 model->getExactSolution(time_i).get_x();
206 ftmp << std::fixed << std::setprecision(7) << time_i << std::setw(11)
207 << get_ele(*(x_plot), 0) << std::setw(11)
208 << get_ele(*(x_plot), 1) << std::setw(11)
209 << get_ele(*(adjoint_plot->col(0)), 0) << std::setw(11)
210 << get_ele(*(adjoint_plot->col(0)), 1) << std::setw(11)
211 << get_ele(*(adjoint_plot->col(1)), 0) << std::setw(11)
212 << get_ele(*(adjoint_plot->col(1)), 1) << std::setw(11)
213 << get_ele(*(x_exact_plot), 0) << std::setw(11)
214 << get_ele(*(x_exact_plot), 1) << std::endl;
215 }
216 ftmp.close();
217 }
218
219 // Calculate the error
220 RCP<Thyra::VectorBase<double> > xdiff = x->clone_v();
221 RCP<Thyra::MultiVectorBase<double> > DxDpdiff = DxDp->clone_mv();
222 Thyra::V_StVpStV(xdiff.ptr(), 1.0, *x_exact, -1.0, *(x));
223 Thyra::V_VmV(DxDpdiff.ptr(), *DxDp_exact, *DxDp);
224 StepSize.push_back(dt);
225 double L2norm = Thyra::norm_2(*xdiff);
226 L2norm *= L2norm;
227 Teuchos::Array<double> L2norm_DxDp(num_param);
228 Thyra::norms_2(*DxDpdiff, L2norm_DxDp());
229 for (int i = 0; i < num_param; ++i)
230 L2norm += L2norm_DxDp[i] * L2norm_DxDp[i];
231 L2norm = std::sqrt(L2norm);
232 ErrorNorm.push_back(L2norm);
233
234 // out << " n = " << n << " dt = " << dt << " error = " << L2norm
235 // << std::endl;
236 }
237
238 // Check the order and intercept
239 double slope = computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
240 out << " Stepper = " << RKMethods[m] << std::endl;
241 out << " =========================" << std::endl;
242 out << " Expected order: " << order << std::endl;
243 out << " Observed order: " << slope << std::endl;
244 out << " =========================" << std::endl;
245 TEST_FLOATING_EQUALITY(slope, order, 0.015);
246 TEST_FLOATING_EQUALITY(ErrorNorm[0], RKMethodErrors[m], 1.0e-4);
247
248 if (comm->getRank() == 0) {
249 std::ofstream ftmp("Tempus_" + RKMethod_ + "_SinCos_AdjSens-Error.dat");
250 double error0 = 0.8 * ErrorNorm[0];
251 for (int n = 0; n < nTimeStepSizes; n++) {
252 ftmp << StepSize[n] << " " << ErrorNorm[n] << " "
253 << error0 * (pow(StepSize[n] / StepSize[0], order)) << std::endl;
254 }
255 ftmp.close();
256 }
257 }
258
259 Teuchos::TimeMonitor::summarize();
260}
261
262// ************************************************************
263// ************************************************************
264// Adjoint sensitivities of the time-integrated response
265// J = int_{t0}^{T} x(t) dt, with RK Explicit 4 Stage.
266TEUCHOS_UNIT_TEST(ExplicitRK, SinCos_ASA_TimeIntegral)
267{
268 std::vector<double> StepSize, ErrorNorm;
269 double order = 0.0;
271 "Tempus_ExplicitRK_SinCos.xml",
272 [](ParameterList& pl) {
273 pl.sublist("Demo Stepper").set("Stepper Type", "RK Explicit 4 Stage");
274 pl.sublist("Demo Stepper")
275 .set("Initial Condition Consistency", "None");
276 pl.sublist("Demo Stepper")
277 .set("Initial Condition Consistency Check", false);
278 pl.sublist("Sensitivities").set("Mass Matrix Is Identity", true);
279 ParameterList& interp_pl = pl.sublist("Demo Integrator")
280 .sublist("Solution History")
281 .sublist("Interpolator");
282 interp_pl.set("Interpolator Type", "Lagrange");
283 interp_pl.set("Order", 3);
284 },
285 "Time Integral", std::vector<double>(), 5, 0.1, false, StepSize, ErrorNorm,
286 order, out, success);
287
288 const double slope = computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
289 out << " Expected order: " << order << " Observed order: " << slope << std::endl;
290 TEST_FLOATING_EQUALITY(slope, order, 0.04);
291}
292
293// ************************************************************
294// ************************************************************
295// Adjoint sensitivities of the response J = sum_k x(t_k), including the
296// initial and final times, with RK Explicit 4 Stage.
297TEUCHOS_UNIT_TEST(ExplicitRK, SinCos_ASA_SumOverTimes)
298{
299 std::vector<double> StepSize, ErrorNorm;
300 double order = 0.0;
302 "Tempus_ExplicitRK_SinCos.xml",
303 [](ParameterList& pl) {
304 pl.sublist("Demo Stepper").set("Stepper Type", "RK Explicit 4 Stage");
305 pl.sublist("Demo Stepper")
306 .set("Initial Condition Consistency", "None");
307 pl.sublist("Demo Stepper")
308 .set("Initial Condition Consistency Check", false);
309 pl.sublist("Sensitivities").set("Mass Matrix Is Identity", true);
310 ParameterList& interp_pl = pl.sublist("Demo Integrator")
311 .sublist("Solution History")
312 .sublist("Interpolator");
313 interp_pl.set("Interpolator Type", "Lagrange");
314 interp_pl.set("Order", 3);
315 },
316 "Sum Over Times", {0.0, 0.3, 0.6, 1.0}, 5, 0.1, false, StepSize, ErrorNorm, order, out, success);
317
318 const double slope =
319 computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
320 out << " Expected order: " << order << " Observed order: " << slope << std::endl;
321 TEST_FLOATING_EQUALITY(slope, order, 0.04);
322}
323
324} // namespace Tempus_Test
Sine-Cosine model problem from Rythmos. This is a canonical Sine-Cosine differential equation.
TEUCHOS_UNIT_TEST(BackwardEuler, SinCos_ASA)
void computeSinCosAdjointResponseErrors(const std::string &xmlFile, const std::function< void(Teuchos::ParameterList &)> &configure, const std::string &responseType, const std::vector< double > &responseTimes, const int nTimeStepSizes, const double dt0, const bool useAdjointModel, std::vector< double > &stepSizes, std::vector< double > &errors, double &stepperOrder, Teuchos::FancyOStream &out, bool &success)
Solve the SinCos adjoint problem with the "Time Integral" or "Sum Over Times" response for a sequence...
Scalar computeLinearRegressionLogLog(std::vector< Scalar > &x, std::vector< Scalar > &y)
Teuchos::RCP< IntegratorAdjointSensitivity< Scalar > > createIntegratorAdjointSensitivity()
Nonmember constructor.