scip-sys 0.1.21

Bindings for the C SCIP solver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*               This file is part of the program and library                */
/*    PaPILO --- Parallel Presolve for Integer and Linear Optimization       */
/*                                                                           */
/* Copyright (C) 2020-2022 Konrad-Zuse-Zentrum                               */
/*                     fuer Informationstechnik Berlin                       */
/*                                                                           */
/* This program is free software: you can redistribute it and/or modify      */
/* it under the terms of the GNU Lesser General Public License as published  */
/* by the Free Software Foundation, either version 3 of the License, or      */
/* (at your option) any later version.                                       */
/*                                                                           */
/* This program is distributed in the hope that it will be useful,           */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of            */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             */
/* GNU Lesser General Public License for more details.                       */
/*                                                                           */
/* You should have received a copy of the GNU Lesser General Public License  */
/* along with this program.  If not, see <https://www.gnu.org/licenses/>.    */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#ifndef _PAPILO_MISC_WRAPPERS_HPP_
#define _PAPILO_MISC_WRAPPERS_HPP_

#include "papilo/core/Presolve.hpp"
#include "papilo/core/postsolve/Postsolve.hpp"
#include "papilo/io/MpsParser.hpp"
#include "papilo/io/MpsWriter.hpp"
#include "papilo/io/SolParser.hpp"
#include "papilo/io/SolWriter.hpp"
#include "papilo/misc/NumericalStatistics.hpp"
#include "papilo/misc/OptionsParser.hpp"
#include "papilo/misc/Validation.hpp"
#ifdef PAPILO_TBB
#include "papilo/misc/tbb.hpp"
#else
#include <chrono>
#endif

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <string>
#include <utility>

