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::Algorithm<RealT> > algo;
153  ROL::Ptr<ROL::OptimizationProblem<RealT> > optProb;
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  algo = ROL::makePtr<ROL::Algorithm<RealT>>("Trust Region",*parlist,false);
178  clock_t start = clock();
179  algo->run(*optProb,true,*outStream);
180  *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n";
181  // Get solution statistic
182  stat[i] = optProb->getSolutionStatistic();
183  // Update smoothing parameter
184  eps *= static_cast<RealT>(1.e-2);
185  }
186  /**********************************************************************************************/
187  /************************* NONSMOOTH PROBLEM **************************************************/
188  /**********************************************************************************************/
189  *outStream << "\nSOLVE NONSMOOTH CVAR PROBLEM WITH BUNDLE TRUST REGION\n";
190  ROL::ParameterList list;
191  list.sublist("SOL").set("Stochastic Component Type",ra);
192  list.sublist("SOL").set("Store Sampled Value and Gradient",storage);
193  list.sublist("SOL").sublist("Risk Measure").set("Name",rm);
194  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Confidence Level",cl);
195  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Convex Combination Parameter",cc);
196  list.sublist("SOL").sublist("Risk Measure").sublist(rm).set("Smoothing Parameter",0.);
197  list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").set("Name","Dirac");
198  list.sublist("SOL").sublist("Risk Measure").sublist(rm).sublist("Distribution").sublist("Dirac").set("Location",0.);
199  // Build stochastic problem
200  zp->set(*xvec[2]);
201  optProb = ROL::makePtr<ROL::OptimizationProblem<RealT>>(pObj,zp);
202  list.sublist("SOL").set("Initial Statistic",stat[2]);
203  optProb->setStochasticObjective(list,sampler);
204  optProb->check(*outStream);
205  // Run ROL algorithm
206  parlist->sublist("Status Test").set("Iteration Limit",1000);
207  parlist->sublist("Step").sublist("Bundle").set("Epsilon Solution Tolerance",1.e-7);
208  algo = ROL::makePtr<ROL::Algorithm<RealT>>("Bundle",*parlist,false);
209  clock_t start = clock();
210  algo->run(*optProb,true,*outStream);
211  *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n";
212  /**********************************************************************************************/
213  /************************* COMPUTE ERROR ******************************************************/
214  /**********************************************************************************************/
215  ROL::Ptr<ROL::Vector<RealT> > cErr = zp->clone();
216  RealT zstat = optProb->getSolutionStatistic();
217  *outStream << "\nSUMMARY:\n";
218  *outStream << " ---------------------------------------------\n";
219  *outStream << " True Value-At-Risk = " << zstat << "\n";
220  *outStream << " ---------------------------------------------\n";
221  RealT VARerror = std::abs(zstat-stat[0]);
222  cErr->set(*xvec[0]); cErr->axpy(-1.0,*zp);
223  RealT CTRLerror = cErr->norm();
224  RealT TOTerror1 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
225  *outStream << " Value-At-Risk (1.e-2) = " << stat[0] << "\n";
226  *outStream << " Value-At-Risk Error = " << VARerror << "\n";
227  *outStream << " Control Error = " << CTRLerror << "\n";
228  *outStream << " Total Error = " << TOTerror1 << "\n";
229  *outStream << " ---------------------------------------------\n";
230  VARerror = std::abs(zstat-stat[1]);
231  cErr->set(*xvec[1]); cErr->axpy(-1.0,*zp);
232  CTRLerror = cErr->norm();
233  RealT TOTerror2 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
234  *outStream << " Value-At-Risk (1.e-4) = " << stat[1] << "\n";
235  *outStream << " Value-At-Risk Error = " << VARerror << "\n";
236  *outStream << " Control Error = " << CTRLerror << "\n";
237  *outStream << " Total Error = " << TOTerror2 << "\n";
238  *outStream << " ---------------------------------------------\n";
239  VARerror = std::abs(zstat-stat[2]);
240  cErr->set(*xvec[2]); cErr->axpy(-1.0,*zp);
241  CTRLerror = cErr->norm();
242  RealT TOTerror3 = std::sqrt(std::pow(VARerror,2)+std::pow(CTRLerror,2));
243  *outStream << " Value-At-Risk (1.e-6) = " << stat[2] << "\n";
244  *outStream << " Value-At-Risk Error = " << VARerror << "\n";
245  *outStream << " Control Error = " << CTRLerror << "\n";
246  *outStream << " Total Error = " << TOTerror3 << "\n";
247  *outStream << " ---------------------------------------------\n\n";
248  // Comparison
249  errorFlag += ((TOTerror1 < 90.*TOTerror2) && (TOTerror2 < 90.*TOTerror3)) ? 1 : 0;
250 
251  // Output controls
252  std::ofstream control;
253  control.open("example04_control.txt");
254  for (int n = 0; n < nx+2; n++) {
255  control << std::scientific << std::setprecision(15)
256  << std::setw(25) << static_cast<RealT>(n)/static_cast<RealT>(nx+1)
257  << std::setw(25) << (*z_ptr)[n]
258  << std::endl;
259  }
260  control.close();
261 
262  }
263  catch (std::logic_error err) {
264  *outStream << err.what() << "\n";
265  errorFlag = -1000;
266  }; // end try
267 
268  if (errorFlag != 0)
269  std::cout << "End Result: TEST FAILED\n";
270  else
271  std::cout << "End Result: TEST PASSED\n";
272 
273  return 0;
274 }
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[])