Debian Codegraph @

packages/rol/example/PDE-OPT/allen-cahn/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_02.cpp
11 \brief Shows how to solve the Poisson-Boltzmann problem.
12 */
13
14 #include "Teuchos_Comm.hpp"
15 #include "Teuchos_GlobalMPISession.hpp"
16 #include "Teuchos_XMLParameterListHelpers.hpp"
17
18 #include "Tpetra_Core.hpp"
19 #include "Tpetra_Version.hpp"
20
21 #include <iostream>
22 #include <algorithm>
23
24 #include "ROL_Stream.hpp"
25 #include "ROL_StochasticProblem.hpp"
26 #include "ROL_Solver.hpp"
27 #include "ROL_UnaryFunctions.hpp"
28 #include "ROL_Bounds.hpp"
29 #include "ROL_Reduced_Objective_SimOpt.hpp"
30 #include "ROL_MonteCarloGenerator.hpp"
31 #include "ROL_TpetraTeuchosBatchManager.hpp"
32 #include "ROL_CompositeConstraint_SimOpt.hpp"
33
34 #include "../TOOLS/linearpdeconstraint.hpp"
35 #include "../TOOLS/pdeconstraint.hpp"
36 #include "../TOOLS/pdeobjective.hpp"
37 #include "../TOOLS/pdevector.hpp"
38 #include "../TOOLS/batchmanager.hpp"
39 #include "pde_poisson_boltzmann_ex02.hpp"
40 #include "mesh_poisson_boltzmann_ex02.hpp"
41 #include "obj_poisson_boltzmann_ex02.hpp"
42
43 typedef double RealT;
44
45 template<class Real>
46 Real random(const Teuchos::Comm<int> &comm,
47 const Real a = -1, const Real b = 1) {
48 Real val(0), u(0);
49 if ( Teuchos::rank<int>(comm)==0 ) {
50 u = static_cast<Real>(rand())/static_cast<Real>(RAND_MAX);
51 val = (b-a)*u + a;
52 }
53 Teuchos::broadcast<int,Real>(comm,0,1,&val);
54 return val;
55 }
56
57 int main(int argc, char *argv[]) {
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_ex02.xml";
83 Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
84 Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
85
86 /*** Initialize main data structure. ***/
87 ROL::Ptr<MeshManager<RealT> > meshMgr
88 = ROL::makePtr<MeshManager_Example02<RealT>>(*parlist);
89 // Initialize PDE describe Poisson's equation
90 ROL::Ptr<PDE_Poisson_Boltzmann_ex02<RealT> > pde
91 = ROL::makePtr<PDE_Poisson_Boltzmann_ex02<RealT>>(*parlist);
92 ROL::Ptr<ROL::Constraint_SimOpt<RealT> > con
93 = ROL::makePtr<PDE_Constraint<RealT>>(pde,meshMgr,serial_comm,*parlist,*outStream);
94 ROL::Ptr<PDE_Constraint<RealT> > pdeCon
95 = ROL::dynamicPtrCast<PDE_Constraint<RealT> >(con);
96 ROL::Ptr<PDE_Doping<RealT> > pdeDoping
97 = ROL::makePtr<PDE_Doping<RealT>>(*parlist);
98 ROL::Ptr<ROL::Constraint_SimOpt<RealT> > conDoping
99 = ROL::makePtr<Linear_PDE_Constraint<RealT>>(pdeDoping,meshMgr,serial_comm,*parlist,*outStream,true);
100 const ROL::Ptr<Assembler<RealT> > assembler = pdeCon->getAssembler();
101 assembler->printMeshData(*outStream);
102 con->setSolveParameters(*parlist);
103
104 /*************************************************************************/
105 /***************** BUILD VECTORS *****************************************/
106 /*************************************************************************/
107 ROL::Ptr<Tpetra::MultiVector<> > u_ptr = assembler->createStateVector();
108 ROL::Ptr<Tpetra::MultiVector<> > p_ptr = assembler->createStateVector();
109 ROL::Ptr<Tpetra::MultiVector<> > r_ptr = assembler->createResidualVector();
110 ROL::Ptr<Tpetra::MultiVector<> > z_ptr = assembler->createControlVector();
111 ROL::Ptr<ROL::Vector<RealT> > up, pp, rp, zp;
112 u_ptr->randomize(); //u_ptr->putScalar(static_cast<RealT>(1));
113 p_ptr->randomize(); //p_ptr->putScalar(static_cast<RealT>(1));
114 r_ptr->randomize(); //r_ptr->putScalar(static_cast<RealT>(1));
115 z_ptr->randomize(); //z_ptr->putScalar(static_cast<RealT>(1));
116 up = ROL::makePtr<PDE_PrimalSimVector<RealT>>(u_ptr,pde,assembler,*parlist);
117 pp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(p_ptr,pde,assembler,*parlist);
118 rp = ROL::makePtr<PDE_DualSimVector<RealT>>(r_ptr,pde,assembler,*parlist);
119 zp = ROL::makePtr<PDE_PrimalOptVector<RealT>>(z_ptr,pde,assembler,*parlist);
120
121 /*************************************************************************/
122 /***************** BUILD SAMPLER *****************************************/
123 /*************************************************************************/
124 int stochDim = 3;
125 std::vector<ROL::Ptr<ROL::Distribution<RealT> > > distVec(stochDim);
126 // Build lambda2 distribution
127 Teuchos::ParameterList LvolList;
128 LvolList.sublist("Distribution").set("Name","Uniform");
129 LvolList.sublist("Distribution").sublist("Uniform").set("Lower Bound", -2.0);
130 LvolList.sublist("Distribution").sublist("Uniform").set("Upper Bound", -1.0);
131 distVec[0] = ROL::DistributionFactory<RealT>(LvolList);
132 // Build delta2 distribution
133 Teuchos::ParameterList DvolList;
134 DvolList.sublist("Distribution").set("Name","Uniform");
135 DvolList.sublist("Distribution").sublist("Uniform").set("Lower Bound", -1.0);
136 DvolList.sublist("Distribution").sublist("Uniform").set("Upper Bound", 0.0);
137 distVec[1] = ROL::DistributionFactory<RealT>(DvolList);
138 // Build doping diffusion distribution
139 Teuchos::ParameterList dopeList;
140 dopeList.sublist("Distribution").set("Name","Uniform");
141 dopeList.sublist("Distribution").sublist("Uniform").set("Lower Bound", 2e-6);
142 dopeList.sublist("Distribution").sublist("Uniform").set("Upper Bound", 2e-4);
143 distVec[2] = ROL::DistributionFactory<RealT>(dopeList);
144 // Build sampler
145 int nsamp = parlist->sublist("Problem").get("Number of Samples",100);
146 ROL::Ptr<ROL::BatchManager<RealT> > bman
147 = ROL::makePtr<ROL::TpetraTeuchosBatchManager<RealT>>(comm);
148 ROL::Ptr<ROL::SampleGenerator<RealT> > sampler
149 = ROL::makePtr<ROL::MonteCarloGenerator<RealT>>(nsamp,distVec,bman);
150 // Print samples
151 std::vector<RealT> sample(stochDim), Lmean(stochDim), Gmean(stochDim);
152 std::stringstream name_samp;
153 name_samp << "samples_" << bman->batchID() << ".txt";
154 std::ofstream file_samp;
155 file_samp.open(name_samp.str());
156 for (int i = 0; i < sampler->numMySamples(); ++i) {
157 sample = sampler->getMyPoint(i);
158 file_samp << std::scientific << std::setprecision(15);
159 for (int j = 0; j < stochDim; ++j) {
160 file_samp << std::setw(25) << std::left << sample[j];
161 Lmean[j] += sampler->getMyWeight(i)*sample[j];
162 }
163 file_samp << std::endl;
164 }
165 file_samp.close();
166 bman->sumAll(&Lmean[0],&Gmean[0],stochDim);
167
168 /*************************************************************************/
169 /***************** BUILD REFERENCE DOPING AND POTENTIAL ******************/
170 /*************************************************************************/
171 ROL::Ptr<Tpetra::MultiVector<> > ru_ptr = assembler->createStateVector();
172 ROL::Ptr<ROL::Vector<RealT> > rup
173 = ROL::makePtr<PDE_PrimalSimVector<RealT>>(ru_ptr,pde,assembler,*parlist);
174 ROL::Ptr<Tpetra::MultiVector<> > rz_ptr = assembler->createControlVector();
175 ROL::Ptr<ROL::Vector<RealT> > rzp
176 = ROL::makePtr<PDE_PrimalOptVector<RealT>>(rz_ptr,pde,assembler,*parlist);
177 ROL::Ptr<Doping<RealT> > dope
178 = ROL::makePtr<Doping<RealT>>(pde->getFE(),
179 assembler->getDofManager()->getCellDofs(),
180 assembler->getCellIds(),*parlist);
181 // Initialize "filtered" of "unfiltered" constraint.
182 ROL::Ptr<ROL::Constraint_SimOpt<RealT> > pdeWithDoping
183 = ROL::makePtr<ROL::CompositeConstraint_SimOpt<RealT>>(con, conDoping,
184 *rp, *rp, *up, *zp, *zp, true, true);
185 pdeWithDoping->setSolveParameters(*parlist);
186 dope->build(rz_ptr);
187 RealT tol(1.e-8);
188 pdeWithDoping->setParameter(Gmean);
189 pdeWithDoping->solve(*rp,*rup,*rzp,tol);
190 pdeCon->outputTpetraVector(ru_ptr,"reference_state.txt");
191 pdeCon->outputTpetraVector(rz_ptr,"reference_control.txt");
192
193 /*************************************************************************/
194 /***************** BUILD COST FUNCTIONAL *********************************/
195 /*************************************************************************/
196 std::vector<ROL::Ptr<QoI<RealT> > > qoi_vec(3,ROL::nullPtr);
197 // Current flow over drain
198 qoi_vec[0] = ROL::makePtr<QoI_State_Cost_1_Poisson_Boltzmann<RealT>>(pde->getFE(),
199 pde->getBdryFE(),pde->getBdryCellLocIds(),*parlist);
200 ROL::Ptr<IntegralObjective<RealT> > stateObj
201 = ROL::makePtr<IntegralObjective<RealT>>(qoi_vec[0],assembler);
202 // Deviation from reference doping
203 qoi_vec[1] = ROL::makePtr<QoI_Control_Cost_1_Poisson_Boltzmann<RealT>>(pde->getFE(),dope);
204 ROL::Ptr<IntegralObjective<RealT> > ctrlObj1
205 = ROL::makePtr<IntegralObjective<RealT>>(qoi_vec[1],assembler);
206 // H1-Seminorm of doping
207 qoi_vec[2] = ROL::makePtr<QoI_Control_Cost_2_Poisson_Boltzmann<RealT>>(pde->getFE());
208 ROL::Ptr<IntegralObjective<RealT> > ctrlObj2
209 = ROL::makePtr<IntegralObjective<RealT>>(qoi_vec[2],assembler);
210 // Build standard vector objective function
211 RealT currentWeight = parlist->sublist("Problem").get("Desired Current Scale",1.5);
212 RealT J = stateObj->value(*rup,*rzp,tol); // Reference current flow over drain
213 J *= currentWeight; // Increase current flow by 50%
214 RealT w1 = parlist->sublist("Problem").get("State Cost Parameter",1e-3);
215 RealT w2 = parlist->sublist("Problem").get("Control Misfit Parameter",1e-2);
216 RealT w3 = parlist->sublist("Problem").get("Control Cost Parameter",1e-8);
217 ROL::Ptr<ROL::StdObjective<RealT> > std_obj
218 = ROL::makePtr<StdObjective_Poisson_Boltzmann<RealT>>(J,w1,w2,w3);
219 // Build full-space objective
220 ROL::Ptr<PDE_Objective<RealT> > obj
221 = ROL::makePtr<PDE_Objective<RealT>>(qoi_vec,std_obj,assembler);
222 // Build reduced-space objective
223 bool storage = parlist->sublist("Problem").get("Use state storage",true);
224 ROL::Ptr<ROL::VectorController<RealT> > stateStore
225 = ROL::makePtr<ROL::VectorController<RealT>>();
226 ROL::Ptr<ROL::Reduced_Objective_SimOpt<RealT> > objReduced
227 = ROL::makePtr<ROL::Reduced_Objective_SimOpt<RealT>>(
228 obj,pdeWithDoping,stateStore,up,zp,pp,storage);
229
230 /*************************************************************************/
231 /***************** BUILD BOUND CONSTRAINT ********************************/
232 /*************************************************************************/
233 ROL::Ptr<Tpetra::MultiVector<> > lo_ptr = assembler->createControlVector();
234 ROL::Ptr<Tpetra::MultiVector<> > hi_ptr = assembler->createControlVector();
235 ROL::Ptr<DopingBounds<RealT> > dopeBnd
236 = ROL::makePtr<DopingBounds<RealT>>(pde->getFE(),
237 assembler->getDofManager()->getCellDofs(),
238 assembler->getCellIds(),*parlist);
239 dopeBnd->build(lo_ptr,hi_ptr);
240 ROL::Ptr<ROL::Vector<RealT> > lop, hip;
241 lop = ROL::makePtr<PDE_PrimalOptVector<RealT>>(lo_ptr,pde,assembler);
242 hip = ROL::makePtr<PDE_PrimalOptVector<RealT>>(hi_ptr,pde,assembler);
243 ROL::Ptr<ROL::BoundConstraint<RealT> > bnd
244 = ROL::makePtr<ROL::Bounds<RealT>>(lop,hip);
245 bool deactivate = parlist->sublist("Problem").get("Deactivate Bound Constraints",false);
246 if (deactivate) {
247 bnd->deactivate();
248 }
249
250 /*************************************************************************/
251 /***************** BUILD STOCHASTIC PROBLEM ******************************/
252 /*************************************************************************/
253 ROL::Ptr<ROL::StochasticProblem<RealT>>
254 opt = ROL::Ptr<ROL::StochasticProblem<RealT>>(objReduced,zp);
255 opt->addBoundConstraint(bnd);
256 parlist->sublist("SOL").set("Initial Statistic", static_cast<RealT>(1));
257 opt->makeObjectiveStochastic(*parlist,sampler);
258 opt->finalize(false,true,*outStream);
259
260 /*************************************************************************/
261 /***************** RUN VECTOR AND DERIVATIVE CHECKS **********************/
262 /*************************************************************************/
263 bool checkDeriv = parlist->sublist("Problem").get("Check Derivatives",false);
264 if ( checkDeriv ) {
265 ROL::Ptr<Tpetra::MultiVector<> > du_ptr = assembler->createStateVector();
266 ROL::Ptr<Tpetra::MultiVector<> > dz_ptr = assembler->createControlVector();
267 du_ptr->randomize(); //du_ptr->putScalar(static_cast<RealT>(0));
268 dz_ptr->randomize(); //dz_ptr->putScalar(static_cast<RealT>(1));
269 ROL::Ptr<ROL::Vector<RealT> > dup, dzp;
270 dup = ROL::makePtr<PDE_PrimalSimVector<RealT>>(du_ptr,pde,assembler,*parlist);
271 dzp = ROL::makePtr<PDE_PrimalOptVector<RealT>>(dz_ptr,pde,assembler,*parlist);
272 // Create ROL SimOpt vectors
273 ROL::Vector_SimOpt<RealT> x(up,zp);
274 ROL::Vector_SimOpt<RealT> d(dup,dzp);
275
276 objReduced->setParameter(Gmean);
277 *outStream << "\n\nCheck Gradient of Full Objective Function\n";
278 obj->checkGradient(x,d,true,*outStream);
279 *outStream << "\n\nCheck Hessian of Full Objective Function\n";
280 obj->checkHessVec(x,d,true,*outStream);
281 *outStream << "\n\nCheck Full Jacobian of PDE Constraint\n";
282 pdeWithDoping->checkApplyJacobian(x,d,*rp,true,*outStream);
283 *outStream << "\n\nCheck Jacobian_1 of PDE Constraint\n";
284 pdeWithDoping->checkApplyJacobian_1(*up,*zp,*dup,*rp,true,*outStream);
285 *outStream << "\n\nCheck Jacobian_2 of PDE Constraint\n";
286 pdeWithDoping->checkApplyJacobian_2(*up,*zp,*dzp,*rp,true,*outStream);
287 *outStream << "\n\nCheck Full Hessian of PDE Constraint\n";
288 pdeWithDoping->checkApplyAdjointHessian(x,*pp,d,x,true,*outStream);
289 *outStream << "\n";
290 pdeWithDoping->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream);
291 *outStream << "\n";
292 pdeWithDoping->checkInverseJacobian_1(*rp,*dup,*up,*zp,true,*outStream);
293 *outStream << "\n";
294 *outStream << "\n\nCheck Gradient of Reduced Objective Function\n";
295 objReduced->checkGradient(*zp,*dzp,true,*outStream);
296 *outStream << "\n\nCheck Hessian of Reduced Objective Function\n";
297 objReduced->checkHessVec(*zp,*dzp,true,*outStream);
298
299 opt->check(true,*outStream);
300 }
301
302 /*************************************************************************/
303 /***************** SOLVE OPTIMIZATION PROBLEM ****************************/
304 /*************************************************************************/
305 parlist->sublist("Step").set("Type","Trust Region");
306 ROL::Solver<RealT> solver(opt,*parlist);
307 zp->set(*rzp);
308 std::clock_t timer = std::clock();
309 solver.solve(*outStream);
310 *outStream << "Optimization time: "
311 << static_cast<RealT>(std::clock()-timer)/static_cast<RealT>(CLOCKS_PER_SEC)
312 << " seconds." << std::endl << std::endl;
313
314 /*************************************************************************/
315 /***************** OUTPUT RESULTS ****************************************/
316 /*************************************************************************/
317 std::clock_t timer_print = std::clock();
318 // Output control to file
319 pdeCon->outputTpetraVector(z_ptr,"control.txt");
320 // Output expected state and samples to file
321 ROL::Ptr<Tpetra::MultiVector<> > Lu_ptr = assembler->createStateVector();
322 ROL::Ptr<Tpetra::MultiVector<> > Lv_ptr = assembler->createStateVector();
323 ROL::Ptr<Tpetra::MultiVector<> > Gu_ptr = assembler->createStateVector();
324 ROL::Ptr<Tpetra::MultiVector<> > Gv_ptr = assembler->createStateVector();
325 ROL::Ptr<ROL::Vector<RealT> > Lup, Gup, Lvp, Gvp;
326 Lup = ROL::makePtr<PDE_PrimalSimVector<RealT>>(Lu_ptr,pde,assembler,*parlist);
327 Lvp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(Lv_ptr,pde,assembler,*parlist);
328 Gup = ROL::makePtr<PDE_PrimalSimVector<RealT>>(Gu_ptr,pde,assembler,*parlist);
329 Gvp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(Gv_ptr,pde,assembler,*parlist);
330 ROL::Elementwise::Power<RealT> sqr(2.0);
331 for (int i = 0; i < sampler->numMySamples(); ++i) {
332 sample = sampler->getMyPoint(i);
333 con->setParameter(sample);
334 con->solve(*rp,*Gup,*zp,tol);
335 Gvp->set(*Gup); Gvp->applyUnary(sqr);
336 Lup->axpy(sampler->getMyWeight(i),*Gup);
337 Lvp->axpy(sampler->getMyWeight(i),*Gvp);
338 }
339 bman->sumAll(*Lup,*Gup);
340 pdeCon->outputTpetraVector(Gu_ptr,"mean_state.txt");
341 bman->sumAll(*Lvp,*Gvp);
342 Gup->applyUnary(sqr);
343 Gvp->axpy(-1.0,*Gup);
344 pdeCon->outputTpetraVector(Gv_ptr,"variance_state.txt");
345 // Build objective function distribution
346 RealT val(0), val1(0), val2(0);
347 int nsamp_dist = parlist->sublist("Problem").get("Number of Output Samples",100);
348 ROL::Ptr<ROL::SampleGenerator<RealT> > sampler_dist
349 = ROL::makePtr<ROL::MonteCarloGenerator<RealT>>(nsamp_dist,distVec,bman);
350 std::stringstream name;
351 name << "obj_samples_" << bman->batchID() << ".txt";
352 std::ofstream file;
353 file.open(name.str());
354 for (int i = 0; i < sampler_dist->numMySamples(); ++i) {
355 sample = sampler_dist->getMyPoint(i);
356 objReduced->setParameter(sample);
357 val = objReduced->value(*zp,tol);
358 val1 = ctrlObj1->value(*up,*zp,tol);
359 val2 = ctrlObj2->value(*up,*zp,tol);
360 file << std::scientific << std::setprecision(15);
361 for (int j = 0; j < stochDim; ++j) {
362 file << std::setw(25) << std::left << sample[j];
363 }
364 file << std::setw(25) << std::left << val;
365 file << std::setw(25) << std::left << (val-w2*val1-w3*val2)/w1;
366 file << std::setw(25) << std::left << val1;
367 file << std::setw(25) << std::left << val2;
368 file << std::endl;
369 }
370 file.close();
371 *outStream << "Output time: "
372 << static_cast<RealT>(std::clock()-timer_print)/static_cast<RealT>(CLOCKS_PER_SEC)
373 << " seconds." << std::endl << std::endl;
374 }
375 catch (std::logic_error& err) {
376 *outStream << err.what() << "\n";
377 errorFlag = -1000;
378 }; // end try
379
380 if (errorFlag != 0)
381 std::cout << "End Result: TEST FAILED\n";
382 else
383 std::cout << "End Result: TEST PASSED\n";
384
385 return 0;
386 }