Debian Codegraph @

packages/rol/example/PDE-OPT/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.cpp
11 \brief Shows how to solve the stochastic Stefan-Boltzmann problem.
12 */
13
14 #include "Teuchos_Comm.hpp"
15 #include "ROL_Stream.hpp"
16 #include "Teuchos_GlobalMPISession.hpp"
17 #include "Teuchos_XMLParameterListHelpers.hpp"
18
19 #include "Tpetra_Core.hpp"
20 #include "Tpetra_Version.hpp"
21
22 #include <iostream>
23 #include <algorithm>
24 //#include <fenv.h>
25
26 #include "ROL_Bounds.hpp"
27 #include "ROL_Reduced_Objective_SimOpt.hpp"
28 #include "ROL_MonteCarloGenerator.hpp"
29 #include "ROL_StochasticProblem.hpp"
30 #include "ROL_Solver.hpp"
31 #include "ROL_TpetraTeuchosBatchManager.hpp"
32
33 #include "../TOOLS/meshmanager.hpp"
34 #include "../TOOLS/pdeconstraint.hpp"
35 #include "../TOOLS/pdeobjective.hpp"
36 #include "../TOOLS/pdevector.hpp"
37 #include "../TOOLS/batchmanager.hpp"
38 #include "pde_navier-stokes.hpp"
39 #include "obj_navier-stokes.hpp"
40
41 typedef double RealT;
42
43 template<class Real>
44 Real random(const Teuchos::Comm<int> &comm,
45 const Real a = -1, const Real b = 1) {
46 Real val(0), u(0);
47 if ( Teuchos::rank<int>(comm)==0 ) {
48 u = static_cast<Real>(rand())/static_cast<Real>(RAND_MAX);
49 val = (b-a)*u + a;
50 }
51 Teuchos::broadcast<int,Real>(comm,0,1,&val);
52 return val;
53 }
54
55 int main(int argc, char *argv[]) {
56 //feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
57
58 // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
59 int iprint = argc - 1;
60 ROL::Ptr<std::ostream> outStream;
61 ROL::nullstream bhs; // outputs nothing
62
63 /*** Initialize communicator. ***/
64 Teuchos::GlobalMPISession mpiSession (&argc, &argv, &bhs);
65 ROL::Ptr<const Teuchos::Comm<int> > comm
66 = Tpetra::getDefaultComm();
67 ROL::Ptr<const Teuchos::Comm<int> > serial_comm
68 = ROL::makePtr<Teuchos::SerialComm<int>>();
69 const int myRank = comm->getRank();
70 if ((iprint > 0) && (myRank == 0)) {
71 outStream = ROL::makePtrFromRef(std::cout);
72 }
73 else {
74 outStream = ROL::makePtrFromRef(bhs);
75 }
76 int errorFlag = 0;
77
78 // *** Example body.
79 try {
80
81 /*** Read in XML input ***/
82 std::string filename = "input.xml";
83 Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
84 Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
85
86 // Problem dimensions
87 const int stochDim = 2;
88 const RealT one(1);
89
90 /*************************************************************************/
91 /***************** BUILD GOVERNING PDE ***********************************/
92 /*************************************************************************/
93 /*** Initialize main data structure. ***/
94 ROL::Ptr<MeshManager<RealT>>
95 meshMgr = ROL::makePtr<MeshManager_BackwardFacingStepChannel<RealT>>(*parlist);
96 // Initialize PDE describing advection-diffusion equation
97 ROL::Ptr<PDE_NavierStokes<RealT>>
98 pde = ROL::makePtr<PDE_NavierStokes<RealT>>(*parlist);
99 ROL::Ptr<ROL::Constraint_SimOpt<RealT>>
100 con = ROL::makePtr<PDE_Constraint<RealT>>(pde,meshMgr,serial_comm,*parlist,*outStream);
101 // Cast the constraint and get the assembler.
102 ROL::Ptr<PDE_Constraint<RealT>>
103 pdecon = ROL::dynamicPtrCast<PDE_Constraint<RealT> >(con);
104 ROL::Ptr<Assembler<RealT> > assembler = pdecon->getAssembler();
105 con->setSolveParameters(*parlist);
106
107 /*************************************************************************/
108 /***************** BUILD VECTORS *****************************************/
109 /*************************************************************************/
110 ROL::Ptr<Tpetra::MultiVector<>> u_ptr = assembler->createStateVector(); u_ptr->randomize();
111 ROL::Ptr<Tpetra::MultiVector<>> du_ptr = assembler->createStateVector(); du_ptr->randomize();
112 ROL::Ptr<Tpetra::MultiVector<>> p_ptr = assembler->createStateVector(); p_ptr->randomize();
113 ROL::Ptr<Tpetra::MultiVector<>> r_ptr = assembler->createResidualVector(); r_ptr->randomize();
114 ROL::Ptr<Tpetra::MultiVector<>> z_ptr = assembler->createControlVector(); z_ptr->randomize();
115 ROL::Ptr<ROL::Vector<RealT>> up, dup, pp, rp;
116 up = ROL::makePtr<PDE_PrimalSimVector<RealT>>(u_ptr,pde,assembler,*parlist);
117 dup = ROL::makePtr<PDE_PrimalSimVector<RealT>>(u_ptr,pde,assembler,*parlist);
118 pp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(p_ptr,pde,assembler,*parlist);
119 rp = ROL::makePtr<PDE_DualSimVector<RealT>>(r_ptr,pde,assembler,*parlist);
120 ROL::Ptr<ROL::TpetraMultiVector<RealT>> zpde
121 = ROL::makePtr<PDE_PrimalOptVector<RealT>>(z_ptr,pde,assembler,*parlist);
122 ROL::Ptr<ROL::Vector<RealT>> zp = ROL::makePtr<PDE_OptVector<RealT>>(zpde);
123 // Create ROL SimOpt vectors
124 ROL::Vector_SimOpt<RealT> x(up,zp);
125
126 /*************************************************************************/
127 /***************** BUILD COST FUNCTIONAL *********************************/
128 /*************************************************************************/
129 std::vector<ROL::Ptr<QoI<RealT>>> qoi_vec(2,ROL::nullPtr);
130 qoi_vec[0] = ROL::makePtr<QoI_State_NavierStokes<RealT>>(*parlist,
131 pde->getVelocityFE(),
132 pde->getPressureFE(),
133 pde->getFieldHelper());
134 qoi_vec[1] = ROL::makePtr<QoI_L2Penalty_NavierStokes<RealT>>(pde->getVelocityFE(),
135 pde->getPressureFE(),
136 pde->getVelocityBdryFE(),
137 pde->getBdryCellLocIds(),
138 pde->getFieldHelper());
139 ROL::Ptr<StdObjective_NavierStokes<RealT>>
140 std_obj = ROL::makePtr<StdObjective_NavierStokes<RealT>>(*parlist);
141 ROL::Ptr<ROL::Objective_SimOpt<RealT>>
142 obj = ROL::makePtr<PDE_Objective<RealT>>(qoi_vec,std_obj,assembler);
143 ROL::Ptr<ROL::Reduced_Objective_SimOpt<RealT>>
144 objReduced = ROL::makePtr<ROL::Reduced_Objective_SimOpt<RealT>>(obj, con, up, zp, pp, true, false);
145
146 /*************************************************************************/
147 /***************** BUILD BOUND CONSTRAINT ********************************/
148 /*************************************************************************/
149 ROL::Ptr<Tpetra::MultiVector<>> zlo_ptr = assembler->createControlVector();
150 ROL::Ptr<Tpetra::MultiVector<>> zhi_ptr = assembler->createControlVector();
151 zlo_ptr->putScalar(static_cast<RealT>(0));
152 zhi_ptr->putScalar(ROL::ROL_INF<RealT>());
153 ROL::Ptr<ROL::TpetraMultiVector<RealT>> zlopde, zhipde;
154 zlopde = ROL::makePtr<PDE_PrimalOptVector<RealT>>(zlo_ptr,pde,assembler,*parlist);
155 zhipde = ROL::makePtr<PDE_PrimalOptVector<RealT>>(zhi_ptr,pde,assembler,*parlist);
156 ROL::Ptr<ROL::Vector<RealT>> zlop = ROL::makePtr<PDE_OptVector<RealT>>(zlopde);
157 ROL::Ptr<ROL::Vector<RealT>> zhip = ROL::makePtr<PDE_OptVector<RealT>>(zhipde);
158 ROL::Ptr<ROL::BoundConstraint<RealT>>
159 bnd = ROL::makePtr<ROL::Bounds<RealT>>(zlop,zhip);
160 bool useBounds = parlist->sublist("Problem").get("Use bounds", false);
161 if (!useBounds) bnd->deactivate();
162
163 /*************************************************************************/
164 /***************** BUILD SAMPLER *****************************************/
165 /*************************************************************************/
166 int nsamp = parlist->sublist("Problem").get("Number of samples",100);
167 std::vector<RealT> tmp = {-one,one};
168 std::vector<std::vector<RealT>> bounds(stochDim,tmp);
169 ROL::Ptr<ROL::BatchManager<RealT>>
170 bman = ROL::makePtr<PDE_OptVector_BatchManager<RealT>>(comm);
171 ROL::Ptr<ROL::SampleGenerator<RealT>>
172 sampler = ROL::makePtr<ROL::MonteCarloGenerator<RealT>>(nsamp,bounds,bman);
173
174 /*************************************************************************/
175 /***************** BUILD STOCHASTIC PROBLEM ******************************/
176 /*************************************************************************/
177 ROL::Ptr<ROL::StochasticProblem<RealT>>
178 opt = ROL::makePtr<ROL::StochasticProblem<RealT>>(objReduced,zp);
179 opt->addBoundConstraint(bnd);
180 parlist->sublist("SOL").set("Initial Statistic",one);
181 opt->makeObjectiveStochastic(*parlist,sampler);
182 opt->finalize(false,true,*outStream);
183
184 /*************************************************************************/
185 /***************** RUN VECTOR AND DERIVATIVE CHECKS **********************/
186 /*************************************************************************/
187 bool checkDeriv = parlist->sublist("Problem").get("Check derivatives",false);
188 if ( checkDeriv ) {
189 ROL::Ptr<ROL::Vector<RealT>> dzp = zp->clone(); dzp->randomize(-one,one);
190 ROL::Ptr<ROL::Vector<RealT>> yzp = zp->clone(); yzp->randomize(-one,one);
191 ROL::Vector_SimOpt<RealT> d(dup,dzp);
192 up->checkVector(*pp,*dup,true,*outStream);
193 zp->checkVector(*yzp,*dzp,true,*outStream);
194 obj->checkGradient(x,d,true,*outStream);
195 obj->checkHessVec(x,d,true,*outStream);
196 con->checkApplyJacobian(x,d,*up,true,*outStream);
197 con->checkApplyAdjointHessian(x,*dup,d,x,true,*outStream);
198 con->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream);
199 con->checkInverseJacobian_1(*up,*up,*up,*zp,true,*outStream);
200 con->checkInverseAdjointJacobian_1(*up,*up,*up,*zp,true,*outStream);
201 objReduced->checkGradient(*zp,*dzp,true,*outStream);
202 objReduced->checkHessVec(*zp,*dzp,true,*outStream);
203 opt->check(true,*outStream);
204 }
205
206 /*************************************************************************/
207 /***************** SOLVE OPTIMIZATION PROBLEM ****************************/
208 /*************************************************************************/
209 parlist->sublist("Step").set("Type","Trust Region");
210 ROL::Solver<RealT> solver(opt,*parlist);
211 up->zero(); zp->zero();
212 std::clock_t timer = std::clock();
213 solver.solve(*outStream);
214 *outStream << "Optimization time: "
215 << static_cast<RealT>(std::clock()-timer)/static_cast<RealT>(CLOCKS_PER_SEC)
216 << " seconds." << std::endl << std::endl;
217
218 /*************************************************************************/
219 /***************** OUTPUT RESULTS ****************************************/
220 /*************************************************************************/
221 std::clock_t timer_print = std::clock();
222 assembler->printMeshData(*outStream);
223 // Output control to file
224 pdecon->outputTpetraVector(z_ptr,"control.txt");
225 // Output expected state and samples to file
226 *outStream << std::endl << "Print Expected Value of State" << std::endl;
227 up->zero(); pp->zero(); dup->zero();
228 RealT tol(1.e-8);
229 ROL::Ptr<ROL::BatchManager<RealT> > bman_Eu
230 = ROL::makePtr<ROL::TpetraTeuchosBatchManager<RealT>>(comm);
231 std::vector<RealT> sample(stochDim);
232 std::stringstream name_samp;
233 name_samp << "samples_" << bman->batchID() << ".txt";
234 std::ofstream file_samp;
235 file_samp.open(name_samp.str());
236 file_samp << std::scientific << std::setprecision(15);
237 for (int i = 0; i < sampler->numMySamples(); ++i) {
238 *outStream << "Sample i = " << i << std::endl;
239 sample = sampler->getMyPoint(i);
240 con->setParameter(sample);
241 con->solve(*rp,*dup,*zp,tol);
242 up->axpy(sampler->getMyWeight(i),*dup);
243 for (int j = 0; j < stochDim; ++j) {
244 file_samp << std::setw(25) << std::left << sample[j];
245 }
246 file_samp << std::endl;
247 }
248 file_samp.close();
249 bman_Eu->sumAll(*up,*pp);
250 pdecon->outputTpetraVector(p_ptr,"mean_state.txt");
251 // Output extreme cases
252 std::vector<RealT> param(stochDim,0);
253 param[0] = -one; param[1] = -one;
254 con->setParameter(param);
255 con->solve(*rp,*dup,*zp,tol);
256 pdecon->outputTpetraVector(du_ptr,"state_m1_m1.txt");
257 param[0] = one; param[1] = -one;
258 con->setParameter(param);
259 con->solve(*rp,*dup,*zp,tol);
260 pdecon->outputTpetraVector(du_ptr,"state_p1_m1.txt");
261 param[0] = -one; param[1] = one;
262 con->setParameter(param);
263 con->solve(*rp,*dup,*zp,tol);
264 pdecon->outputTpetraVector(du_ptr,"state_m1_p1.txt");
265 param[0] = one; param[1] = one;
266 con->setParameter(param);
267 con->solve(*rp,*dup,*zp,tol);
268 pdecon->outputTpetraVector(du_ptr,"state_p1_p1.txt");
269 // Build objective function distribution
270 *outStream << std::endl << "Print Objective CDF" << std::endl;
271 RealT val1(0), val2(0);
272 int nsamp_dist = parlist->sublist("Problem").get("Number of output samples",100);
273 ROL::Ptr<ROL::Objective_SimOpt<RealT> > stateCost
274 = ROL::makePtr<IntegralObjective<RealT>>(qoi_vec[0],assembler);
275 ROL::Ptr<ROL::Reduced_Objective_SimOpt<RealT> > redStateCost
276 = ROL::makePtr<ROL::Reduced_Objective_SimOpt<RealT>>(stateCost, con, up, zp, pp, true, false);
277 ROL::Ptr<ROL::Objective_SimOpt<RealT> > ctrlCost
278 = ROL::makePtr<IntegralObjective<RealT>>(qoi_vec[1],assembler);
279 ROL::Ptr<ROL::Reduced_Objective_SimOpt<RealT> > redCtrlCost
280 = ROL::makePtr<ROL::Reduced_Objective_SimOpt<RealT>>(ctrlCost, con, up, zp, pp, true, false);
281 ROL::Ptr<ROL::SampleGenerator<RealT> > sampler_dist
282 = ROL::makePtr<ROL::MonteCarloGenerator<RealT>>(nsamp_dist,bounds,bman);
283 std::stringstream name;
284 name << "obj_samples_" << bman->batchID() << ".txt";
285 std::ofstream file;
286 file.open(name.str());
287 file << std::scientific << std::setprecision(15);
288 for (int i = 0; i < sampler_dist->numMySamples(); ++i) {
289 sample = sampler_dist->getMyPoint(i);
290 redStateCost->setParameter(sample);
291 val1 = redStateCost->value(*zp,tol);
292 redCtrlCost->setParameter(sample);
293 val2 = redCtrlCost->value(*zp,tol);
294 for (int j = 0; j < stochDim; ++j) {
295 file << std::setw(25) << std::left << sample[j];
296 }
297 file << std::setw(25) << std::left << val1;
298 file << std::setw(25) << std::left << val2 << std::endl;
299 }
300 file.close();
301 *outStream << "Output time: "
302 << static_cast<RealT>(std::clock()-timer_print)/static_cast<RealT>(CLOCKS_PER_SEC)
303 << " seconds." << std::endl << std::endl;
304
305 Teuchos::Array<RealT> res(1,0);
306 con->solve(*rp,*up,*zp,tol);
307 r_ptr->norm2(res.view(0,1));
308
309 /*************************************************************************/
310 /***************** CHECK RESIDUAL NORM ***********************************/
311 /*************************************************************************/
312 *outStream << "Residual Norm: " << res[0] << std::endl << std::endl;
313 errorFlag += (res[0] > 1.e-6 ? 1 : 0);
314 }
315 catch (std::logic_error& err) {
316 *outStream << err.what() << "\n";
317 errorFlag = -1000;
318 }; // end try
319
320 if (errorFlag != 0)
321 std::cout << "End Result: TEST FAILED\n";
322 else
323 std::cout << "End Result: TEST PASSED\n";
324
325 return 0;
326 }