Tempus Version of the Day
Time Integration
Loading...
Searching...
No Matches
Tempus_BackwardEuler_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 "Tempus_config.hpp"
16#include "Tempus_IntegratorBasic.hpp"
17#include "Tempus_IntegratorAdjointSensitivity.hpp"
18
19#include "Thyra_VectorStdOps.hpp"
20#include "Thyra_MultiVectorStdOps.hpp"
21
22#include "../TestModels/SinCosModel.hpp"
25
26#include "Thyra_DefaultMultiVectorProductVector.hpp"
27
28#include <algorithm>
29#include <vector>
30#include <fstream>
31#include <sstream>
32#include <limits>
33
34namespace Tempus_Test {
35
36using Teuchos::getParametersFromXmlFile;
37using Teuchos::ParameterList;
38using Teuchos::RCP;
39using Teuchos::sublist;
40
44
45// ************************************************************
46// ************************************************************
47TEUCHOS_UNIT_TEST(BackwardEuler, SinCos_ASA)
48{
49 std::vector<double> StepSize;
50 std::vector<double> ErrorNorm;
51 const int nTimeStepSizes = 7;
52 double dt = 0.2;
53 double order = 0.0;
54 Teuchos::RCP<const Teuchos::Comm<int> > comm =
55 Teuchos::DefaultComm<int>::getComm();
56 for (int n = 0; n < nTimeStepSizes; n++) {
57 // Read params from .xml file
58 RCP<ParameterList> pList =
59 getParametersFromXmlFile("Tempus_BackwardEuler_SinCos_ASA.xml");
60
61 // Setup the SinCosModel
62 // Here we test using an explicit adjoint model for adjoint sensitivities
63 RCP<ParameterList> scm_pl = sublist(pList, "SinCosModel", true);
64 RCP<SinCosModel<double> > model =
65 Teuchos::rcp(new SinCosModel<double>(scm_pl));
66 RCP<SinCosModelAdjoint<double> > adjoint_model =
67 Teuchos::rcp(new SinCosModelAdjoint<double>(scm_pl));
68
69 dt /= 2;
70
71 // Setup sensitivities
72 RCP<ParameterList> pl = sublist(pList, "Tempus", true);
73 ParameterList& sens_pl = pl->sublist("Sensitivities");
74 sens_pl.set("Mass Matrix Is Identity", false); // Just for testing
75 ParameterList& interp_pl = pl->sublist("Default Integrator")
76 .sublist("Solution History")
77 .sublist("Interpolator");
78 interp_pl.set("Interpolator Type", "Lagrange");
79 interp_pl.set("Order", 0);
80
81 // Set FSAL to false, because it is not currently setup for ASA.
82 pl->sublist("Default Stepper").set("Use FSAL", false);
83
84 // Set IC consistency check to false, because it is not currently
85 // setup for ASA.
86 pl->sublist("Default Stepper")
87 .set("Initial Condition Consistency Check", false);
88
89 // Setup the Integrator and reset initial time step
90 pl->sublist("Default Integrator")
91 .sublist("Time Step Control")
92 .set("Initial Time Step", dt);
93 RCP<Tempus::IntegratorAdjointSensitivity<double> > integrator =
95 adjoint_model);
96 order = integrator->getStepper()->getOrder();
97
98 // Initial Conditions
99 double t0 = pl->sublist("Default Integrator")
100 .sublist("Time Step Control")
101 .get<double>("Initial Time");
102 RCP<const Thyra::VectorBase<double> > x0 =
103 model->getExactSolution(t0).get_x();
104 const int num_param = model->get_p_space(0)->dim();
105 RCP<Thyra::MultiVectorBase<double> > DxDp0 =
106 Thyra::createMembers(model->get_x_space(), num_param);
107 for (int i = 0; i < num_param; ++i)
108 Thyra::assign(DxDp0->col(i).ptr(),
109 *(model->getExactSensSolution(i, t0).get_x()));
110 integrator->initializeSolutionHistory(t0, x0, Teuchos::null, Teuchos::null,
111 DxDp0, Teuchos::null, Teuchos::null);
112
113 // Integrate to timeMax
114 bool integratorStatus = integrator->advanceTime();
115 TEST_ASSERT(integratorStatus)
116
117 // Test if at 'Final Time'
118 double time = integrator->getTime();
119 double timeFinal = pl->sublist("Default Integrator")
120 .sublist("Time Step Control")
121 .get<double>("Final Time");
122 TEST_FLOATING_EQUALITY(time, timeFinal, 1.0e-14);
123
124 // Time-integrated solution and the exact solution along with
125 // sensitivities (relying on response g(x) = x). Note we must transpose
126 // dg/dp since the integrator returns it in gradient form.
127 RCP<const Thyra::VectorBase<double> > x = integrator->getX();
128 RCP<const Thyra::MultiVectorBase<double> > DgDp = integrator->getDgDp();
129 RCP<Thyra::MultiVectorBase<double> > DxDp =
130 Thyra::createMembers(model->get_x_space(), num_param);
131 {
132 Thyra::ConstDetachedMultiVectorView<double> dgdp_view(*DgDp);
133 Thyra::DetachedMultiVectorView<double> dxdp_view(*DxDp);
134 const int num_g = DgDp->domain()->dim();
135 for (int i = 0; i < num_g; ++i)
136 for (int j = 0; j < num_param; ++j) dxdp_view(i, j) = dgdp_view(j, i);
137 }
138 RCP<const Thyra::VectorBase<double> > x_exact =
139 model->getExactSolution(time).get_x();
140 RCP<Thyra::MultiVectorBase<double> > DxDp_exact =
141 Thyra::createMembers(model->get_x_space(), num_param);
142 for (int i = 0; i < num_param; ++i)
143 Thyra::assign(DxDp_exact->col(i).ptr(),
144 *(model->getExactSensSolution(i, time).get_x()));
145
146 // Plot sample solution, exact solution, and adjoint solution
147 if (comm->getRank() == 0 && n == nTimeStepSizes - 1) {
148 typedef Thyra::DefaultProductVector<double> DPV;
149 typedef Thyra::DefaultMultiVectorProductVector<double> DMVPV;
150
151 std::ofstream ftmp("Tempus_BackwardEuler_SinCos_AdjSens.dat");
152 RCP<const SolutionHistory<double> > solutionHistory =
153 integrator->getSolutionHistory();
154 for (int i = 0; i < solutionHistory->getNumStates(); i++) {
155 RCP<const SolutionState<double> > solutionState = (*solutionHistory)[i];
156 const double time_i = solutionState->getTime();
157 RCP<const DPV> x_prod_plot =
158 Teuchos::rcp_dynamic_cast<const DPV>(solutionState->getX());
159 RCP<const Thyra::VectorBase<double> > x_plot =
160 x_prod_plot->getVectorBlock(0);
161 RCP<const DMVPV> adjoint_prod_plot =
162 Teuchos::rcp_dynamic_cast<const DMVPV>(
163 x_prod_plot->getVectorBlock(1));
164 RCP<const Thyra::MultiVectorBase<double> > adjoint_plot =
165 adjoint_prod_plot->getMultiVector();
166 RCP<const Thyra::VectorBase<double> > x_exact_plot =
167 model->getExactSolution(time_i).get_x();
168 ftmp << std::fixed << std::setprecision(7) << time_i << std::setw(11)
169 << get_ele(*(x_plot), 0) << std::setw(11) << get_ele(*(x_plot), 1)
170 << std::setw(11) << get_ele(*(adjoint_plot->col(0)), 0)
171 << std::setw(11) << get_ele(*(adjoint_plot->col(0)), 1)
172 << std::setw(11) << get_ele(*(adjoint_plot->col(1)), 0)
173 << std::setw(11) << get_ele(*(adjoint_plot->col(1)), 1)
174 << std::setw(11) << get_ele(*(x_exact_plot), 0) << std::setw(11)
175 << get_ele(*(x_exact_plot), 1) << std::endl;
176 }
177 ftmp.close();
178 }
179
180 // Calculate the error
181 RCP<Thyra::VectorBase<double> > xdiff = x->clone_v();
182 RCP<Thyra::MultiVectorBase<double> > DxDpdiff = DxDp->clone_mv();
183 Thyra::V_StVpStV(xdiff.ptr(), 1.0, *x_exact, -1.0, *(x));
184 Thyra::V_VmV(DxDpdiff.ptr(), *DxDp_exact, *DxDp);
185 StepSize.push_back(dt);
186 double L2norm = Thyra::norm_2(*xdiff);
187 L2norm *= L2norm;
188 Teuchos::Array<double> L2norm_DxDp(num_param);
189 Thyra::norms_2(*DxDpdiff, L2norm_DxDp());
190 for (int i = 0; i < num_param; ++i)
191 L2norm += L2norm_DxDp[i] * L2norm_DxDp[i];
192 L2norm = std::sqrt(L2norm);
193 ErrorNorm.push_back(L2norm);
194
195 // out << " n = " << n << " dt = " << dt << " error = " << L2norm
196 // << std::endl;
197 }
198
199 // Check the order and intercept
200 double slope = computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
201 out << " Stepper = BackwardEuler" << std::endl;
202 out << " =========================" << std::endl;
203 out << " Expected order: " << order << std::endl;
204 out << " Observed order: " << slope << std::endl;
205 out << " =========================" << std::endl;
206 TEST_FLOATING_EQUALITY(slope, order, 0.015);
207 TEST_FLOATING_EQUALITY(ErrorNorm[0], 0.142525, 1.0e-4);
208
209 if (comm->getRank() == 0) {
210 std::ofstream ftmp("Tempus_BackwardEuler_SinCos_AdjSens-Error.dat");
211 double error0 = 0.8 * ErrorNorm[0];
212 for (int n = 0; n < nTimeStepSizes; n++) {
213 ftmp << StepSize[n] << " " << ErrorNorm[n] << " "
214 << error0 * (StepSize[n] / StepSize[0]) << std::endl;
215 }
216 ftmp.close();
217 }
218}
219
220// ************************************************************
221// ************************************************************
222// Adjoint sensitivities of the time-integrated response
223// J = int_{t0}^{T} x(t) dt.
224TEUCHOS_UNIT_TEST(BackwardEuler, SinCos_ASA_TimeIntegral)
225{
226 std::vector<double> StepSize, ErrorNorm;
227 double order = 0.0;
229 "Tempus_BackwardEuler_SinCos_ASA.xml",
230 [](ParameterList& pl) {
231 pl.sublist("Sensitivities").set("Mass Matrix Is Identity", false);
232 },
233 "Time Integral", std::vector<double>(), 6, 0.1, true, StepSize,
234 ErrorNorm, order, out, success);
235
236 const double slope = computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
237 out << " Expected order: " << order << " Observed order: " << slope << std::endl;
238 TEST_FLOATING_EQUALITY(slope, order, 0.04);
239}
240
241// ************************************************************
242// ************************************************************
243// Adjoint sensitivities of the response J = sum_k x(t_k), with response times
244// on the time grid, including the initial and final times.
245TEUCHOS_UNIT_TEST(BackwardEuler, SinCos_ASA_SumOverTimes)
246{
247 std::vector<double> StepSize, ErrorNorm;
248 double order = 0.0;
250 "Tempus_BackwardEuler_SinCos_ASA.xml",
251 [](ParameterList& pl) {
252 pl.sublist("Sensitivities").set("Mass Matrix Is Identity", false);
253 },
254 "Sum Over Times", {0.1, 0.4, 0.7, 1.0}, 6, 0.1, true, StepSize,
255 ErrorNorm, order, out, success);
256
257 const double slope = computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
258 out << " Expected order: " << order << " Observed order: " << slope << std::endl;
259 TEST_FLOATING_EQUALITY(slope, order, 0.04);
260}
261
262// ************************************************************
263// ************************************************************
264// Same as SinCos_ASA_SumOverTimes, with a response time that is not on the
265// time grid. With "Variable" time steps the forward time steps land on it.
266TEUCHOS_UNIT_TEST(BackwardEuler, SinCos_ASA_SumOverTimes_Variable)
267{
268 std::vector<double> StepSize, ErrorNorm;
269 double order = 0.0;
271 "Tempus_BackwardEuler_SinCos_ASA.xml",
272 [](ParameterList& pl) {
273 pl.sublist("Sensitivities").set("Mass Matrix Is Identity", false);
274 // Variable time steps, which only change to land on time events
275 ParameterList& tscs = pl.sublist("Default Integrator")
276 .sublist("Time Step Control")
277 .sublist("Time Step Control Strategy");
278 tscs.set("Strategy Type", "Basic VS");
279 tscs.set("Amplification Factor", 1.5);
280 tscs.set("Reduction Factor", 0.5);
281 tscs.set("Minimum Value Monitoring Function", 0.0);
282 tscs.set("Maximum Value Monitoring Function", 1.0e+10);
283 },
284 "Sum Over Times", {0.1 + 1.0 / 3.0, 0.8, 1.0}, 6, 0.1, true, StepSize,
285 ErrorNorm, order, out, success);
286
287 const double slope = computeLinearRegressionLogLog<double>(StepSize, ErrorNorm);
288 out << " Expected order: " << order << " Observed order: " << slope << std::endl;
289 TEST_FLOATING_EQUALITY(slope, order, 0.04);
290}
291
292// ************************************************************
293// ************************************************************
294// With "Constant" time steps (the default time step control strategy), a
295// response time that is not on the time grid is an error.
296TEUCHOS_UNIT_TEST(BackwardEuler, SinCos_ASA_SumOverTimes_OffGrid)
297{
298 std::vector<double> StepSize, ErrorNorm;
299 double order = 0.0;
301 "Tempus_BackwardEuler_SinCos_ASA.xml",
302 [](ParameterList& pl) {
303 pl.sublist("Sensitivities")
304 .set("Mass Matrix Is Identity", false);
305 },
306 "Sum Over Times", {0.1 + 1.0 / 3.0, 1.0}, 1, 0.1, true,
307 StepSize, ErrorNorm, order, out, success),
308 std::logic_error);
309}
310
311// ************************************************************
312// ************************************************************
313// NOX row sum scaling ("Function Scaling" = "Row Sum") of the nonlinear solves
314// of the forward and adjoint problems, with the explicit adjoint model. The
315// forward and adjoint integrators are created from the same parameters, in
316// which the forward solver stores its row sum scaling objects (in the forward
317// residual space), and the adjoint operator, a blocked operator with a scaled
318// identity block, must support the row sums and the scaling. The problem is
319// linear and the linear solves are direct, so the errors are those without
320// scaling.
321TEUCHOS_UNIT_TEST(BackwardEuler, SinCos_ASA_RowSumScaling)
322{
323 const std::vector<double> responseTimes = {0.4, 1.0};
324
325 // Parameters with or without row sum scaling
326 auto configure = [](const bool rowSumScaling) {
327 return [rowSumScaling](ParameterList& pl) {
328 pl.sublist("Sensitivities").set("Mass Matrix Is Identity", false);
329 if (rowSumScaling)
330 pl.sublist("Default Stepper")
331 .sublist("Default Solver")
332 .sublist("NOX")
333 .sublist("Thyra Group Options")
334 .set("Function Scaling", "Row Sum");
335 };
336 };
337
338 std::vector<double> StepSize, ErrorNorm, StepSizeScaled, ErrorNormScaled;
339 double order = 0.0;
341 "Tempus_BackwardEuler_SinCos_ASA.xml", configure(false),
342 "Sum Over Times", responseTimes, 3, 0.1, true, StepSize, ErrorNorm,
343 order, out, success);
345 "Tempus_BackwardEuler_SinCos_ASA.xml", configure(true), "Sum Over Times",
346 responseTimes, 3, 0.1, true, StepSizeScaled, ErrorNormScaled, order, out,
347 success);
348
349 TEST_EQUALITY(ErrorNormScaled.size(), ErrorNorm.size());
350 for (std::size_t n = 0; n < std::min(ErrorNorm.size(), ErrorNormScaled.size());
351 ++n)
352 TEST_FLOATING_EQUALITY(ErrorNormScaled[n], ErrorNorm[n], 1.0e-8);
353}
354
355} // namespace Tempus_Test
SolutionHistory is basically a container of SolutionStates. SolutionHistory maintains a collection of...
Solution state for integrators and steppers.
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.