source: coliny/branches/coliny-2.0/src/exec/coliny.cpp @ 4790

Revision 4790, 11.6 KB checked in by wehart, 7 years ago (diff)

Misc change.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1/*  _________________________________________________________________________
2 *
3 *  Coliny: A Library of COLIN optimizers
4 *  Copyright (c) 2003, Sandia National Laboratories.
5 *  This software is distributed under the GNU Lesser General Public License.
6 *  For more information, see the README.html file in the top Coliny directory.
7 *  _________________________________________________________________________
8 */
9
10//
11// coliny.cpp
12//
13
14#if 1
15
16#include <colin/ColinMain.h>
17#include <coliny/Factory.h>
18
19int main(int argc, char* argv[])
20{
21return colin::colin_main(argc,argv,"coliny");
22}
23
24#else
25
26
27#include <acro_config.h>
28
29#if defined(ACRO_USING_AMPL ) && !defined(TFLOPS)
30
31//#include <utilib/ParameterList.h>
32#include <utilib/string_ops.h>
33#include <colin/OptSetup.h>
34#include <coliny/Factory.h>
35#include <colin/OptSolverUtil.h>
36
37using namespace utilib;
38using namespace coliny;
39using namespace std;
40using colin::real;
41
42#undef NO
43extern "C" {
44#include "getstub.h"
45#include "asl.h"
46};
47#undef real
48#undef getenv
49#define asl cur_ASL
50
51//
52// Global data
53//
54static char xxxvers[] = "AMPL/Coliny\0\nAMPL/Coliny 1.0 Driver Version 20040903\n";
55static char* usage_msg[] = {
56"  TODO "
57};
58static Option_Info Oinfo = {
59        "coliny", "Coliny Solver Library 1.0",
60        "coliny_options", 0, 0, 0, xxxvers,
61        usage_msg, 0, 0, 0, 0, 20040903
62        };
63
64//
65// The function that computes the objective
66//
67void test_function(BasicArray<double>& vec, colin::AppResponse_Utilib& response)
68{
69//
70// Compute the function value
71//
72fint retcd = 0;
73for (unsigned int i=0; i<n_obj; i++)
74  response.function_value(i) = objval (i, vec.data(), &retcd);
75//
76// Check for errors in the function value computation
77// 
78if (retcd != 0){
79   EXCEPTION_MNGR(std::runtime_error,"The AMPL function objval returned a nonzero error state: " << retcd << " at point " << vec)
80   }
81//
82// Compute the constraint functions
83//
84BasicArray<double> constraint(n_con); 
85fint nerror = 0;
86conval (vec.data(), constraint.data(), &nerror);
87//
88// Check for errors in the constraint value computation
89//
90if (nerror != 0) {
91   EXCEPTION_MNGR(std::runtime_error, "The AMPL function conval returned a nonzero error state: " << nerror)
92   }   
93//
94// Compute a penalized objective value
95//
96for (int i = n_conjac[0]; i < n_conjac[1]; i++) {
97  response.constraint_values()[i] = constraint[i];
98  #if 0
99  if (constraint[i] < Al[i])
100     ans += 10000.0 * (Al[i] - constraint[i]);
101  if (constraint[i] > Au[i])
102     ans += 10000.0 * (constraint[i] - Au[i]);
103  #endif
104  }
105
106for (unsigned int i=0; i<response.request_vector().size(); i++) {
107  response.request_vector()[i] &= colin::mode_f;
108  response.response_vector()[i] |= colin::mode_f;
109  }
110
111// ACRO_VALIDATING I/O
112//cout << "COLINY.cpp\n" << response << endl;
113//cout << "Point: " << vec << endl;
114//cout << "Fval: " << response.function_value() << endl;
115//cout << "Cvals: " << response.constraint_values() << endl;
116
117}
118
119void init_ampl(char* stub,
120        colin::OptProblem<BasicArray<double>,colin::AppResponse_Utilib>& problem,
121        BasicArray<double>& initpt)
122{
123if (stub == NULL)
124   EXCEPTION_MNGR(std::runtime_error, "No stub passed to init_ampl()")
125//
126// Read *.nl file
127// 
128ASL*  asl = ASL_alloc(ASL_read_fg);
129FILE* nl = jac0dim(stub, (fint) strlen(stub));
130initpt.resize(n_var);
131initpt << 0.0;
132X0 = initpt.data();
133fg_read(nl,0);
134//
135// Setup lower and upper bounds on variables
136//
137BasicArray<real> vlower(n_var);
138BasicArray<real> vupper(n_var);
139for (int i=0; i<n_var; i++) {
140  if (LUv[2*i] == negInfinity)
141     vlower[i] = real::negative_infinity;
142  else
143     vlower[i] = LUv[2*i];
144  if (LUv[2*i+1] == Infinity)
145     vupper[i] = real::positive_infinity;
146  else
147     vupper[i] = LUv[2*i+1];
148  }
149//
150// Setup lower and upper bounds on constraints
151//
152BasicArray<real> clower(n_con);
153BasicArray<real> cupper(n_con);
154double* b = LUrhs;
155for ( int i = 0; i < n_con; i++, b +=2) {
156  if (b[0] == negInfinity)
157     clower[i] = real::negative_infinity;
158  else
159     clower[i] = b[0];
160  if (b[1] == Infinity)
161     cupper[i] = real::positive_infinity;
162  else
163     cupper[i] = b[1];
164  }
165ucout << "\nNumber of objectives: " << n_obj << endl;
166ucout << "Number of variables: " << n_var << endl;
167ucout << "\nVariable\tlower bound\tupper bound\n";
168for (int i=0; i< n_var; i++){
169   ucout << "  " << i << "\t\t" << vlower[i] << "\t" << vupper[i] << "\n" << Flush;
170  }
171ucout << "\nConstraint\tlower bound\tupper bound\n";
172for (int i=0; i< n_con; i++){
173   ucout << "  " << i << "\t\t" << clower[i] << "\t" << cupper[i] << "\n" << Flush;
174  }
175ucout << endl;
176//
177// Setup problem
178//
179colin::OptSetup(problem,&test_function,vlower,vupper,clower,cupper,n_obj);
180///
181/// Setup initpt
182///
183initpt.resize(vlower.size());
184for (unsigned int i=0; i<initpt.size(); i++)
185  initpt[i] = X0[i];
186//
187// TODO setup linear constraints
188//
189}
190
191
192void process_options(CharString& envstr, char* s, ParameterList& plist,
193                                                        CharString& solverstr)
194{
195   ucout << "Processing AMPL Options: " << envstr << endl;
196   //// Eliminate white space before and after '=' characters
197   int slen = strlen(s);
198   int offset=0;
199   for (int i=0; i<slen; i++) {
200     if (s[i] == '=') {
201        int j = i-1;
202        while ((j >= 0) && (s[j] == ' ')) { offset++; j--; }
203        s[i-offset] = s[i];
204        i++;
205        while ((i<slen) && (s[i] == ' ')) { offset++; i++; }
206        s[i-offset] = s[i];
207        }
208     else {
209        s[i-offset] = s[i];
210        }
211     }
212   s[slen-offset] = '\000';
213   //// Process the options
214   istringstream isstr(s);
215   string str;
216   while (isstr >> str) {
217     const char* param = str.c_str();
218     char* tmp = const_cast<char*>(param);
219     unsigned int i=0;
220     while ((i<str.size()) && (*tmp != '=')) {tmp++; i++;}
221     if (i == str.size()) {
222        ucout << "  OPTION: " << param << " true" << endl;
223        plist.add_parameter(str,"true",false);
224        }
225     else {
226        *tmp = '\000';
227        tmp++;
228        if (strcmp(param,"solver") == 0) {
229           solverstr = tmp;
230           }
231        ucout << "  OPTION: " << param << " " << tmp << endl;
232        plist.add_parameter(param,tmp,false);
233        }
234     }
235   ucout << endl;
236}
237
238
239
240int main(int argc, char* argv[])
241{
242InitializeTiming();
243double start_time = CPUSeconds();
244
245#if defined(ACRO_HAVE_MPI)
246uMPI::init(&argc,&argv,MPI_COMM_WORLD);
247
248#if 0
249int tmp;
250if (uMPI::rank == 0) {
251   cerr << "Processor 0 waiting: pid = " << getpid() << endl;
252   cin >> tmp;
253   }
254if (uMPI::rank == 1) {
255   cerr << "Processor 1 waiting: pid = " << getpid() << endl;
256   cin >> tmp;
257   }
258uMPI::barrier();
259#endif
260#endif
261
262CommonIO::begin();
263#if defined(ACRO_HAVE_MPI)
264if (uMPI::rank == 0)
265   CommonIO::end_tagging();
266#endif
267
268
269if (argc == 1) {
270   ucout << "coliny <*.nl> -AMPL" << endl;
271   CommonIO::end();
272   exit(1);
273   }
274
275try {
276utilib::exception_mngr::set_exit_function(&exit_fn);
277
278//
279// Set up the problem and initialize AMPL
280//
281string fname = argv[1];
282colin::OptProblem<BasicArray<double>,colin::AppResponse_Utilib > problem;
283BasicArray<double> initpt;
284init_ampl(const_cast<char*>(fname.c_str()), problem, initpt);
285//
286// Process solver options
287//
288getstub(&argv,&Oinfo);
289//getopts(argv,&Oinfo);
290ParameterList plist;
291BasicArray<ParameterList> plist_subsolvers;
292CharString envstr = "coliny_options";
293char* s = getenv(envstr.data());
294if (!s) {
295   envstr = "COLINY_OPTIONS";
296   s = getenv(envstr.data());
297   }
298if (s) {
299   CharString solverstr;
300   process_options(envstr,s,plist,solverstr);
301   if (solverstr != "") {
302      CharString dummy;
303      BasicArray<CharString> strarray = split(solverstr,'-');
304      strarray[0] += "_options";
305      s = getenv(strarray[0].data());
306      if (s) process_options(strarray[0], s, plist, dummy);
307      if (strarray.size() > 1) {
308        plist_subsolvers.resize(strarray.size()-1);
309        for (size_t i=1; i<strarray.size(); i++) {
310          strarray[i] += "_options";
311          s = getenv(strarray[i].data());
312          if (!s) {
313             strarray[i] = upper_case(strarray[i]);
314             s = getenv( strarray[i].data() );
315             }
316          if (s) process_options(strarray[i], s, plist_subsolvers[i-1], dummy);
317          }
318        }
319      }
320   }
321//
322//
323//
324bool   use_abort=false;
325bool   verbose=false;
326bool   debug_solver_params=false;
327string solver_str="unknown";
328int    repetitions=0;
329
330utilib::ParameterSet params;
331params.create_parameter("verbose",verbose,
332        "<bool>","false","TODO");
333params.create_parameter("debug-solver-params",debug_solver_params,
334        "<bool>","false",
335        "If true, print solver parameters");
336params.create_parameter("solver",solver_str,
337        "<string>","ps",
338        "The name of the Coliny solver");
339params.create_parameter("repetitions",repetitions,
340        "<int>","0",
341        "The number of times that the solver is run (to check that solver reset() methods work).");
342/*
343params.create_parameter("param-file",paramfile,
344        "<string>","",
345        "The name of the file of parameter values");
346*/
347params.create_parameter("use-abort",use_abort,
348        "<bool>","false","If true, then force an abort when an error occurs.");
349
350params.set_parameters(plist,false);
351string paramfile;
352params.get_parameter<string>("param-file",paramfile);
353if (use_abort)
354    utilib::exception_mngr::set_mode(utilib::exception_mngr::Abort);
355if (solver_str == "unknown") {
356   EXCEPTION_MNGR(runtime_error, "ERROR: option 'solver' not specified");
357   CommonIO::end();
358   exit(1);
359   }
360
361CharString tmp;
362tmp += "cp ";
363tmp += fname.c_str();
364tmp += ".nl dummy.nl";
365system(tmp.data());
366
367
368//
369// Setup the solver
370// Other names for solvers: direct, ms, ms.ps, ms.sw, sw, eareal, apps
371//
372colin::OptSolverHandle<BasicArray<double>,colin::AppResponse_Utilib> solver = coliny::Factory<BasicArray<double>,colin::AppResponse_Utilib>(solver_str.c_str());
373
374if (paramfile != "") {
375   ifstream ifstr;
376   ifstr.open(paramfile.c_str());
377   if (ifstr)
378      solver->read_parameter_values(ifstr);
379   }
380solver->set_parameters(plist);
381solver->set_subsolver_parameters(plist_subsolvers);
382
383if (params.get_parameter<bool>("help")) {
384   //solver->initialize("help");
385   solver->help_parameters(ucout);
386   CommonIO::end();
387   exit(1);
388   }
389//
390// Minimize and generate summary statistics about the optimizer
391//
392BasicArray<double> best_point;
393real best_value;
394if (initpt.size() > 0)
395   colin::solve(solver, problem, initpt, -1, verbose, debug_solver_params, best_point, best_value);
396else
397   colin::solve(solver, problem, -1, verbose, debug_solver_params, best_point, best_value);
398ucout << "Total-Time: " << (CPUSeconds()- start_time) << endl;
399ucout << Flush;
400
401for (int i=0; i<repetitions; i++) {
402  real tmp_best_value;
403  BasicArray<double> tmp_best_point;
404  problem.reset_neval();
405  if (initpt.size() > 0)
406     colin::solve(solver, problem, initpt, -1, verbose, debug_solver_params, tmp_best_point, tmp_best_value);
407  else
408     colin::solve(solver, problem, -1, verbose, debug_solver_params, tmp_best_point, tmp_best_value);
409  if (fabs(tmp_best_value - best_value) > 1e-6) {
410     ucout << "Repetition-Check: Fail" << endl;
411     EXCEPTION_MNGR(std::runtime_error, "Value in repetition " << i << " is different: orig=" << best_value << " rep=" << tmp_best_value)
412     }
413  for (unsigned int i=0; i<best_point.size(); i++) {
414    if (std::fabs(tmp_best_point[i] - best_point[i]) > 1e-6) {
415       ucout << "Repetition-Check: Fail" << endl;
416       EXCEPTION_MNGR(std::runtime_error, "Point in repetition " << i << " is different: orig=" << best_point << " rep=" << tmp_best_point)
417       }
418    }
419  }
420if (repetitions > 0)
421   ucout << "Repetition-Check: Pass" << endl;
422CharString msg;
423msg += "Coliny Solver: ";
424msg += solver_str;
425msg += "  final f = ";
426msg += best_value;
427need_nl = 0;
428write_sol(msg.data(), best_point.data(), NULL, NULL);
429}
430
431catch (std::exception& err) {
432  cerr << "Caught STL exception: " << err.what() << endl;
433  }
434
435catch (const char* err) {
436  cerr << "Caught string exception: " << err << endl;
437  }
438
439ucout << Flush;
440CommonIO::end();
441
442#if defined(ACRO_HAVE_MPI)
443uMPI::done();
444#endif
445return 0;
446}
447
448
449#else
450
451int main()
452{
453        std::cout << "Doing nothing!" << std::endl;
454        return -1;
455}
456
457#endif
458
459#endif
Note: See TracBrowser for help on using the repository browser.