Debian Codegraph @

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