Debian Codegraph @

packages/rol/example/PDE-OPT/thermal-fluids/example_04.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 Navier-Stokes control 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_TpetraMultiVector.hpp"
27 #include "ROL_Reduced_Objective_SimOpt.hpp"
28 #include "ROL_MonteCarloGenerator.hpp"
29 #include "ROL_OptimizationSolver.hpp"
30 #include "ROL_TpetraTeuchosBatchManager.hpp"
31
32 #include "../TOOLS/pdeconstraint.hpp"
33 #include "../TOOLS/pdeobjective.hpp"
34 #include "../TOOLS/pdevector.hpp"
35 #include "../TOOLS/batchmanager.hpp"
36 #include "pde_thermal-fluids_ex03.hpp"
37 #include "obj_thermal-fluids_ex03.hpp"
38 #include "mesh_thermal-fluids.hpp"
39
40 typedef double RealT;
41
42 template<class Real>
43 void print(ROL::Objective<Real> &obj,
44 const ROL::Vector<Real> &z,
45 ROL::SampleGenerator<Real> &sampler,
46 const int ngsamp,
47 const ROL::Ptr<const Teuchos::Comm<int> > &comm,
48 const std::string &filename) {
49 Real tol(1e-8);
50 // Build objective function distribution
51 int nsamp = sampler.numMySamples();
52 std::vector<Real> myvalues(nsamp), myzerovec(nsamp, 0);
53 std::vector<double> gvalues(ngsamp), gzerovec(ngsamp, 0);
54 std::vector<Real> sample = sampler.getMyPoint(0);
55 int sdim = sample.size();
56 std::vector<std::vector<Real> > mysamples(sdim, myzerovec);
57 std::vector<std::vector<double> > gsamples(sdim, gzerovec);
58 for (int i = 0; i < nsamp; ++i) {
59 sample = sampler.getMyPoint(i);
60 obj.setParameter(sample);
61 myvalues[i] = static_cast<double>(obj.value(z,tol));
62 for (int j = 0; j < sdim; ++j) {
63 mysamples[j][i] = static_cast<double>(sample[j]);
64 }
65 }
66
67 // Send data to root processor
68 #ifdef HAVE_MPI
69 ROL::Ptr<const Teuchos::MpiComm<int> > mpicomm
70 = ROL::dynamicPtrCast<const Teuchos::MpiComm<int> >(comm);
71 int nproc = Teuchos::size<int>(*mpicomm);
72 std::vector<int> sampleCounts(nproc, 0), sampleDispls(nproc, 0);
73 MPI_Gather(&nsamp,1,MPI_INT,&sampleCounts[0],1,MPI_INT,0,*(mpicomm->getRawMpiComm())());
74 for (int i = 1; i < nproc; ++i) {
75 sampleDispls[i] = sampleDispls[i-1] + sampleCounts[i-1];
76 }
77 MPI_Gatherv(&myvalues[0],nsamp,MPI_DOUBLE,&gvalues[0],&sampleCounts[0],&sampleDispls[0],MPI_DOUBLE,0,*(mpicomm->getRawMpiComm())());
78 for (int j = 0; j < sdim; ++j) {
79 MPI_Gatherv(&mysamples[j][0],nsamp,MPI_DOUBLE,&gsamples[j][0],&sampleCounts[0],&sampleDispls[0],MPI_DOUBLE,0,*(mpicomm->getRawMpiComm())());
80 }
81 #else
82 gvalues.assign(myvalues.begin(),myvalues.end());
83 for (int j = 0; j < sdim; ++j) {
84 gsamples[j].assign(mysamples[j].begin(),mysamples[j].end());
85 }
86 #endif
87
88 // Print
89 int rank = Teuchos::rank<int>(*comm);
90 if ( rank==0 ) {
91 std::ofstream file;
92 file.open(filename);
93 file << std::scientific << std::setprecision(15);
94 for (int i = 0; i < ngsamp; ++i) {
95 for (int j = 0; j < sdim; ++j) {
96 file << std::setw(25) << std::left << gsamples[j][i];
97 }
98 file << std::setw(25) << std::left << gvalues[i] << std::endl;
99 }
100 file.close();
101 }
102 }
103
104 int main(int argc, char *argv[]) {
105 //feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
106
107 // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
108 int iprint = argc - 1;
109 ROL::Ptr<std::ostream> outStream;
110 ROL::nullstream bhs; // outputs nothing
111
112 /*** Initialize communicator. ***/
113 Teuchos::GlobalMPISession mpiSession (&argc, &argv, &bhs);
114 ROL::Ptr<const Teuchos::Comm<int> > comm
115 = Tpetra::getDefaultComm();
116 ROL::Ptr<const Teuchos::Comm<int> > serial_comm
117 = ROL::makePtr<Teuchos::SerialComm<int>>();
118 const int myRank = comm->getRank();
119 if ((iprint > 0) && (myRank == 0)) {
120 outStream = ROL::makePtrFromRef(std::cout);
121 }
122 else {
123 outStream = ROL::makePtrFromRef(bhs);
124 }
125 int errorFlag = 0;
126
127 // *** Example body.
128 try {
129
130 /*** Read in XML input ***/
131 std::string filename = "input_ex04.xml";
132 Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
133 Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
134 parlist->sublist("SimOpt").sublist("Solve").set("Output Iteration History",myRank==0);
135
136 /*** Initialize main data structure. ***/
137 ROL::Ptr<MeshManager<RealT> > meshMgr
138 = ROL::makePtr<MeshManager_ThermalFluids<RealT>>(*parlist);
139 // Initialize PDE describing Navier-Stokes equations.
140 ROL::Ptr<PDE_ThermalFluids_ex03<RealT> > pde
141 = ROL::makePtr<PDE_ThermalFluids_ex03<RealT>>(*parlist);
142 ROL::Ptr<ROL::Constraint_SimOpt<RealT> > con
143 = ROL::makePtr<PDE_Constraint<RealT>>(pde,meshMgr,serial_comm,*parlist,*outStream);
144 // Cast the constraint and get the assembler.
145 ROL::Ptr<PDE_Constraint<RealT> > pdecon
146 = ROL::dynamicPtrCast<PDE_Constraint<RealT> >(con);
147 ROL::Ptr<Assembler<RealT> > assembler = pdecon->getAssembler();
148 con->setSolveParameters(*parlist);
149 pdecon->outputTpetraData();
150
151 // Create state vector and set to zeroes
152 ROL::Ptr<Tpetra::MultiVector<> > u_ptr, p_ptr, du_ptr, dy_ptr, yu_ptr, yp_ptr, r_ptr, z_ptr, dz_ptr;
153 u_ptr = assembler->createStateVector(); u_ptr->randomize();
154 p_ptr = assembler->createStateVector(); p_ptr->randomize();
155 du_ptr = assembler->createStateVector(); du_ptr->randomize();
156 dy_ptr = assembler->createStateVector(); dy_ptr->randomize();
157 yu_ptr = assembler->createStateVector(); yu_ptr->randomize();
158 yp_ptr = assembler->createStateVector(); yp_ptr->randomize();
159 r_ptr = assembler->createResidualVector(); r_ptr->randomize();
160 z_ptr = assembler->createControlVector(); z_ptr->randomize();
161 dz_ptr = assembler->createControlVector(); dz_ptr->randomize();
162 ROL::Ptr<ROL::Vector<RealT> > up, pp, dup, dyp, yup, ypp, rp, zp, dzp;
163 up = ROL::makePtr<PDE_PrimalSimVector<RealT>>(u_ptr,pde,assembler);
164 pp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(p_ptr,pde,assembler);
165 dup = ROL::makePtr<PDE_PrimalSimVector<RealT>>(du_ptr,pde,assembler);
166 dyp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(dy_ptr,pde,assembler);
167 yup = ROL::makePtr<PDE_PrimalSimVector<RealT>>(yu_ptr,pde,assembler);
168 ypp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(yp_ptr,pde,assembler);
169 rp = ROL::makePtr<PDE_DualSimVector<RealT>>(r_ptr,pde,assembler);
170 zp = ROL::makePtr<PDE_PrimalOptVector<RealT>>(z_ptr,pde,assembler);
171 dzp = ROL::makePtr<PDE_PrimalOptVector<RealT>>(dz_ptr,pde,assembler);
172 // Create ROL SimOpt vectors
173 ROL::Vector_SimOpt<RealT> x(up,zp);
174 ROL::Vector_SimOpt<RealT> d(dup,dzp);
175
176 // Initialize objective function.
177 std::vector<ROL::Ptr<QoI<RealT> > > qoi_vec(2,ROL::nullPtr);
178 qoi_vec[0] = ROL::makePtr<QoI_State_ThermalFluids<RealT>>(*parlist,
179 pde->getVelocityFE(),
180 pde->getPressureFE(),
181 pde->getThermalFE(),
182 pde->getFieldHelper());
183 qoi_vec[1] = ROL::makePtr<QoI_L2Penalty_ThermalFluids<RealT>>(pde->getVelocityFE(),
184 pde->getPressureFE(),
185 pde->getThermalFE(),
186 pde->getThermalBdryFE(),
187 pde->getBdryCellLocIds(),
188 pde->getFieldHelper());
189 ROL::Ptr<StdObjective_ThermalFluids<RealT> > std_obj
190 = ROL::makePtr<StdObjective_ThermalFluids<RealT>>(*parlist);
191 ROL::Ptr<ROL::Objective_SimOpt<RealT> > obj
192 = ROL::makePtr<PDE_Objective<RealT>>(qoi_vec,std_obj,assembler);
193 ROL::Ptr<ROL::VectorController<RealT> > stateStore
194 = ROL::makePtr<ROL::VectorController<RealT>>();
195 ROL::Ptr<ROL::Reduced_Objective_SimOpt<RealT> > robj
196 = ROL::makePtr<ROL::Reduced_Objective_SimOpt<RealT>>(obj, con, stateStore, up, zp, pp, true, false);
197
198 /*************************************************************************/
199 /***************** BUILD SAMPLER *****************************************/
200 /*************************************************************************/
201 int Nbottom = parlist->sublist("Problem").get("Bottom KL Truncation Order",5);
202 int Nleft = parlist->sublist("Problem").get("Left KL Truncation Order",5);
203 int Nright = parlist->sublist("Problem").get("Right KL Truncation Order",5);
204 int stochDim = Nbottom + Nleft + Nright + 3;
205 int nsamp = parlist->sublist("Problem").get("Number of samples",100);
206 // Build vector of distributions
207 std::vector<ROL::Ptr<ROL::Distribution<RealT> > > distVec(stochDim);
208 Teuchos::ParameterList UList;
209 UList.sublist("Distribution").set("Name","Uniform");
210 UList.sublist("Distribution").sublist("Uniform").set("Lower Bound",-1.0);
211 UList.sublist("Distribution").sublist("Uniform").set("Upper Bound", 1.0);
212 for (int i = 0; i < stochDim; ++i) {
213 distVec[i] = ROL::DistributionFactory<RealT>(UList);
214 }
215 // Sampler
216 ROL::Ptr<ROL::BatchManager<RealT> > bman
217 = ROL::makePtr<ROL::TpetraTeuchosBatchManager<RealT>>(comm);
218 // = ROL::makePtr<PDE_OptVector_BatchManager<RealT>>(comm);
219 ROL::Ptr<ROL::SampleGenerator<RealT> > sampler
220 = ROL::makePtr<ROL::MonteCarloGenerator<RealT>>(nsamp,distVec,bman);
221
222 /*************************************************************************/
223 /***************** BUILD STOCHASTIC PROBLEM ******************************/
224 /*************************************************************************/
225 ROL::OptimizationProblem<RealT> opt(robj,zp);
226 parlist->sublist("SOL").set("Initial Solution",1.0);
227 opt.setStochasticObjective(*parlist,sampler);
228
229 // Run derivative checks
230 bool checkDeriv = parlist->sublist("Problem").get("Check derivatives",false);
231 if ( checkDeriv ) {
232 *outStream << "Check Gradient of Full Objective Function" << std::endl;
233 obj->checkGradient(x,d,true,*outStream);
234 *outStream << std::endl << "Check Hessian of Full Objective Function" << std::endl;
235 obj->checkHessVec(x,d,true,*outStream);
236 *outStream << std::endl << "Check Jacobian of Constraint" << std::endl;
237 con->checkApplyJacobian(x,d,*up,true,*outStream);
238 *outStream << std::endl << "Check Jacobian_1 of Constraint" << std::endl;
239 con->checkApplyJacobian_1(*up,*zp,*dup,*rp,true,*outStream);
240 *outStream << std::endl << "Check Jacobian_2 of Constraint" << std::endl;
241 con->checkApplyJacobian_2(*up,*zp,*dzp,*rp,true,*outStream);
242 *outStream << std::endl << "Check Hessian of Constraint" << std::endl;
243 con->checkApplyAdjointHessian(x,*dup,d,x,true,*outStream);
244 *outStream << std::endl << "Check Hessian_11 of Constraint" << std::endl;
245 con->checkApplyAdjointHessian_11(*up,*zp,*pp,*dup,*rp,true,*outStream);
246 *outStream << std::endl << "Check Hessian_12 of Constraint" << std::endl;
247 con->checkApplyAdjointHessian_12(*up,*zp,*pp,*dup,*dzp,true,*outStream);
248 *outStream << std::endl << "Check Hessian_21 of Constraint" << std::endl;
249 con->checkApplyAdjointHessian_21(*up,*zp,*pp,*dzp,*rp,true,*outStream);
250 *outStream << std::endl << "Check Hessian_22 of Constraint" << std::endl;
251 con->checkApplyAdjointHessian_22(*up,*zp,*pp,*dzp,*dzp,true,*outStream);
252
253 *outStream << std::endl << "Check Adjoint Jacobian of Constraint" << std::endl;
254 con->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream);
255 *outStream << std::endl << "Check Adjoint Jacobian_1 of Constraint" << std::endl;
256 con->checkAdjointConsistencyJacobian_1(*pp,*dup,*up,*zp,true,*outStream);
257 *outStream << std::endl << "Check Adjoint Jacobian_2 of Constraint" << std::endl;
258 con->checkAdjointConsistencyJacobian_2(*pp,*dzp,*up,*zp,true,*outStream);
259
260 *outStream << std::endl << "Check Constraint Solve" << std::endl;
261 con->checkSolve(*up,*zp,*rp,true,*outStream);
262 *outStream << std::endl << "Check Inverse Jacobian_1 of Constraint" << std::endl;
263 con->checkInverseJacobian_1(*rp,*dup,*up,*zp,true,*outStream);
264 *outStream << std::endl << "Check Inverse Adjoint Jacobian_1 of Constraint" << std::endl;
265 con->checkInverseAdjointJacobian_1(*rp,*pp,*up,*zp,true,*outStream);
266
267 *outStream << std::endl << "Check Gradient of Reduced Objective Function" << std::endl;
268 robj->checkGradient(*zp,*dzp,true,*outStream);
269 *outStream << std::endl << "Check Hessian of Reduced Objective Function" << std::endl;
270 robj->checkHessVec(*zp,*dzp,true,*outStream);
271 }
272
273 up->zero();
274 zp->zero();
275 parlist->sublist("Step").set("Type","Trust Region");
276 ROL::OptimizationSolver<RealT> solver(opt,*parlist);
277 std::clock_t timer = std::clock();
278 solver.solve(*outStream);
279 *outStream << "Optimization time: "
280 << static_cast<RealT>(std::clock()-timer)/static_cast<RealT>(CLOCKS_PER_SEC)
281 << " seconds." << std::endl << std::endl;
282
283 /*************************************************************************/
284 /***************** OUTPUT RESULTS ****************************************/
285 /*************************************************************************/
286 std::clock_t timer_print = std::clock();
287 assembler->printMeshData(*outStream);
288 // Output control to file
289 pdecon->outputTpetraVector(z_ptr,"control.txt");
290 // Output expected state and samples to file
291 *outStream << std::endl << "Print Expected Value of State" << std::endl;
292 up->zero(); pp->zero(); dup->zero(); dzp->zero(); yup->zero(); dyp->zero();
293 RealT tol(1.e-8);
294 ROL::Ptr<ROL::BatchManager<RealT> > bman_Eu
295 = ROL::makePtr<ROL::TpetraTeuchosBatchManager<RealT>>(comm);
296 std::vector<RealT> sample(stochDim);
297 std::stringstream name_samp;
298 name_samp << "samples_" << bman->batchID() << ".txt";
299 std::ofstream file_samp;
300 file_samp.open(name_samp.str());
301 file_samp << std::scientific << std::setprecision(15);
302 for (int i = 0; i < sampler->numMySamples(); ++i) {
303 *outStream << "Sample i = " << i << std::endl;
304 sample = sampler->getMyPoint(i);
305 con->setParameter(sample);
306 con->solve(*rp,*dup,*zp,tol);
307 up->axpy(sampler->getMyWeight(i),*dup);
308 con->solve(*rp,*dyp,*dzp,tol);
309 yup->axpy(sampler->getMyWeight(i),*dyp);
310 for (int j = 0; j < stochDim; ++j) {
311 file_samp << std::setw(25) << std::left << sample[j];
312 }
313 file_samp << std::endl;
314 }
315 file_samp.close();
316 bman_Eu->sumAll(*up,*pp);
317 bman_Eu->sumAll(*yup,*ypp);
318 pdecon->outputTpetraVector(p_ptr,"mean_state.txt");
319 pdecon->outputTpetraVector(yp_ptr,"mean_uncontrolled_state.txt");
320 // Build full objective function distribution
321 *outStream << std::endl << "Print Objective CDF" << std::endl;
322 int nsamp_dist = parlist->sublist("Problem").get("Number of output samples",100);
323 ROL::Ptr<ROL::SampleGenerator<RealT> > sampler_dist
324 = ROL::makePtr<ROL::MonteCarloGenerator<RealT>>(nsamp_dist,distVec,bman);
325 print<RealT>(*robj,*zp,*sampler_dist,nsamp_dist,comm,"obj_samples.txt");
326 // Build vorticity objective function distribution
327 ROL::Ptr<ROL::Objective_SimOpt<RealT> > obj0
328 = ROL::makePtr<IntegralObjective<RealT>>(qoi_vec[0],assembler);
329 ROL::Ptr<ROL::VectorController<RealT> > stateStore0
330 = ROL::makePtr<ROL::VectorController<RealT>>();
331 ROL::Ptr<ROL::Reduced_Objective_SimOpt<RealT> > robj0
332 = ROL::makePtr<ROL::Reduced_Objective_SimOpt<RealT>>(obj0, con, stateStore0, up, zp, pp, true, false);
333 print<RealT>(*robj0,*zp,*sampler_dist,nsamp_dist,comm,"vort_samples.txt");
334
335 *outStream << "Output time: "
336 << static_cast<RealT>(std::clock()-timer_print)/static_cast<RealT>(CLOCKS_PER_SEC)
337 << " seconds." << std::endl << std::endl;
338 }
339 catch (std::logic_error& err) {
340 *outStream << err.what() << "\n";
341 errorFlag = -1000;
342 }; // end try
343
344 if (errorFlag != 0)
345 std::cout << "End Result: TEST FAILED\n";
346 else
347 std::cout << "End Result: TEST PASSED\n";
348
349 return 0;
350 }