namespace papilo
{

enum class ResultStatus
{
   kOk = 0,
   kUnbndOrInfeas,
   kError
};

template <typename REAL>
ResultStatus
presolve_and_solve(
    const OptionsInfo& opts,
    std::unique_ptr<SolverFactory<REAL>> lpSolverFactory = nullptr,
    std::unique_ptr<SolverFactory<REAL>> mipSolverFactory = nullptr )
{
   try
   {
      double readtime = 0;
      Problem<REAL> problem;
      boost::optional<Problem<REAL>> prob;

      {
         Timer t( readtime );
         prob = MpsParser<REAL>::loadProblem( opts.instance_file );
      }

      // Check whether reading was successful or not
      if( !prob )
      {
         fmt::print( "error loading problem {}\n", opts.instance_file );
         return ResultStatus::kError;
      }
      problem = *prob;

      fmt::print( "reading took {:.3} seconds\n", readtime );

      NumericalStatistics<REAL> nstats( problem );
      nstats.printStatistics();

      Presolve<REAL> presolve;
      presolve.addDefaultPresolvers();
      presolve.getPresolveOptions().threads = std::max( 0, opts.nthreads );

      if( !opts.param_settings_file.empty() || !opts.unparsed_options.empty() ||
          opts.print_params )
      {
         ParameterSet paramSet = presolve.getParameters();
         if(lpSolverFactory != nullptr)
            lpSolverFactory->add_parameters(paramSet);
         if(mipSolverFactory != nullptr)
            mipSolverFactory->add_parameters(paramSet);

         if( !opts.param_settings_file.empty() && !opts.print_params )
         {
            std::ifstream input( opts.param_settings_file );
            if( input )
            {
               String theoptionstr;
               String thevaluestr;
               for( String line; getline( input, line ); )
               {
                  std::size_t pos = line.find_first_of( '#' );
                  if( pos != String::npos )
                     line = line.substr( 0, pos );

                  pos = line.find_first_of( '=' );

                  if( pos == String::npos )
                     continue;

                  theoptionstr = line.substr( 0, pos - 1 );
                  thevaluestr = line.substr( pos + 1 );

                  boost::algorithm::trim( theoptionstr );
                  boost::algorithm::trim( thevaluestr );

                  try
                  {
                     paramSet.parseParameter( theoptionstr.c_str(),
                                              thevaluestr.c_str() );
                     fmt::print( "set {} = {}\n", theoptionstr, thevaluestr );
                  }
                  catch( const std::exception& e )
                  {
                     fmt::print( "parameter '{}' could not be set: {}\n", line,
                                 e.what() );
                  }
               }
            }
            else
            {
               fmt::print( "could not read parameter file '{}'\n",
                           opts.param_settings_file );
            }
         }

         if( !opts.unparsed_options.empty() )
         {
            String theoptionstr;
            String thevaluestr;

            for( const auto& option : opts.unparsed_options )
            {
               std::size_t pos = option.find_first_of( '=' );
               if( pos != String::npos && pos > 2 )
               {
                  theoptionstr = option.substr( 2, pos - 2 );
                  thevaluestr = option.substr( pos + 1 );
                  try
                  {
                     paramSet.parseParameter( theoptionstr.c_str(),
                                              thevaluestr.c_str() );
                     fmt::print( "set {} = {}\n", theoptionstr, thevaluestr );
                  }
                  catch( const std::exception& e )
                  {
                     fmt::print( "parameter '{}' could not be set: {}\n",
                                 option, e.what() );
                  }
               }
               else
               {
                  fmt::print(
                      "parameter '{}' could not be set: value expected\n",
                      option );
               }
            }
         }

         if( opts.print_params )
         {
            if( !opts.param_settings_file.empty() )
            {
               std::ofstream outfile( opts.param_settings_file );

               if( outfile )
               {
                  std::ostream_iterator<char> out_it( outfile );
                  paramSet.printParams( out_it );
               }
               else
               {
                  fmt::print( "could not write to parameter file '{}'\n",
                              opts.param_settings_file );
               }
            }
            else
            {
               String paramDesc;
               paramSet.printParams( std::back_inserter( paramDesc ) );
               puts( paramDesc.c_str() );
            }
         }
      }

      presolve.setLPSolverFactory( std::move( lpSolverFactory ) );
      presolve.setMIPSolverFactory( std::move( mipSolverFactory ) );

      presolve.getPresolveOptions().tlim =
          std::min( opts.tlim, presolve.getPresolveOptions().tlim );

      bool store_dual_postsolve = false;
      std::unique_ptr<SolverInterface<REAL>> solver;
      if(opts.command == Command::kSolve)
      {
         if( problem.getNumIntegralCols() == 0 &&
             presolve.getLPSolverFactory() )
         {
            solver = presolve.getLPSolverFactory()->newSolver(
                presolve.getVerbosityLevel() );
            store_dual_postsolve = solver->is_dual_solution_available();
         }
         else if( presolve.getMIPSolverFactory() )
            solver = presolve.getMIPSolverFactory()->newSolver(
                presolve.getVerbosityLevel() );
         else
         {
            fmt::print( "no solver available for solving; aborting\n" );
            return ResultStatus::kError;
         }
      }

      auto result = presolve.apply( problem, store_dual_postsolve );

      if( !opts.optimal_solution_file.empty() )
      {
         if( presolve.getPresolveOptions().dualreds != 0 )
         {
            fmt::print( "**WARNING: Enabling dual reductions might cut of "
                        "feasible or optimal solution\n" );
         }
         Validation<REAL>::validateProblem( problem, result.postsolve,
                                            opts.optimal_solution_file,
                                            result.status );
      }

      switch( result.status )
      {
      case PresolveStatus::kInfeasible:
         fmt::print(
             "presolving detected infeasible problem after {:.3f} seconds\n",
             presolve.getStatistics().presolvetime );
         return ResultStatus::kUnbndOrInfeas;
      case PresolveStatus::kUnbndOrInfeas:
         fmt::print(
             "presolving detected unbounded or infeasible problem after "
             "{:.3f} seconds\n",
             presolve.getStatistics().presolvetime );
         return ResultStatus::kUnbndOrInfeas;
      case PresolveStatus::kUnbounded:
         fmt::print(
             "presolving detected unbounded problem after {:.3f} seconds\n",
             presolve.getStatistics().presolvetime );
         return ResultStatus::kUnbndOrInfeas;
      case PresolveStatus::kUnchanged:
      case PresolveStatus::kReduced:
         break;
      }

      fmt::print( "\npresolving finished after {:.3f} seconds\n\n",
                  presolve.getStatistics().presolvetime );

      double writetime = 0;
      if( !opts.reduced_problem_file.empty() )
      {
         Timer t( writetime );

         MpsWriter<REAL>::writeProb( opts.reduced_problem_file, problem,
                                     result.postsolve.origrow_mapping,
                                     result.postsolve.origcol_mapping );

         fmt::print( "reduced problem written to {} in {:.3f} seconds\n\n",
                     opts.reduced_problem_file, t.getTime() );
      }

      if( !opts.postsolve_archive_file.empty() )
      {

         Timer t( writetime );
         std::ofstream ofs( opts.postsolve_archive_file,
                            std::ios_base::binary );
         boost::archive::binary_oarchive oa( ofs );

         // write class instance to archive
         oa << result.postsolve;
         fmt::print( "postsolve archive written to {} in {:.3f} seconds\n\n",
                     opts.postsolve_archive_file, t.getTime() );
      }

      if( opts.command == Command::kPresolve )
         return ResultStatus::kOk;

      double solvetime = 0;
      {
         Timer t( solvetime );

         solver->setUp( problem, result.postsolve.origrow_mapping,
                        result.postsolve.origcol_mapping );

         if( opts.tlim != std::numeric_limits<double>::max() )
         {
            double tlim =
                opts.tlim - presolve.getStatistics().presolvetime - writetime;
            if( tlim <= 0 )
            {
               fmt::print( "time limit reached in presolving\n" );
               return ResultStatus::kOk;
            }
            solver->setTimeLimit( tlim );
         }

         solver->solve();

         SolverStatus status = solver->getStatus();

         if( opts.print_stats )
            solver->printDetails();

         Solution<REAL> solution;
         solution.type = SolutionType::kPrimal;

         if( result.postsolve.getOriginalProblem().getNumIntegralCols() == 0 &&
             store_dual_postsolve )
            solution.type = SolutionType::kPrimalDual;

         if( ( status == SolverStatus::kOptimal ||
               status == SolverStatus::kInterrupted ) &&
             solver->getSolution( solution ) )
            postsolve( result.postsolve, solution, opts.objective_reference,
                       opts.orig_solution_file, opts.orig_dual_solution_file,
                       opts.orig_reduced_costs_file, opts.orig_basis_file );

         if( status == SolverStatus::kInfeasible )
            fmt::print(
                "\nsolving detected infeasible problem after {:.3f} seconds\n",
                presolve.getStatistics().presolvetime + solvetime + writetime );
         else if( status == SolverStatus::kUnbounded )
            fmt::print(
                "\nsolving detected unbounded problem after {:.3f} seconds\n",
                presolve.getStatistics().presolvetime + solvetime + writetime );
         else if( status == SolverStatus::kUnbndOrInfeas )
            fmt::print(
                "\nsolving detected unbounded or infeasible problem after "
                "{:.3f} seconds\n",
                presolve.getStatistics().presolvetime + solvetime + writetime );
         else
            fmt::print( "\nsolving finished after {:.3f} seconds\n",
                        presolve.getStatistics().presolvetime + solvetime +
                            writetime );
      }
   }
   catch( std::bad_alloc& ex )
   {
      fmt::print( "Memory out exception occured! Please assign more memory\n" );
      return ResultStatus::kError;
   }

   return ResultStatus::kOk;
}

template <typename REAL>
void
postsolve( PostsolveStorage<REAL>& postsolveStorage,
           const Solution<REAL>& reduced_sol,
           const std::string& objective_reference = "",
           const std::string& primal_solution_output = "",
           const std::string& dual_solution_output = "",
           const std::string& reduced_solution_output = "",
           const std::string& basis_output = "" )
{
   Solution<REAL> original_sol;

#ifdef PAPILO_TBB
   auto t0 = tbb::tick_count::now();
#else
   auto t0 = std::chrono::steady_clock::now();
#endif
   const Message msg{};
   Postsolve<REAL> postsolve{ msg, postsolveStorage.getNum() };
   PostsolveStatus status =
       postsolve.undo( reduced_sol, original_sol, postsolveStorage );
#ifdef PAPILO_TBB
   auto t1 = tbb::tick_count::now();
   double sec1 = ( t1 - t0 ).seconds();
#else
   auto t1 = std::chrono::steady_clock::now();
   double sec1 =
       std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 )
           .count() /
       1000;
#endif
   fmt::print( "\npostsolve finished after {:.3f} seconds\n", sec1 );

