Debian Codegraph @

packages/rol/example/PDE-OPT/dynamic/navier-stokes/example_02.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Rapid Optimization Library (ROL) Package
4 //
5 // Copyright 2014 NTESS and the ROL contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 /*! \file example_01_l1.cpp
11 \brief Shows how to solve the Navier-Stokes control problem.
12 */
13
14 #include "Teuchos_Comm.hpp"
15 #include "Teuchos_GlobalMPISession.hpp"
16 #include "Tpetra_Core.hpp"
17 #include "Tpetra_Version.hpp"
18
19 #include <iostream>
20 #include <algorithm>
21 //#include <fenv.h>
22
23 #include "ROL_Bounds.hpp"
24 #include "ROL_Stream.hpp"
25 #include "ROL_ParameterList.hpp"
26 #include "ROL_OptimizationSolver.hpp"
27 #include "ROL_ReducedDynamicObjective.hpp"
28 #include "ROL_DynamicConstraintCheck.hpp"
29 #include "ROL_DynamicObjectiveCheck.hpp"
30
31 #include "../../TOOLS/dynconstraint.hpp"
32 #include "../../TOOLS/pdeconstraint.hpp"
33 #include "../../TOOLS/pdeobjective.hpp"
34 #include "../../TOOLS/ltiobjective.hpp"
35 #include "../../TOOLS/meshreader.hpp"
36 #include "../../TOOLS/pdevector.hpp"
37 #include "dynpde_navier-stokes.hpp"
38 #include "obj_navier-stokes.hpp"
39 #include "initial_condition.hpp"
40 #include "l1penaltydynamic.hpp"
41
42 #include "ROL_TypeP_TrustRegionAlgorithm.hpp"
43 #include "ROL_TypeP_ProxGradientAlgorithm.hpp"
44
45 template<class Real>
46 void computeInitialCondition(const ROL::Ptr<ROL::Vector<Real>> &u0,
47 const ROL::Ptr<ROL::Vector<Real>> &ck,
48 const ROL::Ptr<ROL::Vector<Real>> &uo,
49 const ROL::Ptr<ROL::Vector<Real>> &un,
50 const ROL::Ptr<ROL::Vector<Real>> &zk,
51 const ROL::Ptr<DynConstraint<Real>> &con,
52 const Real dt,
53 std::ostream &outStream);
54
55 int main(int argc, char *argv[]) {
56 //feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
57 using RealT = double;
58
59 /*** Initialize communicator. ***/
60 Teuchos::GlobalMPISession mpiSession(&argc, &argv);
61 ROL::Ptr<const Teuchos::Comm<int>> comm
62 = Tpetra::getDefaultComm();
63
64 // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
65 const int numProcs = (comm->getSize() > 1) ? comm->getSize() : 0;
66 const int myRank = comm->getRank();
67 ROL::Ptr<std::ostream> outStream = ROL::makeStreamPtr( std::cout, (argc > 1) && (myRank==0) );
68
69 int errorFlag = 0;
70
71 // *** Example body.
72 try {
73
74 /*** Read in XML input ***/
75 ROL::Ptr<ROL::ParameterList> parlist = ROL::getParametersFromXmlFile("input_02.xml");
76 int nt = parlist->sublist("Time Discretization").get("Number of Time Steps", 100);
77 RealT T = parlist->sublist("Time Discretization").get("End Time", 1.0);
78 RealT dt = T/static_cast<RealT>(nt);
79 bool useParametricControl = parlist->sublist("Problem").get("Use Parametric Control", true);
80 int verbosity = parlist->sublist("General").get("Output Level", 1);
81 verbosity = (myRank==0 ? verbosity : 0);
82 parlist->sublist("General").set("Output Level", verbosity);
83 bool solveOutput = parlist->sublist("Dynamic Constraint").sublist("Solve").get("Output Iteration History", true);
84 solveOutput = (myRank==0 ? solveOutput : false);
85 parlist->sublist("Dynamic Constraint").sublist("Solve").set("Output Iteration History", solveOutput);
86 solveOutput = parlist->sublist("SimOpt").sublist("Solve").get("Output Iteration History", true);
87 solveOutput = (myRank==0 ? solveOutput : false);
88 parlist->sublist("SimOpt").sublist("Solve").set("Output Iteration History", solveOutput);
89 RealT Re = parlist->sublist("Problem").get("Reynolds Number",200.0);
90
91 parlist->sublist("Reduced Dynamic Objective").set("State Domain Seed",12321*(myRank+1));
92 parlist->sublist("Reduced Dynamic Objective").set("State Range Seed", 32123*(myRank+1));
93 parlist->sublist("Reduced Dynamic Objective").set("Adjoint Domain Seed",23432*(myRank+1));
94 parlist->sublist("Reduced Dynamic Objective").set("Adjoint Range Seed", 43234*(myRank+1));
95 parlist->sublist("Reduced Dynamic Objective").set("State Sensitivity Domain Seed",34543*(myRank+1));
96 parlist->sublist("Reduced Dynamic Objective").set("State Sensitivity Range Seed", 54345*(myRank+1));
97
98 /*************************************************************************/
99 /***************** BUILD GOVERNING PDE ***********************************/
100 /*************************************************************************/
101 /*** Initialize mesh data structure. ***/
102 ROL::Ptr<MeshManager<RealT>> meshMgr
103 = ROL::makePtr<MeshReader<RealT>>(*parlist, numProcs);
104 // Initialize PDE describing Navier-Stokes equations.
105 ROL::Ptr<DynamicPDE_NavierStokes<RealT>> pde
106 = ROL::makePtr<DynamicPDE_NavierStokes<RealT>>(*parlist);
107
108 /*************************************************************************/
109 /***************** BUILD CONSTRAINT **************************************/
110 /*************************************************************************/
111 ROL::Ptr<DynConstraint<RealT>> dyn_con
112 = ROL::makePtr<DynConstraint<RealT>>(pde,meshMgr,comm,*parlist,*outStream);
113 const ROL::Ptr<Assembler<RealT>> assembler = dyn_con->getAssembler();
114 dyn_con->setSolveParameters(*parlist);
115 dyn_con->getAssembler()->printMeshData(*outStream);
116
117 /*************************************************************************/
118 /***************** BUILD VECTORS *****************************************/
119 /*************************************************************************/
120 ROL::Ptr<Tpetra::MultiVector<>> u0_ptr = assembler->createStateVector();
121 ROL::Ptr<Tpetra::MultiVector<>> uo_ptr = assembler->createStateVector();
122 ROL::Ptr<Tpetra::MultiVector<>> un_ptr = assembler->createStateVector();
123 ROL::Ptr<Tpetra::MultiVector<>> ck_ptr = assembler->createResidualVector();
124 ROL::Ptr<ROL::Vector<RealT>> u0, uo, un, ck, zk;
125 u0 = ROL::makePtr<PDE_PrimalSimVector<RealT>>(u0_ptr,pde,*assembler,*parlist);
126 uo = ROL::makePtr<PDE_PrimalSimVector<RealT>>(uo_ptr,pde,*assembler,*parlist);
127 un = ROL::makePtr<PDE_PrimalSimVector<RealT>>(un_ptr,pde,*assembler,*parlist);
128 ck = ROL::makePtr<PDE_DualSimVector<RealT>>(ck_ptr,pde,*assembler,*parlist);
129 if (!useParametricControl) {
130 ROL::Ptr<Tpetra::MultiVector<>> zk_ptr = assembler->createControlVector();
131 zk = ROL::makePtr<PDE_PrimalOptVector<RealT>>(zk_ptr,pde,*assembler,*parlist);
132 }
133 else {
134 zk = ROL::makePtr<PDE_OptVector<RealT>>(ROL::makePtr<ROL::StdVector<RealT>>(1));
135 }
136 ROL::Ptr<ROL::PartitionedVector<RealT>> z
137 = ROL::PartitionedVector<RealT>::create(*zk, nt); // nt 'clones' of zk's
138
139 // write l1 obj that takes in rol vector, loops nt entries, grabs
140 // data from nt entries, sum abs of zk clones
141
142 /*************************************************************************/
143 /***************** BUILD COST FUNCTIONAL *********************************/
144 /*************************************************************************/
145 std::vector<ROL::Ptr<QoI<RealT>>> qoi_vec(3,ROL::nullPtr), qoi_T(1,ROL::nullPtr);
146 RealT w1 = parlist->sublist("Problem").get("State Cost",1.0);
147 RealT w2 = parlist->sublist("Problem").get("State Boundary Cost",1.0);
148 RealT w3 = parlist->sublist("Problem").get("L2 Control Cost",0.0);
149 RealT wT = parlist->sublist("Problem").get("Final Time State Cost",1.0);
150
151 std::vector<RealT> wts = {w1, w2, w3}, wts_T = {wT};
152 std::string intObj = parlist->sublist("Problem").get("Integrated Objective Type", "Dissipation");
153 std::string ftObj = parlist->sublist("Problem").get("Final Time Objective Type", "Tracking");
154
155 qoi_vec[0] = ROL::makePtr<QoI_State_NavierStokes<RealT>>(intObj,
156 *parlist,
157 pde->getVelocityFE(),
158 pde->getPressureFE(),
159 pde->getFieldHelper());
160 qoi_vec[1] = ROL::makePtr<QoI_DownStreamPower_NavierStokes<RealT>>(pde->getVelocityFE(),
161 pde->getPressureFE(),
162 pde->getVelocityBdryFE(1),
163 pde->getBdryCellLocIds(1),
164 pde->getFieldHelper());
165 qoi_T[0] = ROL::makePtr<QoI_State_NavierStokes<RealT>>(ftObj,
166 *parlist,
167 pde->getVelocityFE(),
168 pde->getPressureFE(),
169 pde->getFieldHelper());
170 if (useParametricControl) {
171 qoi_vec[2] = ROL::makePtr<QoI_RotationControl_NavierStokes<RealT>>();
172 }
173 else {
174 qoi_vec[2] = ROL::makePtr<QoI_L2Penalty_NavierStokes<RealT>>(pde->getVelocityFE(),
175 pde->getPressureFE(),
176 pde->getVelocityBdryFE(4),
177 pde->getBdryCellLocIds(4),
178 pde->getFieldHelper());
179 }
180 ROL::Ptr<ROL::Objective_SimOpt<RealT>> obj_k // pde integrated obj
181 = ROL::makePtr<PDE_Objective<RealT>>(qoi_vec,wts,assembler);
182 ROL::Ptr<ROL::Objective_SimOpt<RealT>> obj_T // final time obj
183 = ROL::makePtr<PDE_Objective<RealT>>(qoi_T,wts_T,assembler);
184 ROL::Ptr<LTI_Objective<RealT>> dyn_obj // combination
185 = ROL::makePtr<LTI_Objective<RealT>>(*parlist,obj_k,obj_T);// integrates over interval, added over timepoints somewhere
186
187 /*************************************************************************/
188 /***************** BUILD REDUCED COST FUNCTIONAL *************************/
189 /*************************************************************************/
190 std::vector<ROL::TimeStamp<RealT>> timeStamp(nt);
191 for( int k=0; k<nt; ++k ) {
192 timeStamp.at(k).t.resize(2);
193 timeStamp.at(k).t.at(0) = k*dt;
194 timeStamp.at(k).t.at(1) = (k+1)*dt;
195 }
196 std::clock_t timer_init = std::clock();
197 std::stringstream file;
198 file << "initial_condition_Re" << static_cast<int>(Re) << ".txt";
199 std::ifstream infile(file.str());
200 if (infile.good()) {
201 dyn_con->inputTpetraVector(u0_ptr, file.str());
202 }
203 else {
204 PotentialFlow<RealT> pf(pde->getVelocityFE(),
205 pde->getPressureFE(),
206 pde->getCellNodes(),
207 assembler->getDofManager()->getCellDofs(),
208 assembler->getCellIds(),
209 pde->getFieldHelper(),
210 *parlist);
211 pf.build(u0_ptr);
212 computeInitialCondition<RealT>(u0,ck,uo,un,zk,dyn_con,dt,*outStream);
213 dyn_con->outputTpetraVector(u0_ptr, file.str());
214 }
215 *outStream << "Initial condition time: "
216 << static_cast<RealT>(std::clock()-timer_init)/static_cast<RealT>(CLOCKS_PER_SEC)
217 << " seconds." << std::endl << std::endl;
218 // Construct reduce dynamic objective function
219 ROL::ParameterList &rpl = parlist->sublist("Reduced Dynamic Objective");
220 ROL::Ptr<ROL::ReducedDynamicObjective<RealT>> obj
221 = ROL::makePtr<ROL::ReducedDynamicObjective<RealT>>(dyn_obj, dyn_con, u0, zk, ck, timeStamp, rpl, outStream);// summing over
222 // create l1 dynamic objective for nobj, pass to TRnonsmooth
223 ROL::Ptr<ROL::PartitionedVector<RealT>> zlo = ROL::PartitionedVector<RealT>::create(*zk, nt);
224 ROL::Ptr<ROL::PartitionedVector<RealT>> zhi = ROL::PartitionedVector<RealT>::create(*zk, nt);
225 zlo->setScalar(parlist->sublist("Problem").get("Lower Control Bound", -1.e0));
226 zhi->setScalar(parlist->sublist("Problem").get("Upper Control Bound", 1.e0));
227 ROL::Ptr<L1_Dyn_Objective<RealT>> nobj
228 = ROL::makePtr<L1_Dyn_Objective<RealT>>(*parlist,timeStamp, zlo, zhi);
229
230 //Algo pointer
231 ROL::Ptr<ROL::TypeP::TrustRegionAlgorithm<RealT>> algo;
232 //ROL::Ptr<ROL::TypeP::ProxGradientAlgorithm<RealT>> algo;
233 /*************************************************************************/
234 /***************** RUN VECTOR AND DERIVATIVE CHECKS **********************/
235 /*************************************************************************/
236 bool checkDeriv = parlist->sublist("Problem").get("Check Derivatives",false);
237 if ( checkDeriv ) {
238 ROL::Ptr<ROL::PartitionedVector<RealT>> dz = ROL::PartitionedVector<RealT>::create(*zk, nt);
239 ROL::Ptr<ROL::PartitionedVector<RealT>> hz = ROL::PartitionedVector<RealT>::create(*zk, nt);
240 zk->randomize(); z->randomize(); dz->randomize(); hz->randomize();
241 uo->randomize(); un->randomize();
242 ROL::ValidateFunction<RealT> validate(1,13,20,11,true,*outStream);
243 ROL::DynamicObjectiveCheck<RealT>::check(*dyn_obj,validate,*uo,*un,*zk);
244 ROL::DynamicConstraintCheck<RealT>::check(*dyn_con,validate,*uo,*un,*zk);
245 obj->checkGradient(*z,*dz,true,*outStream);
246 obj->checkHessVec(*z,*dz,true,*outStream);
247 obj->checkHessSym(*z,*dz,*hz,true,*outStream);
248 }
249
250 /*************************************************************************/
251 /***************** RUN VECTOR AND DERIVATIVE CHECKS **********************/
252 /*************************************************************************/
253 bool printU0 = parlist->sublist("Problem").get("Print Uncontrolled State", false);
254 if (printU0) {
255 std::clock_t timer_print0 = std::clock();
256 zk->zero(); uo->set(*u0); un->zero();
257 for (int k = 1; k < nt; ++k) {
258 // Print previous state to file
259 std::stringstream u0file;
260 u0file << "uncontrolled_state." << k-1 << ".txt";
261 dyn_con->outputTpetraVector(uo_ptr, u0file.str());
262 // Advance time stepper
263 dyn_con->solve(*ck, *uo, *un, *zk, timeStamp[k]);
264 uo->set(*un);
265 }
266 // Print previous state to file
267 std::stringstream u0file;
268 u0file << "uncontrolled_state." << nt-1 << ".txt";
269 dyn_con->outputTpetraVector(uo_ptr, u0file.str());
270 *outStream << "Output uncontrolled state time: "
271 << static_cast<RealT>(std::clock()-timer_print0)/static_cast<RealT>(CLOCKS_PER_SEC)
272 << " seconds." << std::endl << std::endl;
273 }
274
275 /*************************************************************************/
276 /***************** SOLVE OPTIMIZATION PROBLEM ****************************/
277 /*************************************************************************/
278 z->zero();
279 if (useParametricControl) {
280 bool readFromFile = parlist->sublist("Initial Guess").get("Read From File",false);
281 if (!readFromFile) {
282 // Linearly interpolate between optimal values for angular velocity
283 // amplitude and Strouhal number obtained for Re=200, 1000 in
284 // JW He, R Glowinski, R Metcalfe, A Nordlander, J Periaux
285 // Active Control and Drag Optimization for Flow Past a
286 // Circular Cylinder
287 // Journal of Computation Physics, 163, pg. 83-117, 2000.
288 RealT Re = parlist->sublist("Problem").get("Reynolds Number",200.0);
289 RealT amp0 = 6.0 - (Re - 200.0)/1600.0;
290 RealT Se0 = 0.74 - (Re - 200.0) * (0.115/800.0);
291 RealT amp = parlist->sublist("Problem").sublist("Initial Guess").get("Amplitude", amp0);
292 RealT Se = parlist->sublist("Problem").sublist("Initial Guess").get("Strouhal Number", Se0);
293 RealT ph = parlist->sublist("Problem").sublist("Initial Guess").get("Phase Shift", 0.0);
294 for( int k=0; k<nt; ++k ) {
295 ROL::Ptr<std::vector<RealT>> zn
296 = ROL::dynamicPtrCast<PDE_OptVector<RealT>>(z->get(k))->getParameter()->getVector();
297 (*zn)[0] = -amp * std::sin(2.0 * M_PI * Se * timeStamp[k].t[0] + ph);
298 }
299 }
300 else {
301 for (int k = 1; k < nt; ++k) {
302 std::stringstream zname;
303 zname << "initial_control." << k-1 << ".txt";
304 std::fstream zfile;
305 zfile.open(zname.str(),std::ios::in);
306 if (!zfile.is_open()) std::cout << "CANNOT OPEN " << zname.str() << std::endl;
307 zfile >> (*(ROL::dynamicPtrCast<PDE_OptVector<RealT>>(z->get(k-1))->getParameter()->getVector()))[0];
308 zfile.close();
309 }
310 }
311 }
312 //parlist->sublist("Step").sublist("Trust Region").sublist("TRN").sublist("Solver").set("Subproblem Solver", "NCG");
313 algo = ROL::makePtr<ROL::TypeP::TrustRegionAlgorithm<RealT>>(*parlist);
314 //algo = ROL::makePtr<ROL::TypeP::ProxGradientAlgorithm<RealT>>(*parlist);
315 //ROL::OptimizationProblem<RealT> problem(obj,z);// need to change this
316 //ROL::OptimizationSolver<RealT> solver(problem,*parlist);// need to change this
317 std::clock_t timer = std::clock();
318 //solver.solve(*outStream);
319 algo->run(*z, *obj, *nobj, *outStream);
320 *outStream << "Optimization time: "
321 << static_cast<RealT>(std::clock()-timer)/static_cast<RealT>(CLOCKS_PER_SEC)
322 << " seconds." << std::endl << std::endl;
323
324 /*************************************************************************/
325 /***************** OUTPUT RESULTS ****************************************/
326 /*************************************************************************/
327 std::clock_t timer_print = std::clock();
328 // Output state and control to file
329 uo->set(*u0); un->zero();
330 for (int k = 1; k < nt; ++k) {
331 // Print previous state to file
332 std::stringstream ufile;
333 ufile << "state." << k-1 << ".txt";
334 dyn_con->outputTpetraVector(uo_ptr, ufile.str());
335 // Print current control
336 if (!useParametricControl) {
337 std::stringstream zfile;
338 zfile << "control." << k-1 << ".txt";
339 dyn_con->outputTpetraVector(ROL::dynamicPtrCast<PDE_PrimalOptVector<RealT>>(z->get(k-1))->getVector(),zfile.str());
340 }
341 else {
342 if (myRank == 0) {
343 std::stringstream zname;
344 zname << "control." << k-1 << ".txt";
345 std::ofstream zfile;
346 zfile.open(zname.str());
347 zfile << std::scientific << std::setprecision(15);
348 ROL::Ptr<std::vector<RealT>> zn
349 = ROL::dynamicPtrCast<PDE_OptVector<RealT>>(z->get(k-1))->getParameter()->getVector();
350 zfile << std::right << std::setw(25) << (*zn)[0];
351 zfile.close();
352 }
353 }
354 // Advance time stepper
355 dyn_con->solve(*ck, *uo, *un, *z->get(k), timeStamp[k]);
356 uo->set(*un);
357 }
358 // Print previous state to file
359 std::stringstream ufile;
360 ufile << "state." << nt-1 << ".txt";
361 dyn_con->outputTpetraVector(uo_ptr, ufile.str());
362 // Print current control
363 if (!useParametricControl) {
364 std::stringstream zfile;
365 zfile << "control." << nt-1 << ".txt";
366 dyn_con->outputTpetraVector(ROL::dynamicPtrCast<PDE_PrimalOptVector<RealT>>(z->get(nt-1))->getVector(),zfile.str());
367 }
368 else {
369 if (myRank == 0) {
370 std::stringstream zname;
371 zname << "control." << nt-1 << ".txt";
372 std::ofstream zfile;
373 zfile.open(zname.str());
374 zfile << std::scientific << std::setprecision(15);
375 ROL::Ptr<std::vector<RealT>> zn
376 = ROL::dynamicPtrCast<PDE_OptVector<RealT>>(z->get(nt-1))->getParameter()->getVector();
377 zfile << std::right << std::setw(25) << (*zn)[0];
378 zfile.close();
379 }
380 }
381 *outStream << "Output time: "
382 << static_cast<RealT>(std::clock()-timer_print)/static_cast<RealT>(CLOCKS_PER_SEC)
383 << " seconds." << std::endl << std::endl;
384 }
385 catch (std::logic_error& err) {
386 *outStream << err.what() << "\n";
387 errorFlag = -1000;
388 }; // end try
389
390 if (errorFlag != 0)
391 std::cout << "End Result: TEST FAILED\n";
392 else
393 std::cout << "End Result: TEST PASSED\n";
394
395 return 0;
396 }
397
398 template<class Real>
399 void computeInitialCondition(const ROL::Ptr<ROL::Vector<Real>> &u0,
400 const ROL::Ptr<ROL::Vector<Real>> &ck,
401 const ROL::Ptr<ROL::Vector<Real>> &uo,
402 const ROL::Ptr<ROL::Vector<Real>> &un,
403 const ROL::Ptr<ROL::Vector<Real>> &zk,
404 const ROL::Ptr<DynConstraint<Real>> &con,
405 const Real dt,
406 std::ostream &outStream) {
407 Real T = 80.0;
408 int nt = static_cast<int>(T/dt);
409 std::vector<ROL::TimeStamp<Real>> ts(nt);
410 for( int k=0; k<nt; ++k ) {
411 ts.at(k).t.resize(2);
412 ts.at(k).t.at(0) = k*dt;
413 ts.at(k).t.at(1) = (k+1)*dt;
414 }
415 // Solve Navier-Stokes equation to determine initial condition
416 zk->zero(); uo->set(*u0); un->zero();
417 Real unorm = uo->norm();
418 outStream << std::scientific << std::setprecision(6);
419 outStream << std::right << std::setw(8) << "ts"
420 << std::right << std::setw(16) << "||u(ts)||"
421 << std::right << std::setw(16) << "avg time (sec)"
422 << std::endl;
423 outStream << std::right << std::setw(8) << 0
424 << std::right << std::setw(16) << unorm
425 << std::right << std::setw(16) << "---"
426 << std::endl;
427 std::vector<Real> time(10);
428 std::clock_t timer_step;
429 Real time_avg(0);
430 for (int k = 1; k < nt; ++k) {
431 // Advance time stepper
432 timer_step = std::clock();
433 con->solve(*ck, *uo, *un, *zk, ts[k]);
434 time[k%10] = static_cast<Real>(std::clock()-timer_step)/static_cast<Real>(CLOCKS_PER_SEC);
435 uo->set(*un);
436 if ( k%10==0 ) {
437 unorm = uo->norm();
438 time_avg = 0.0;
439 for (int i = 0; i < 10; ++i) {
440 time_avg += time[i];
441 }
442 time_avg *= 0.1;
443 outStream << std::right << std::setw(8) << k
444 << std::right << std::setw(16) << unorm
445 << std::right << std::setw(16) << time_avg
446 << std::endl;
447 }
448 }
449 u0->set(*uo);
450 }
451
452