ROL
example_05.cpp
Go to the documentation of this file.
1 // @HEADER
2 // ************************************************************************
3 //
4 // Rapid Optimization Library (ROL) Package
5 // Copyright (2014) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact lead developers:
38 // Drew Kouri (dpkouri@sandia.gov) and
39 // Denis Ridzal (dridzal@sandia.gov)
40 //
41 // ************************************************************************
42 // @HEADER
43 
44 #include "example_05.hpp"
45 
46 typedef double RealT;
47 
48 template<class Real>
49 Real random(const ROL::Ptr<const Teuchos::Comm<int> > &comm) {
50  Real val = 0.0;
51  if ( Teuchos::rank<int>(*comm)==0 ) {
52  val = (Real)rand()/(Real)RAND_MAX;
53  }
54  Teuchos::broadcast<int,Real>(*comm,0,1,&val);
55  return val;
56 }
57 
58 int main(int argc, char* argv[]) {
59 
60  Teuchos::GlobalMPISession mpiSession(&argc, &argv);
61  ROL::Ptr<const Teuchos::Comm<int> > comm
62  = ROL::toPtr(Teuchos::DefaultComm<int>::getComm());
63 
64  // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
65  int iprint = argc - 1;
66  ROL::Ptr<std::ostream> outStream;
67  ROL::nullstream bhs; // outputs nothing
68  if (iprint > 0 && Teuchos::rank<int>(*comm)==0)
69  outStream = ROL::makePtrFromRef(std::cout);
70  else
71  outStream = ROL::makePtrFromRef(bhs);
72 
73  int errorFlag = 0;
74 
75  try {
76  /**********************************************************************************************/
77  /************************* CONSTRUCT ROL ALGORITHM ********************************************/
78  /**********************************************************************************************/
79  // Get ROL parameterlist
80  std::string filename = "input.xml";
81  auto parlist = ROL::getParametersFromXmlFile( filename );
82  // Build ROL algorithm
83  parlist->sublist("Status Test").set("Gradient Tolerance",1.e-7);
84  parlist->sublist("Status Test").set("Step Tolerance",1.e-14);
85  parlist->sublist("Status Test").set("Iteration Limit",100);
86  /**********************************************************************************************/
87  /************************* CONSTRUCT VECTORS **************************************************/
88  /**********************************************************************************************/
89  // Build control vectors
90  int nx = 256;
91  // Construct storage for optimal solution
92  ROL::Ptr<std::vector<RealT> > z_ptr = ROL::makePtr<std::vector<RealT>>(nx+2,0);
93  ROL::Ptr<ROL::Vector<RealT> > zp = ROL::makePtr<ROL::StdVector<RealT>>(z_ptr);
94  ROL::Ptr<std::vector<RealT> > x1_ptr = ROL::makePtr<std::vector<RealT>>(nx+2,0);
95  ROL::Ptr<ROL::Vector<RealT> > x1p = ROL::makePtr<ROL::StdVector<RealT>>(x1_ptr);
96  ROL::Ptr<std::vector<RealT> > x2_ptr = ROL::makePtr<std::vector<RealT>>(nx+2,0);
97  ROL::Ptr<ROL::Vector<RealT> > x2p = ROL::makePtr<ROL::StdVector<RealT>>(x2_ptr);
98  ROL::Ptr<std::vector<RealT> > x3_ptr = ROL::makePtr<std::vector<RealT>>(nx+2,0);
99  ROL::Ptr<ROL::Vector<RealT> > x3p = ROL::makePtr<ROL::StdVector<RealT>>(x3_ptr);
100  std::vector<ROL::Ptr<ROL::Vector<RealT> > > xvec = {x1p, x2p, x3p};
101  // Create vectors for derivative check
102  ROL::Ptr<std::vector<RealT> > xr_ptr = ROL::makePtr<std::vector<RealT>>(nx+2,0);
103  ROL::StdVector<RealT> xr(xr_ptr);
104  ROL::Ptr<std::vector<RealT> > d_ptr = ROL::makePtr<std::vector<RealT>>(nx+2,0);
105  ROL::StdVector<RealT> d(d_ptr);
106  for ( int i = 0; i < nx+2; i++ ) {
107  (*xr_ptr)[i] = random<RealT>(comm);
108  (*d_ptr)[i] = random<RealT>(comm);
109  }
110  // Build state and adjoint vectors
111  ROL::Ptr<std::vector<RealT> > u_ptr = ROL::makePtr<std::vector<RealT>>(nx,1);
112  ROL::Ptr<ROL::Vector<RealT> > up = ROL::makePtr<ROL::StdVector<RealT>>(u_ptr);
113  ROL::Ptr<std::vector<RealT> > p_ptr = ROL::makePtr<std::vector<RealT>>(nx,0);
114  ROL::Ptr<ROL::Vector<RealT> > pp = ROL::makePtr<ROL::StdVector<RealT>>(p_ptr);
115  /**********************************************************************************************/
116  /************************* CONSTRUCT SOL COMPONENTS *******************************************/
117  /**********************************************************************************************/
118  // Build samplers
119  int dim = 4, nSamp = 100;
120  std::vector<RealT> tmp = {-1, 1};
121  std::vector<std::vector<RealT> > bounds(dim,tmp);
122  ROL::Ptr<ROL::BatchManager<RealT> > bman
123  = ROL::makePtr<ROL::StdTeuchosBatchManager<RealT,int>>(comm);
124  ROL::Ptr<ROL::SampleGenerator<RealT> > sampler
125  = ROL::makePtr<ROL::MonteCarloGenerator<RealT>>(nSamp,bounds,bman,false,false,100);
126  /**********************************************************************************************/
127  /************************* CONSTRUCT OBJECTIVE FUNCTION ***************************************/
128  /**********************************************************************************************/
129  // Build risk-averse objective function
130  RealT alpha = 1.e-3;
131  ROL::Ptr<ROL::Objective_SimOpt<RealT> > pobjSimOpt
132  = ROL::makePtr<Objective_BurgersControl<RealT>>(alpha,nx);
133  ROL::Ptr<ROL::Constraint_SimOpt<RealT> > pconSimOpt
134  = ROL::makePtr<Constraint_BurgersControl<RealT>>(nx);
135  pconSimOpt->setSolveParameters(*parlist);
136  ROL::Ptr<ROL::Objective<RealT> > pObj
137  = ROL::makePtr<ROL::Reduced_Objective_SimOpt<RealT>>(pobjSimOpt,pconSimOpt,up,zp,pp);
138  // Test parametrized objective functions
139  *outStream << "Check Derivatives of Parametrized Objective Function\n";
140  xvec[0]->set(xr);
141  pObj->setParameter(sampler->getMyPoint(0));
142  pObj->checkGradient(*xvec[0],d,true,*outStream);
143  pObj->checkHessVec(*xvec[0],d,true,*outStream);
144  /**********************************************************************************************/
145  /************************* SMOOTHED CVAR 1.e-2, 1.e-4, 1.e-6 **********************************/
146  /**********************************************************************************************/
147  const RealT cl(0.9), cc(1), lb(-0.5), ub(0.5);
148  const std::string ra = "Risk Averse", rm = "CVaR", dist = "Parabolic";
149  const bool storage = true;
150  RealT eps(1.e-2);
151  std::vector<RealT> stat(3,0);
152  ROL::Ptr<ROL::OptimizationProblem<RealT>> optProb;
153  ROL::Ptr<ROL::OptimizationSolver<RealT>> solver;
154  for (int i = 0; i < 3; ++i) {
155  *outStream << "\nSOLVE SMOOTHED CONDITIONAL VALUE AT RISK WITH TRUST REGION\n";
156  // Build CVaR risk measure
157  ROL::ParameterList list;
158  list.sublist("SOL").set("Stochastic Component Type",ra);
159  list.sublist("SOL").set("Store Sampled Value and Gradient",storage);
160  list.sublist("SOL").sublist("Risk Measure").set("Name",rm);
161  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Confidence Level",cl);
162  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Convex Combination Parameter",cc);
163  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Smoothing Parameter",eps);
164  list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").set("Name",dist);
165  list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").sublist(dist).set("Lower Bound",lb);
166  list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").sublist(dist).set("Upper Bound",ub);
167  // Build stochastic problem
168  if ( i==0 ) { xvec[i]->zero(); }
169  else { xvec[i]->set(*xvec[i-1]); }
170  optProb = ROL::makePtr<ROL::OptimizationProblem<RealT>>(pObj,xvec[i]);
171  RealT init_stat(1);
172  if ( i > 0 ) { init_stat = stat[i-1]; }
173  list.sublist("SOL").set("Initial Statistic",init_stat);
174  optProb->setStochasticObjective(list,sampler);
175  optProb->check(*outStream);
176  // Run ROL algorithm
177  parlist->sublist("Step").set("Type","Trust Region");
178  solver = ROL::makePtr<ROL::OptimizationSolver<RealT>>(*optProb,*parlist);
179  clock_t start = clock();
180  solver->solve(*outStream);
181  *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n";
182  // Get solution statistic
183  stat[i] = optProb->getSolutionStatistic();
184  // Update smoothing parameter
185  eps *= static_cast<RealT>(1.e-2);
186  }
187  /**********************************************************************************************/
188  /************************* NONSMOOTH PROBLEM **************************************************/
189  /**********************************************************************************************/
190  *outStream << "\nSOLVE NONSMOOTH CVAR PROBLEM WITH BUNDLE TRUST REGION\n";
191  ROL::ParameterList list;
192  list.sublist("SOL").set("Stochastic Component Type",ra);
193  list.sublist("SOL").set("Store Sampled Value and Gradient",storage);
194  list.sublist("SOL").sublist("Risk Measure").set("Name",rm);
195  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Confidence Level",cl);
196  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Convex Combination Parameter",cc);
197  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Smoothing Parameter",0.);
198  list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").set("Name","Dirac");
199  list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").sublist("Dirac").set("Location",0.);
200  // Build stochastic problem
201  zp->set(*xvec[2]);
202  optProb = ROL::makePtr<ROL::OptimizationProblem<RealT>>(pObj,zp);
203  list.sublist("SOL").set("Initial Statistic",stat[2]);
204  optProb->setStochasticObjective(list,sampler);
205  optProb->check(*outStream);
206  // Run ROL algorithm
207  parlist->sublist("Status Test").set("Iteration Limit",1000);
208  parlist->sublist("Step").sublist("Bundle").set("Epsilon Solution Tolerance",1.e-7);
209  parlist->sublist("Step").set("Type","Bundle");
210  solver = ROL::makePtr<ROL::OptimizationSolver<RealT>>(*optProb,*parlist);
211  clock_t start = clock();
212  solver->solve(*outStream);
213  *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n";
214  /**********************************************************************************************/
215  /************************* COMPUTE ERROR ******************************************************/
216  /**********************************************************************************************/
217  ROL::Ptr<ROL::Vector<RealT> > cErr = zp->clone();
218  RealT zstat = optProb->getSolutionStatistic();
219  *outStream << "\nSUMMARY:\n";
220  *outStream << " ---------------------------------------------\n";
221  *outStream << " True Value-At-Risk = " << zstat << "\n";
222  *outStream << " ---------------------------------------------\n";
223  RealT VARerror = std::abs(zstat-stat[0]);
224  cErr->set(*xvec[0]); cErr->axpy(-1.0,*zp);
225  RealT CTRLerror = cErr->norm();
226  RealT TOTerror1 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
227  *outStream << " Value-At-Risk (1.e-2) = " << stat[0] << "\n";
228  *outStream << " Value-At-Risk Error = " << VARerror << "\n";
229  *outStream << " Control Error = " << CTRLerror << "\n";
230  *outStream << " Total Error = " << TOTerror1 << "\n";
231  *outStream << " ---------------------------------------------\n";
232  VARerror = std::abs(zstat-stat[1]);
233  cErr->set(*xvec[1]); cErr->axpy(-1.0,*zp);
234  CTRLerror = cErr->norm();
235  RealT TOTerror2 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
236  *outStream << " Value-At-Risk (1.e-4) = " << stat[1] << "\n";
237  *outStream << " Value-At-Risk Error = " << VARerror << "\n";
238  *outStream << " Control Error = " << CTRLerror << "\n";
239  *outStream << " Total Error = " << TOTerror2 << "\n";
240  *outStream << " ---------------------------------------------\n";
241  VARerror = std::abs(zstat-stat[2]);
242  cErr->set(*xvec[2]); cErr->axpy(-1.0,*zp);
243  CTRLerror = cErr->norm();
244  RealT TOTerror3 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
245  *outStream << " Value-At-Risk (1.e-6) = " << stat[2] << "\n";
246  *outStream << " Value-At-Risk Error = " << VARerror << "\n";
247  *outStream << " Control Error = " << CTRLerror << "\n";
248  *outStream << " Total Error = " << TOTerror3 << "\n";
249  *outStream << " ---------------------------------------------\n\n";
250  // Comparison
251  errorFlag += ((TOTerror1 < 90.*TOTerror2) && (TOTerror2 < 90.*TOTerror3)) ? 1 : 0;
252 
253  // Output controls
254  std::ofstream control;
255  control.open("example04_control.txt");
256  for (int n = 0; n < nx+2; n++) {
257  control << std::scientific << std::setprecision(15)
258  << std::setw(25) << static_cast<RealT>(n)/static_cast<RealT>(nx+1)
259  << std::setw(25) << (*z_ptr)[n]
260  << std::endl;
261  }
262  control.close();
263 
264  }
265  catch (std::logic_error& err) {
266  *outStream << err.what() << "\n";
267  errorFlag = -1000;
268  }; // end try
269 
270  if (errorFlag != 0)
271  std::cout << "End Result: TEST FAILED\n";
272  else
273  std::cout << "End Result: TEST PASSED\n";
274 
275  return 0;
276 }
Provides the ROL::Vector interface for scalar values, to be used, for example, with scalar constraint...
Real random(const ROL::Ptr< const Teuchos::Comm< int > > &comm)
Definition: example_05.cpp:49
basic_nullstream< char, char_traits< char >> nullstream
Definition: ROL_Stream.hpp:72
int main(int argc, char *argv[])
constexpr auto dim