   const Problem<REAL>& origprob = postsolveStorage.getOriginalProblem();
   REAL origobj = origprob.computeSolObjective( original_sol.primal );

   REAL boundviol = 0;
   REAL intviol = 0;
   REAL rowviol = 0;
   bool origfeas = origprob.computeSolViolations( postsolveStorage.getNum(),
                                                  original_sol.primal,
                                                  boundviol, rowviol, intviol );

   fmt::print( "feasible: {}\nobjective value: {:.15}\n", origfeas,
               double( origobj ) );

   fmt::print( "\nviolations:\n" );
   fmt::print( "  bounds:      {:.15}\n", double( boundviol ) );
   fmt::print( "  constraints: {:.15}\n", double( rowviol ) );
   fmt::print( "  integrality: {:.15}\n\n", double( intviol ) );

   if( !primal_solution_output.empty() )
   {
#ifdef PAPILO_TBB
      auto t2 = tbb::tick_count::now();
#else
      auto t2 = std::chrono::steady_clock::now();
#endif
      SolWriter<REAL>::writePrimalSol( primal_solution_output,
                                       original_sol.primal,
                                       origprob.getObjective().coefficients,
                                       origobj, origprob.getVariableNames() );
#ifdef PAPILO_TBB
      auto t3 = tbb::tick_count::now();
      double sec3 = ( t3 - t2 ).seconds();
#else
      auto t3 = std::chrono::steady_clock::now();
      double sec3 =
          std::chrono::duration_cast<std::chrono::milliseconds>( t3 - t2 )
              .count() /
          1000;
#endif

      fmt::print( "solution written to file {} in {:.3} seconds\n",
                  primal_solution_output, sec3 );
   }

