Debian Codegraph @

packages/rol/example/PDE-OPT/topo-opt/elasticity/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 stochastic stuctural topology optimization problem.
12 */
13
14 #include "Teuchos_Comm.hpp"
15 #include "Teuchos_Time.hpp"
16 #include "ROL_Stream.hpp"
17 #include "Teuchos_GlobalMPISession.hpp"
18 #include "Teuchos_XMLParameterListHelpers.hpp"
19
20 #include "Tpetra_Core.hpp"
21 #include "Tpetra_Version.hpp"
22
23 #include <iostream>
24 #include <algorithm>
25
26 #include "ROL_Solver.hpp"
27 #include "ROL_StochasticProblem.hpp"
28 #include "ROL_Bounds.hpp"
29 #include "ROL_LinearCombinationObjective.hpp"
30 #include "ROL_TpetraTeuchosBatchManager.hpp"
31 #include "ROL_SingletonTeuchosBatchManager.hpp"
32
33 #include "../../TOOLS/pdeobjective.hpp"
34 #include "../../TOOLS/pdevector.hpp"
35 #include "../../TOOLS/meshreader.hpp"
36
37 #include "src/mesh_topo-opt.hpp"
38 #include "src/pde_elasticity.hpp"
39 #include "src/sampler.hpp"
40
41 #include "../src/pde_filter.hpp"
42 #include "../src/filtered_compliance_robj.hpp"
43 #include "../src/volume_con.hpp"
44 #include "../src/volume_obj.hpp"
45 #include "../src/obj_volume.hpp"
46 #include "../src/obj_phasefield.hpp"
47 #include "../src/printCDF.hpp"
48
49 typedef double RealT;
50
51 int main(int argc, char *argv[]) {
52 // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
53 int iprint = argc - 1;
54 ROL::Ptr<std::ostream> outStream;
55 ROL::nullstream bhs; // outputs nothing
56
57 /*** Initialize communicator. ***/
58 Teuchos::GlobalMPISession mpiSession (&argc, &argv, &bhs);
59 ROL::Ptr<const Teuchos::Comm<int> > comm
60 = Tpetra::getDefaultComm();
61 ROL::Ptr<const Teuchos::Comm<int> > serial_comm
62 = ROL::makePtr<Teuchos::SerialComm<int>>();
63 const int myRank = comm->getRank();
64 if ((iprint > 0) && (myRank == 0)) {
65 outStream = ROL::makePtrFromRef(std::cout);
66 }
67 else {
68 outStream = ROL::makePtrFromRef(bhs);
69 }
70 int errorFlag = 0;
71
72 // *** Example body.
73 try {
74 RealT tol(1e-8);
75
76 /*** Read in XML input ***/
77 std::string filename = "input_ex02.xml";
78 Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
79 Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
80
81 // Retrieve parameters.
82 const std::string example = parlist->sublist("Problem").get("Example", "Default");
83 const RealT volFraction = parlist->sublist("Problem").get("Volume Fraction", 0.4);
84 const RealT initDens = parlist->sublist("Problem").get("Initial Density",volFraction);
85 const RealT cmpFactor = parlist->sublist("Problem").get("Compliance Factor", 1.1);
86 int probDim = parlist->sublist("Problem").get("Problem Dimension", 2);
87 const std::string minType = parlist->sublist("Problem").get("Minimization Type", "Volume");
88 const bool usePhaseField = parlist->sublist("Problem").get("Use Phase Field", false);
89 bool useFilter = parlist->sublist("Problem").get("Use Filter", true);
90 const bool normalizeObj = parlist->sublist("Problem").get("Normalize Compliance", true);
91 const bool volEq = parlist->sublist("Problem").get("Use Volume Equality Constraint",true);
92 std::string hessAppr = parlist->sublist("Problem").get("Hessian Approximation","None");
93 hessAppr = (minType == "Compliance" ? hessAppr : "None");
94 if (example == "2D Wheel" ||
95 example == "2D Truss" ||
96 example == "2D Cantilever with 1 Load" ||
97 example == "2D Cantilever with 3 Loads" ||
98 example == "2D Beams" ||
99 example == "2D Carrier Plate")
100 probDim = 2;
101 else if (example == "3D Cantilever" ||
102 example == "3D L Beam")
103 probDim = 3;
104 if (usePhaseField) useFilter = false;
105
106 /*** Initialize main data structure. ***/
107 TEUCHOS_TEST_FOR_EXCEPTION(probDim<2 || probDim>3, std::invalid_argument,
108 ">>> PDE-OPT/topo-opt/elasticity/example_01.cpp: Problem dim is not 2 or 3!");
109 ROL::Ptr<MeshManager<RealT>> meshMgr;
110 if (probDim == 2) meshMgr = ROL::makePtr<MeshManager_TopoOpt<RealT>>(*parlist);
111 else meshMgr = ROL::makePtr<MeshReader<RealT>>(*parlist);
112 // Initialize PDE describing elasticity equations.
113 ROL::Ptr<PDE_Elasticity<RealT>>
114 pde = ROL::makePtr<PDE_Elasticity<RealT>>(*parlist);
115
116 // Initialize the filter PDE.
117 ROL::Ptr<PDE<RealT>> pdeFilter = pde;
118
119 // Initialize reduced compliance objective function.
120 ROL::Ptr<ROL::Objective<RealT>> robj_com;
121 ROL::Ptr<Assembler<RealT>> assembler, assemblerFilter;
122 if (useFilter && !usePhaseField) {
123 pdeFilter = ROL::makePtr<PDE_Filter<RealT>>(*parlist);
124 pde->setDensityFields(pdeFilter->getFields());
125 robj_com = ROL::makePtr<TopOptFilteredComplianceObjective<RealT>>(
126 pde,pdeFilter,meshMgr,comm,*parlist,*outStream);
127 assembler = ROL::dynamicPtrCast<TopOptFilteredComplianceObjective<RealT>>(robj_com)->getAssembler();
128 assemblerFilter = ROL::dynamicPtrCast<TopOptFilteredComplianceObjective<RealT>>(robj_com)->getFilterAssembler();
129 }
130 else {
131 robj_com = ROL::makePtr<TopOptComplianceObjective<RealT>>(
132 pde,meshMgr,comm,*parlist,*outStream);
133 assembler = ROL::dynamicPtrCast<TopOptComplianceObjective<RealT>>(robj_com)->getAssembler();
134 assemblerFilter = assembler;
135 }
136
137 // Create vectors.
138 ROL::Ptr<Tpetra::MultiVector<>> u_ptr, p_ptr, r_ptr, z_ptr;
139 u_ptr = assembler->createStateVector(); u_ptr->putScalar(0.0);
140 p_ptr = assembler->createStateVector(); p_ptr->putScalar(0.0);
141 r_ptr = assembler->createResidualVector(); r_ptr->putScalar(0.0);
142 z_ptr = assemblerFilter->createControlVector(); z_ptr->putScalar(1.0);
143 ROL::Ptr<ROL::Vector<RealT>> up, pp, rp, zp;
144 up = ROL::makePtr<PDE_PrimalSimVector<RealT>>(u_ptr,pde,assembler,*parlist);
145 pp = ROL::makePtr<PDE_PrimalSimVector<RealT>>(p_ptr,pde,assembler,*parlist);
146 rp = ROL::makePtr<PDE_DualSimVector<RealT>>(r_ptr,pde,assembler,*parlist);
147 zp = ROL::makePtr<PDE_PrimalOptVector<RealT>>(z_ptr,pdeFilter,assemblerFilter,*parlist);
148
149 // Build volume objective function.
150 ROL::Ptr<QoI<RealT>> qoi_vol;
151 if (minType == "Compliance" && volEq) {
152 if (useFilter && !usePhaseField)
153 qoi_vol = ROL::makePtr<QoI_Volume_TopoOpt<RealT>>(ROL::dynamicPtrCast<PDE_Filter<RealT>>(pdeFilter)->getDensityFE(),
154 volFraction);
155 else
156 qoi_vol = ROL::makePtr<QoI_Volume_TopoOpt<RealT>>(pde->getDensityFE(),
157 volFraction);
158 }
159 else {
160 if (useFilter && !usePhaseField)
161 qoi_vol = ROL::makePtr<QoI_Volume_TopoOpt<RealT>>(ROL::dynamicPtrCast<PDE_Filter<RealT>>(pdeFilter)->getDensityFE());
162 else
163 qoi_vol = ROL::makePtr<QoI_Volume_TopoOpt<RealT>>(pde->getDensityFE());
164 }
165 ROL::Ptr<TopOptVolumeObjective<RealT>>
166 obj_vol = ROL::makePtr<TopOptVolumeObjective<RealT>>(qoi_vol,assemblerFilter,zp);
167 ROL::Ptr<TopOptVolumeConstraint<RealT>>
168 con_vol = ROL::makePtr<TopOptVolumeConstraint<RealT>>(qoi_vol,assemblerFilter,zp);
169
170 // Compute volume
171 zp->setScalar(1.0);
172 RealT vol = obj_vol->value(*zp,tol);
173
174 // Normalize compliance objective function
175 RealT cs(1);
176 zp->setScalar(initDens);
177 if (normalizeObj) {
178 if (useFilter && !usePhaseField)
179 cs = ROL::dynamicPtrCast<TopOptFilteredComplianceObjective<RealT>>(robj_com)->normalize(*zp,tol);
180 else
181 cs = ROL::dynamicPtrCast<TopOptComplianceObjective<RealT>>(robj_com)->normalize(*zp,tol);
182 }
183
184 // Output problem details
185 *outStream << std::endl;
186 *outStream << "Problem Data" << std::endl;
187 *outStream << " Example: " << example << std::endl;
188 *outStream << " Dimension: " << probDim << std::endl;
189 *outStream << " Minimize Type: " << minType << std::endl;
190 *outStream << " Use Phase Field: " << usePhaseField << std::endl;
191 if (!usePhaseField) {
192 *outStream << " SIMP Power: "
193 << parlist->sublist("Problem").get("SIMP Power",3.0) << std::endl;
194 *outStream << " Use Filter: " << useFilter << std::endl;
195 }
196 if (minType == "Volume") {
197 *outStream << " Compliance Factor: " << cmpFactor << std::endl;
198 }
199 else if (minType == "Compliance") {
200 *outStream << " Volume Fraction: " << volFraction << std::endl;
201 *outStream << " Initial Density: " << initDens << std::endl;
202 *outStream << " Use Equality: " << volEq << std::endl;
203 *outStream << " Hessian Approx: " << hessAppr << std::endl;
204 }
205 *outStream << " Domain Volume: " << vol << std::endl;
206 *outStream << " Compliance Scale: " << cs << std::endl;
207 *outStream << std::endl;
208
209 // Create objective, constraint, multiplier and bounds
210 ROL::Ptr<ROL::Objective<RealT>> obj;
211 ROL::Ptr<ROL::Constraint<RealT>> icon;
212 ROL::Ptr<ROL::Vector<RealT>> iup, ilp;
213 ROL::Ptr<ROL::Vector<RealT>> imul;
214 ROL::Ptr<ROL::BoundConstraint<RealT>> ibnd;
215 if (!usePhaseField) {
216 if (minType == "Volume") {
217 obj = obj_vol;
218 icon = ROL::makePtr<ROL::ConstraintFromObjective<RealT>>(robj_com);
219 // Set upper bound to compliance for solid beam.
220 zp->setScalar(1.0);
221 RealT comp = robj_com->value(*zp,tol);
222 ilp = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
223 iup = ROL::makePtr<ROL::SingletonVector<RealT>>(cmpFactor*comp);
224 imul = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
225 ibnd = ROL::makePtr<ROL::Bounds<RealT>>(ilp,iup);
226 }
227 else if (minType == "Compliance") {
228 obj = robj_com;
229 icon = con_vol;
230 imul = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
231 if (volEq) {
232 ilp = ROL::nullPtr;
233 iup = ROL::nullPtr;
234 ibnd = ROL::nullPtr;
235 }
236 else {
237 // Set upper bound to fraction of total volume.
238 ilp = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
239 iup = ROL::makePtr<ROL::SingletonVector<RealT>>(volFraction*vol);
240 ibnd = ROL::makePtr<ROL::Bounds<RealT>>(ilp,iup);
241 }
242 }
243 else if (minType == "Total") {
244 std::vector<ROL::Ptr<ROL::Objective<RealT>>> obj_vec(2,ROL::nullPtr);
245 obj_vec[0] = robj_com;
246 obj_vec[1] = obj_vol;
247 std::vector<RealT> weights(2,0.0);
248 weights[0] = static_cast<RealT>(1);
249 weights[1] = parlist->sublist("Problem").get("Volume Objective Scale",0.04096);
250 obj = ROL::makePtr<ROL::LinearCombinationObjective<RealT>>(weights,obj_vec);
251 icon = ROL::nullPtr;
252 ilp = ROL::nullPtr;
253 iup = ROL::nullPtr;
254 imul = ROL::nullPtr;
255 ibnd = ROL::nullPtr;
256 }
257 else {
258 throw ROL::Exception::NotImplemented("Unknown minimization type!");
259 }
260 }
261 else {
262 // Build Modica-Mortola Energy objective function.
263 RealT penParam = parlist->sublist("Problem").get("Phase Field Penalty Parameter",1e-1);
264 ROL::Ptr<QoI<RealT>>
265 qoi_pfe = ROL::makePtr<QoI_ModicaMortolaEnergy_PhaseField<RealT>>(pde->getDensityFE(),
266 penParam);
267 ROL::Ptr<IntegralOptObjective<RealT>>
268 obj_pfe = ROL::makePtr<IntegralOptObjective<RealT>>(qoi_pfe,assembler);
269 // Get weights for linear combination objective.
270 std::vector<RealT> weights(1,0.0);
271 weights[0] = parlist->sublist("Problem").get("Phase Field Energy Objective Scale",0.00064);
272 std::vector<ROL::Ptr<ROL::Objective<RealT>>> obj_vec(1,ROL::nullPtr);
273 obj_vec[0] = obj_pfe;
274 if (minType == "Volume") {
275 weights.push_back(parlist->sublist("Problem").get("Volume Objective Scale",0.04096));
276 obj_vec.push_back(obj_vol);
277 obj = ROL::makePtr<ROL::LinearCombinationObjective<RealT>>(weights,obj_vec);
278 icon = ROL::makePtr<ROL::ConstraintFromObjective<RealT>>(robj_com);
279 // Set upper bound to compliance for solid beam.
280 RealT comp = robj_com->value(*zp,tol);
281 ilp = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
282 iup = ROL::makePtr<ROL::SingletonVector<RealT>>(cmpFactor*comp);
283 imul = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
284 ibnd = ROL::makePtr<ROL::Bounds<RealT>>(ilp,iup);
285 }
286 else if (minType == "Compliance") {
287 weights.push_back(static_cast<RealT>(1));
288 obj_vec.push_back(robj_com);
289 obj = ROL::makePtr<ROL::LinearCombinationObjective<RealT>>(weights,obj_vec);
290 icon = con_vol;
291 imul = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
292 if (volEq) {
293 ilp = ROL::nullPtr;
294 iup = ROL::nullPtr;
295 ibnd = ROL::nullPtr;
296 }
297 else {
298 // Set upper bound to fraction of total volume.
299 ilp = ROL::makePtr<ROL::SingletonVector<RealT>>(0);
300 iup = ROL::makePtr<ROL::SingletonVector<RealT>>(volFraction*vol);
301 ibnd = ROL::makePtr<ROL::Bounds<RealT>>(ilp,iup);
302 }
303 }
304 else if (minType == "Total") {
305 weights.push_back(static_cast<RealT>(1));
306 obj_vec.push_back(robj_com);
307 weights.push_back(parlist->sublist("Problem").get("Volume Objective Scale",0.04096));
308 obj_vec.push_back(obj_vol);
309 obj = ROL::makePtr<ROL::LinearCombinationObjective<RealT>>(weights,obj_vec);
310 icon = ROL::nullPtr;
311 ilp = ROL::nullPtr;
312 iup = ROL::nullPtr;
313 imul = ROL::nullPtr;
314 ibnd = ROL::nullPtr;
315 }
316 else {
317 throw ROL::Exception::NotImplemented("Unknown minimization type!");
318 }
319 }
320
321 // Initialize bound constraints.
322 RealT lval = (usePhaseField ? -1.0 : 0.0), uval = 1.0;
323 ROL::Ptr<ROL::Vector<RealT>> lop = zp->clone(); lop->setScalar(lval);
324 ROL::Ptr<ROL::Vector<RealT>> hip = zp->clone(); hip->setScalar(uval);
325 ROL::Ptr<ROL::BoundConstraint<RealT>>
326 bnd = ROL::makePtr<ROL::Bounds<RealT>>(lop,hip);
327 if (usePhaseField) bnd->deactivate();
328
329 // Build sampler.
330 BuildSampler<RealT> buildSampler(parlist->sublist("Problem"),probDim,example);
331 //int stochDim = buildSampler.getDimension();
332 int nsamp = parlist->sublist("Problem").get("Number of samples", 1);
333 ROL::Ptr<ROL::BatchManager<RealT>>
334 bman = ROL::makePtr<ROL::TpetraTeuchosBatchManager<RealT>>(comm);
335 ROL::Ptr<ROL::SampleGenerator<RealT>>
336 sampler = buildSampler.get(nsamp,bman);
337
338 // Set up optimization problem.
339 ROL::Ptr<ROL::StochasticProblem<RealT>>
340 prob = ROL::makePtr<ROL::StochasticProblem<RealT>>(obj,zp);
341 if (bnd->isActivated()) prob->addBoundConstraint(bnd);
342 if ( minType == "Compliance" ) {
343 if ( volEq ) prob->addLinearConstraint("Volume",icon,imul);
344 else prob->addLinearConstraint("Volume",icon,imul,ibnd);
345 }
346 else if ( minType == "Volume" )
347 prob->addConstraint("Compliance",icon,imul,ibnd);
348 if ( minType == "Volume" ) {
349 ROL::Ptr<ROL::BatchManager<RealT>>
350 cbman = ROL::makePtr<ROL::SingletonTeuchosBatchManager<RealT,int>>(comm);
351 parlist->sublist("SOL").sublist("Compliance") = parlist->sublist("SOL");
352 prob->makeConstraintStochastic("Compliance",*parlist,sampler,cbman);
353 }
354 else {
355 parlist->sublist("SOL").sublist("Objective") = parlist->sublist("SOL");
356 prob->makeObjectiveStochastic(*parlist,sampler);
357 }
358 prob->setProjectionAlgorithm(*parlist);
359 prob->finalize(false,true,*outStream);
360
361 // Check derivatives.
362 bool derivCheck = parlist->sublist("Problem").get("Check derivatives",false);
363 if (derivCheck) prob->check(true,*outStream);
364
365 // Solve optimization problem.
366 Teuchos::Time algoTimer("Algorithm Time", true);
367 ROL::Solver<RealT> solver(prob,*parlist);
368 solver.solve(*outStream);
369 algoTimer.stop();
370 *outStream << "Total optimization time = " << algoTimer.totalElapsedTime() << " seconds.\n";
371
372 // Output.
373 if (useFilter && !usePhaseField)
374 ROL::dynamicPtrCast<TopOptFilteredComplianceObjective<RealT>>(robj_com)->summarize(*outStream);
375 else
376 ROL::dynamicPtrCast<TopOptComplianceObjective<RealT>>(robj_com)->summarize(*outStream);
377 if (minType == "Compliance") con_vol->summarize(*outStream);
378 else obj_vol->summarize(*outStream);
379 assembler->printMeshData(*outStream);
380 up->zero(); pp->zero();
381 for (int i = 0; i < sampler->numMySamples(); ++i) {
382 robj_com->setParameter(sampler->getMyPoint(i));
383 if (useFilter && !usePhaseField)
384 ROL::dynamicPtrCast<TopOptFilteredComplianceObjective<RealT>>(robj_com)->solveState(*up,*zp);
385 else
386 ROL::dynamicPtrCast<TopOptComplianceObjective<RealT>>(robj_com)->solveState(*up,*zp);
387 pp->axpy(sampler->getMyWeight(i),*up);
388 }
389 sampler->sumAll(*pp,*up);
390 assembler->outputTpetraVector(u_ptr,"mean_state.txt");
391 assembler->outputTpetraVector(z_ptr,"density.txt");
392 int nsamp_dist = parlist->sublist("Problem").get("Number of output samples",1000);
393 ROL::Ptr<ROL::SampleGenerator<RealT>>
394 sampler_dist = buildSampler.get(nsamp_dist,bman);
395 if (minType != "Volume")
396 TopOptPrintCDF<RealT>(*obj,*zp,*sampler_dist,nsamp_dist,comm,"obj_samples.txt");
397 else
398 TopOptPrintCDF<RealT>(*robj_com,*zp,*sampler_dist,nsamp_dist,comm,"obj_samples.txt");
399
400 // Get a summary from the time monitor.
401 Teuchos::TimeMonitor::summarize();
402 }
403 catch (std::logic_error& err) {
404 *outStream << err.what() << "\n";
405 errorFlag = -1000;
406 }; // end try
407
408 if (errorFlag != 0)
409 std::cout << "End Result: TEST FAILED\n";
410 else
411 std::cout << "End Result: TEST PASSED\n";
412
413 return 0;
414 }