Debian Codegraph @

packages/rol/example/PDE-OPT/published/TRSPG_Kouri2021/lasso/example_01.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_01.cpp
11 \brief Shows how to minimize a function with binary (0/1) constraints.
12 */
13
14 #include "ROL_Solver.hpp"
15 #include "ROL_Bounds.hpp"
16 #include "ROL_StdObjective.hpp"
17 #include "ROL_StdConstraint.hpp"
18 #include "ROL_Stream.hpp"
19 #include "ROL_LinearAlgebra.hpp"
20 #include "ROL_BLAS.hpp"
21
22 #include "Teuchos_Time.hpp"
23 #include "Teuchos_GlobalMPISession.hpp"
24 #include "Teuchos_XMLParameterListHelpers.hpp"
25
26 #include <iostream>
27 #include <fstream>
28 #include <random>
29
30 typedef double RealT;
31
32 template<class Real>
33 class LassoObjective : public ROL::StdObjective<Real> {
34 private:
35 const ROL::Ptr<ROL::BLAS<int,Real>> blas_;
36 const ROL::LA::Matrix<Real> X_;
37 const std::vector<Real> y_;
38 std::vector<Real> res_;
39 const int nrows_, ncols_;
40 const Real wt_;
41 int fval_, grad_, hess_;
42 bool computeRes_;
43
44 void computeResidual(const std::vector<Real> &x) {
45 if (computeRes_) {
46 const Real one(1);
47 std::vector<Real> d(ncols_);
48 for (int j = 0; j < ncols_; ++j) d[j] = (x[j]-x[ncols_+j]);
49 res_.assign(y_.begin(),y_.end());
50 applyK(res_,d,one,-one,false);
51 computeRes_ = false;
52 }
53 }
54
55 void applyK(std::vector<Real> &Kx, const std::vector<Real> &x, Real alpha, Real beta, bool trans) const {
56 //const Real zero(0), one(1);
57 if (trans)
58 blas_->GEMV( Teuchos::TRANS,nrows_,ncols_,alpha,X_.values(),nrows_,&x[0],1,beta,&Kx[0],1);
59 else
60 blas_->GEMV(Teuchos::NO_TRANS,nrows_,ncols_,alpha,X_.values(),nrows_,&x[0],1,beta,&Kx[0],1);
61 }
62
63 public:
64 LassoObjective(const ROL::LA::Matrix<Real> &X, const std::vector<Real> &y)
65 : blas_(ROL::makePtr<ROL::BLAS<int,Real>>()),
66 X_(X), y_(y), nrows_(X.numRows()), ncols_(X.numCols()),
67 wt_(static_cast<Real>(1)/static_cast<Real>(nrows_)),
68 fval_(0), grad_(0), hess_(0), computeRes_(true) {
69 res_.resize(nrows_);
70 }
71
72 void summarize(std::ostream &stream) const {
73 stream << std::endl;
74 stream << std::string(114,'=') << std::endl;
75 stream << " LassoObjective::summarize" << std::endl;
76 stream << " Number of calls to value: " << fval_ << std::endl;
77 stream << " Number of calls to gradient: " << grad_ << std::endl;
78 stream << " Number of calls to hessVec: " << hess_ << std::endl;
79 stream << std::string(114,'=') << std::endl;
80 stream << std::endl;
81 }
82
83 void reset(void) {
84 fval_ = 0; grad_ = 0; hess_ = 0;
85 }
86
87 void update(const std::vector<Real> &x, ROL::UpdateType type, int iter = -1) {
88 if (type != ROL::UpdateType::Revert && type != ROL::UpdateType::Accept)
89 computeRes_ = true;
90 }
91
92 Real value(const std::vector<Real> &x, Real &tol) {
93 fval_++;
94 computeResidual(x);
95 return wt_*static_cast<Real>(0.5)*blas_->DOT(nrows_,&res_[0],1,&res_[0],1);
96 }
97
98 void gradient(std::vector<Real> &g, const std::vector<Real> &x, Real &tol) {
99 grad_++;
100 const Real zero(0), one(1);
101 computeResidual(x);
102 std::vector<Real> Kr(ncols_);
103 applyK(Kr,res_,one,zero,true);
104 for (int j = 0; j < ncols_; ++j) {
105 g[j] = wt_*Kr[j];
106 g[ncols_+j] = -wt_*Kr[j];
107 }
108 }
109
110 void hessVec(std::vector<Real> &hv, const std::vector<Real> &v, const std::vector<Real> &x, Real &tol) {
111 hess_++;
112 const Real zero(0), one(1);
113 std::vector<Real> d(ncols_), res(nrows_), Kr(ncols_);
114 for (int j = 0; j < ncols_; ++j) d[j] = (v[j]-v[ncols_+j]);
115 res_.assign(y_.begin(),y_.end());
116 applyK(res,d,one,zero,false);
117 applyK(Kr,res,one,zero,true);
118 for (int j = 0; j < ncols_; ++j) {
119 hv[j] = wt_*Kr[j];
120 hv[ncols_+j] = -wt_*Kr[j];
121 }
122 }
123
124 };
125
126 template<typename Real>
127 class LassoConstraint : public ROL::StdConstraint<Real> {
128 private:
129 const Real t_;
130 const std::vector<Real> d_;
131 const int size_;
132
133 public:
134 LassoConstraint(Real t, const std::vector<Real> &d) : t_(t), d_(d), size_(d.size()) {}
135
136 void value(std::vector<Real> &c, const std::vector<Real> &x, Real &tol) {
137 c[0] = -t_;
138 for (int j = 0; j < size_; ++j) c[0] += (x[j]+x[size_+j])/d_[j];
139 }
140
141 void applyJacobian(std::vector<Real> &jv, const std::vector<Real> &v, const std::vector<Real> &x, Real &tol) {
142 jv[0] = static_cast<Real>(0);
143 for (int j = 0; j < size_; ++j) jv[0] += (v[j]+v[size_+j])/d_[j];
144 }
145
146 void applyAdjointJacobian(std::vector<Real> &ajv, const std::vector<Real> &v, const std::vector<Real> &x, Real &tol) {
147 for (int j = 0; j < size_; ++j) {
148 ajv[j] = v[0]/d_[j];
149 ajv[size_+j] = v[0]/d_[j];
150 }
151 }
152
153 void applyAdjointHessian(std::vector<Real> &ahuv, const std::vector<Real> &u, const std::vector<Real> &v, const std::vector<Real> &x, Real &tol) {
154 ahuv.assign(x.size(),static_cast<Real>(0));
155 }
156
157 };
158
159 int main(int argc, char *argv[]) {
160 Teuchos::GlobalMPISession mpiSession(&argc, &argv);
161
162 // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
163 int iprint = argc - 1;
164 ROL::Ptr<std::ostream> outStream;
165 ROL::nullstream bhs; // outputs nothing
166 if (iprint > 0)
167 outStream = ROL::makePtrFromRef(std::cout);
168 else
169 outStream = ROL::makePtrFromRef(bhs);
170
171 int errorFlag = 0;
172
173 // *** Example body.
174
175 try {
176
177 /*** Read in XML input ***/
178 std::string filename = "input.xml";
179 Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
180 Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
181
182 // Set up problem data
183 bool useRandomData = false;
184 int nfactors, nVars;
185 ROL::LA::Matrix<RealT> X;
186 std::vector<RealT> y, d;
187 if (useRandomData) {
188 unsigned seed = 111;
189 nfactors = 500000;
190 nVars = 500;
191 X.reshape(nfactors,nVars);
192 y.resize(nfactors,0.0);
193 d.resize(nVars,1.0);
194 std::default_random_engine generator(seed);
195 std::normal_distribution<RealT> dist(0.0,1.0);
196 for (int i = 0; i < nfactors; ++i) {
197 for (int j = 0; j < nVars; ++j) X(i,j) = dist(generator);
198 }
199 std::vector<RealT> w(nVars);
200 for (int j = 0; j < nVars; ++j) {
201 RealT u = static_cast<RealT>(rand())/static_cast<RealT>(RAND_MAX);
202 w[j] = (u > static_cast<RealT>(0.5) ? dist(generator) : static_cast<RealT>(0));
203 }
204 for (int i = 0; i < nfactors; ++i) {
205 y[i] = dist(generator);
206 for (int j = 0; j < nVars; ++j) y[i] += X(i,j)*w[j];
207 }
208 }
209 else {
210 nfactors = 20640;
211 nVars = 9;
212 X.reshape(nfactors,nVars);
213 y.resize(nfactors,0.0);
214 d.resize(nVars,0.0);
215 std::ifstream file;
216 file.open("lasso-data.txt");
217 RealT medVal(0), medInc(0), medAge(0), totRoom(0), totBed(0), pop(0), house(0), lon(0), lat(0);
218 for (int i = 0; i < nfactors; ++i) {
219 file >> medVal;
220 file >> medInc;
221 file >> medAge;
222 file >> totRoom;
223 file >> totBed;
224 file >> pop;
225 file >> house;
226 file >> lon;
227 file >> lat;
228 y[i] = std::log(medVal);
229 X(i,0) = static_cast<RealT>(1);
230 X(i,1) = medInc;
231 X(i,2) = std::pow(medInc,2);
232 X(i,3) = std::pow(medInc,3);
233 X(i,4) = std::log(medAge);
234 X(i,5) = std::log(totRoom)-std::log(pop);
235 X(i,6) = std::log(totBed)-std::log(pop);
236 X(i,7) = std::log(pop)-std::log(house);
237 X(i,8) = std::log(house);
238 for (int j = 0; j < nVars; ++j) d[j] = std::max(std::abs(X(i,j)),d[j]);
239 }
240 file.close();
241 for (int i = 0; i < nfactors; ++i) {
242 for (int j = 0; j < nVars; ++j) X(i,j) /= d[j];
243 }
244 }
245
246 RealT alpha(1);
247 ROL::Ptr<LassoObjective<RealT>> obj = ROL::makePtr<LassoObjective<RealT>>(X,y);
248 ROL::Ptr<LassoConstraint<RealT>> con = ROL::makePtr<LassoConstraint<RealT>>(alpha,d);
249 ROL::Ptr<ROL::StdVector<RealT>> mul = ROL::makePtr<ROL::StdVector<RealT>>(1,0);
250 ROL::Ptr<ROL::StdVector<RealT>> res = ROL::makePtr<ROL::StdVector<RealT>>(1,0);
251 ROL::Ptr<ROL::StdVector<RealT>> u = ROL::makePtr<ROL::StdVector<RealT>>(1,0);
252 ROL::Ptr<ROL::Bounds<RealT>> ibnd = ROL::makePtr<ROL::Bounds<RealT>>(*u,false);
253 ROL::Ptr<ROL::StdVector<RealT>> x = ROL::makePtr<ROL::StdVector<RealT>>(2*nVars,0);
254 ROL::Ptr<ROL::StdVector<RealT>> l = ROL::makePtr<ROL::StdVector<RealT>>(2*nVars,0);
255 ROL::Ptr<ROL::Bounds<RealT>> bnd = ROL::makePtr<ROL::Bounds<RealT>>(*l,true);
256 ROL::Ptr<ROL::Problem<RealT>> prob = ROL::makePtr<ROL::Problem<RealT>>(obj,x);
257 prob->addBoundConstraint(bnd);
258 prob->addLinearConstraint("L1",con,mul,ibnd,res);
259 prob->setProjectionAlgorithm(*parlist);
260 prob->finalize(false,true,*outStream);
261 prob->check(true,*outStream);
262
263 ROL::Ptr<ROL::Solver<RealT>> solver;
264 std::vector<RealT> vals(6);
265
266 // SPG
267 obj->reset();
268 x->zero();
269 prob->edit();
270 prob->finalize(false,true,*outStream);
271 parlist->sublist("Step").set("Type","Spectral Gradient");
272 Teuchos::Time spgTimer("SPG Time", true);
273 solver = ROL::makePtr<ROL::Solver<RealT>>(prob,*parlist);
274 solver->solve(*outStream);
275 spgTimer.stop();
276 *outStream << "Total optimization time = " << spgTimer.totalElapsedTime() << " seconds.\n";
277 obj->summarize(*outStream);
278 vals[0] = solver->getAlgorithmState()->value;
279
280 // PQN
281 obj->reset();
282 x->zero();
283 prob->edit();
284 prob->finalize(false,true,*outStream);
285 parlist->sublist("Step").set("Type","Line Search");
286 parlist->sublist("Step").sublist("Line Search").sublist("Descent Method").set("Type","Quasi-Newton Method");
287 Teuchos::Time pqnTimer("PQN Time", true);
288 solver = ROL::makePtr<ROL::Solver<RealT>>(prob,*parlist);
289 solver->solve(*outStream);
290 pqnTimer.stop();
291 *outStream << "Total optimization time = " << pqnTimer.totalElapsedTime() << " seconds.\n";
292 obj->summarize(*outStream);
293 vals[1] = solver->getAlgorithmState()->value;
294
295 // LMTR
296 obj->reset();
297 x->zero();
298 prob->edit();
299 prob->finalize(false,true,*outStream);
300 parlist->sublist("Step").set("Type","Trust Region");
301 parlist->sublist("Step").sublist("Trust Region").set("Subproblem Model","Lin-More");
302 Teuchos::Time lmtrTimer("LMTR Time", true);
303 solver = ROL::makePtr<ROL::Solver<RealT>>(prob,*parlist);
304 solver->solve(*outStream);
305 lmtrTimer.stop();
306 *outStream << "Total optimization time = " << lmtrTimer.totalElapsedTime() << " seconds.\n";
307 obj->summarize(*outStream);
308 vals[2] = solver->getAlgorithmState()->value;
309
310 // TRSPG
311 obj->reset();
312 x->zero();
313 prob->edit();
314 prob->finalize(false,true,*outStream);
315 parlist->sublist("Step").set("Type","Trust Region");
316 parlist->sublist("Step").sublist("Trust Region").set("Subproblem Model","SPG");
317 Teuchos::Time trspgTimer("TRSPG Time", true);
318 solver = ROL::makePtr<ROL::Solver<RealT>>(prob,*parlist);
319 solver->solve(*outStream);
320 trspgTimer.stop();
321 *outStream << "Total optimization time = " << trspgTimer.totalElapsedTime() << " seconds.\n";
322 obj->summarize(*outStream);
323 vals[3] = solver->getAlgorithmState()->value;
324
325 // AL-LMTR
326 obj->reset();
327 x->zero();
328 mul->zero();
329 prob->edit();
330 prob->finalize(true,true,*outStream);
331 parlist->sublist("Step").set("Type","Augmented Lagrangian");
332 parlist->sublist("Step").sublist("Augmented Lagrangian").set("Subproblem Step Type","Trust Region");
333 parlist->sublist("Step").sublist("Trust Region").set("Subproblem Model","Lin-More");
334 Teuchos::Time allmtrTimer("AL-LMTR Time", true);
335 solver = ROL::makePtr<ROL::Solver<RealT>>(prob,*parlist);
336 solver->solve(*outStream);
337 allmtrTimer.stop();
338 *outStream << "Total optimization time = " << allmtrTimer.totalElapsedTime() << " seconds.\n";
339 obj->summarize(*outStream);
340 vals[4] = solver->getAlgorithmState()->value;
341
342 // AL-TRSPG
343 obj->reset();
344 x->zero();
345 mul->zero();
346 prob->edit();
347 prob->finalize(true,true,*outStream);
348 parlist->sublist("Step").set("Type","Augmented Lagrangian");
349 parlist->sublist("Step").sublist("Augmented Lagrangian").set("Subproblem Step Type","Trust Region");
350 parlist->sublist("Step").sublist("Trust Region").set("Subproblem Model","SPG");
351 Teuchos::Time altrspgTimer("AL-TRSPG Time", true);
352 solver = ROL::makePtr<ROL::Solver<RealT>>(prob,*parlist);
353 solver->solve(*outStream);
354 altrspgTimer.stop();
355 *outStream << "Total optimization time = " << altrspgTimer.totalElapsedTime() << " seconds.\n";
356 obj->summarize(*outStream);
357 vals[5] = solver->getAlgorithmState()->value;
358
359 RealT minval = std::min(vals[0],std::min(vals[1],std::min(vals[2],vals[3])));
360 *outStream << std::scientific << std::setprecision(16);
361 *outStream << "SPG " << (vals[0]-minval)/minval << std::endl;
362 *outStream << "PQN " << (vals[1]-minval)/minval << std::endl;
363 *outStream << "LMTR " << (vals[2]-minval)/minval << std::endl;
364 *outStream << "TRSPG " << (vals[3]-minval)/minval << std::endl;
365 *outStream << "AL-LMTR " << (vals[4]-minval)/minval << std::endl;
366 *outStream << "AL-TRSPG " << (vals[5]-minval)/minval << std::endl;
367 *outStream << std::endl;
368
369 }
370 catch (std::logic_error& err) {
371 *outStream << err.what() << "\n";
372 errorFlag = -1000;
373 }; // end try
374
375 if (errorFlag != 0)
376 std::cout << "End Result: TEST FAILED\n";
377 else
378 std::cout << "End Result: TEST PASSED\n";
379
380 return 0;
381
382 }
383
384