   if( !dual_solution_output.empty() &&
       original_sol.type == SolutionType::kPrimalDual )
   {
#ifdef PAPILO_TBB
      auto t2 = tbb::tick_count::now();
#else
      auto t2 = std::chrono::steady_clock::now();
#endif
      const ConstraintMatrix<REAL>& constraintMatrix =
          origprob.getConstraintMatrix();
      SolWriter<REAL>::writeDualSol( dual_solution_output, original_sol.dual,
                                     constraintMatrix.getRightHandSides(),
                                     constraintMatrix.getLeftHandSides(),
                                     origobj, origprob.getConstraintNames() );
#ifdef PAPILO_TBB
      auto t3 = tbb::tick_count::now();
      double sec3 = ( t3 - t2 ).seconds();
#else
      auto t3 = std::chrono::steady_clock::now();
      double sec3 =
          std::chrono::duration_cast<std::chrono::milliseconds>( t3 - t2 )
              .count() /
          1000;
#endif

      fmt::print( "dual solution written to file {} in {:.3} seconds\n",
                  dual_solution_output, sec3 );
   }

   if( !reduced_solution_output.empty() &&
       original_sol.type == SolutionType::kPrimalDual )
   {
#ifdef PAPILO_TBB
      auto t2 = tbb::tick_count::now();
#else
      auto t2 = std::chrono::steady_clock::now();
#endif
      SolWriter<REAL>::writeReducedCostsSol(
          reduced_solution_output, original_sol.reducedCosts,
          origprob.getUpperBounds(), origprob.getLowerBounds(), origobj,
          origprob.getVariableNames() );
#ifdef PAPILO_TBB
      auto t3 = tbb::tick_count::now();
      double sec3 = ( t3 - t2 ).seconds();
#else
      auto t3 = std::chrono::steady_clock::now();
      double sec3 =
          std::chrono::duration_cast<std::chrono::milliseconds>( t3 - t2 )
              .count() /
          1000;
#endif

      fmt::print( "reduced solution written to file {} in {:.3} seconds\n",
                  reduced_solution_output, sec3 );
   }

   if( !basis_output.empty() && original_sol.type == SolutionType::kPrimalDual )
   {
#ifdef PAPILO_TBB
      auto t2 = tbb::tick_count::now();
#else
      auto t2 = std::chrono::steady_clock::now();
#endif

      SolWriter<REAL>::writeBasis( basis_output, original_sol.varBasisStatus,
                                   original_sol.rowBasisStatus,
                                   origprob.getVariableNames(),
                                   origprob.getConstraintNames() );
#ifdef PAPILO_TBB
      auto t3 = tbb::tick_count::now();
      double sec3 = ( t3 - t2 ).seconds();
#else
      auto t3 = std::chrono::steady_clock::now();
      double sec3 =
          std::chrono::duration_cast<std::chrono::milliseconds>( t3 - t2 )
              .count() /
          1000;
#endif
      fmt::print( "basis written to file {} in {:.3} seconds\n", basis_output,
                  sec3 );
   }

   if( !objective_reference.empty() )
   {
      if( origfeas && status == PostsolveStatus::kOk &&
          postsolveStorage.num.isFeasEq(
              boost::lexical_cast<double>( objective_reference ),
              double( origobj ) ) )
         fmt::print( "validation: SUCCESS\n" );
      else
         fmt::print( "validation: FAILURE\n" );
   }
}

template <typename REAL>
void
postsolve( const OptionsInfo& opts )
{
   PostsolveStorage<REAL> ps;
   std::ifstream inArchiveFile( opts.postsolve_archive_file,
                                std::ios_base::binary );
   boost::archive::binary_iarchive inputArchive( inArchiveFile );
   inputArchive >> ps;
   inArchiveFile.close();

   SolParser<REAL> parser;
   Solution<REAL> reduced_solution;
   bool success = parser.read( opts.reduced_solution_file, ps.origcol_mapping,
                               ps.getOriginalProblem().getVariableNames(),
                               reduced_solution );
   if( success )
      postsolve( ps, reduced_solution, opts.objective_reference,
                 opts.orig_solution_file, opts.orig_dual_solution_file,
                 opts.orig_reduced_costs_file, opts.orig_basis_file );
}

} // namespace papilo

#endif