generate_nmp_bendersdecomp.cpp 18.4 KB
Newer Older
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
#include "generate_nmp_bendersdecomp.h"
#include "nmp_benders_conshdlr.h"
#include "../Maintenance_Problem.h"

#include <scip/prob.h>
#include <scip/struct_var.h>

struct SCIP_VarData_Master{
  SCIP* subproblem_lpsol;
  SCIP_VAR* edgepot_of_subproblem_lpsol;
  SCIP* subproblem_heursol;
  SCIP_VAR* edgepot_of_subproblem_heursol;
};

struct SCIP_Probdata_Subproblem{
  int epoch;
  int nepochs;
  int nedges;
  int number_of_added_cons;
};

struct SCIP_VarData_Subproblem{
  SCIP_Real capacity;
  SCIP* master;
  SCIP_VAR* decision_of_master;
};

SCIP_RETCODE del_vardata_master(SCIP* scip, SCIP_VAR* var, SCIP_VARDATA** vardata_unpec){
  std::cout << "deleting" << std::endl;
  SCIP_VarData_Master** vardata = (SCIP_VarData_Master**) vardata_unpec;
  SCIPreleaseVar((*vardata)->subproblem_lpsol, &(*vardata)->edgepot_of_subproblem_lpsol);
  SCIPreleaseVar((*vardata)->subproblem_heursol, &(*vardata)->edgepot_of_subproblem_heursol);

  SCIPfreeBlockMemory(scip, vardata);

  return SCIP_OKAY;
}

SCIP_RETCODE del_vardata_subproblem(SCIP* scip, SCIP_VAR* var, SCIP_VARDATA** vardata_unpec){
  std::cout << "deleting" << std::endl;
  SCIP_VarData_Subproblem** vardata = (SCIP_VarData_Subproblem**) vardata_unpec;
  SCIPreleaseVar((*vardata)->master, &(*vardata)->decision_of_master);

  SCIPfreeBlockMemory(scip, vardata);

  return SCIP_OKAY;
}

SCIP_RETCODE del_probdata_subproblem(SCIP* scip, SCIP_PROBDATA** probdata_unpec){
  std::cout << "deleting" << std::endl;
  SCIP_Probdata_Subproblem** probdata = (SCIP_Probdata_Subproblem**) probdata_unpec;
  SCIPfreeBlockMemory(scip, probdata);

  return SCIP_OKAY;
}

std::pair<
  Linear_Program,
  std::pair<
    std::map<
      std::pair<Node*,std::string>,
      std::pair<Variable*, size_t>
    >,
    std::map<
      std::pair<Edge*,std::string>,
      std::pair<Variable*, size_t>
    >
  >
> generate_dual_flow_problem(Graph& graph, Node* source, Node* target){
  Linear_Program lp(false);

  assert(graph.nodes().find(source) != graph.nodes().end());
  assert(graph.nodes().find(target) != graph.nodes().end());

  for(std::string attr : std::vector({"Upper", "Flow"})){
    if(!graph.edge_template(attr).first) {
      std::cout << graph << std::endl;
      throw std::invalid_argument("generate_dual_flow_problem needs Graph with predetermined attributes present");
    }
  }


  std::pair<
    std::map<
      std::pair<Node*,std::string>,
      std::pair<Variable*, size_t>
    >,
    std::map<
      std::pair<Edge*,std::string>,
      std::pair<Variable*, size_t>
    >
  > lookup;

  /*
    constraints
  */
  lookup = lp_generator::grow_from_graph(
    lp,
    graph,
    [](Edge* edge) -> std::vector<constraint_data> {
      std::stringstream capacity_name;
      capacity_name << "edge_" << edge->description();

      std::vector<constraint_data> constraints;
      constraints.push_back({capacity_name.str(), Inequality, {{{{edge->from(), "Nodepotential"}, -1}, {{edge->to(), "Nodepotential"}, 1}}, {{{edge, "Edgepotential"}, -1}}}, 0});

      return constraints;
    },
    [source, target](Node* node) -> std::vector<constraint_data> {

      std::vector<constraint_data> constraints;
      if(node == source){
        constraints.push_back({"set_source_potential", Equality, {{{{source, "Nodepotential"}, 1}}, {} }, -1});
      }else if(node == target){
        constraints.push_back({"set_target_potential", Equality, {{{{target, "Nodepotential"}, 1}}, {} }, 0});
      }
      return constraints;
    },
    {{"Edgepotential", {Continuous, {true, 0}, {false, 1}}}},
    {{"Nodepotential", {Continuous, {false, 0}, {false, 0}}}},
    ""
  );

  return {lp, lookup};
}

std::pair<
  Linear_Program,
  std::vector<
    std::pair<
      std::map<
        std::pair<Node*,std::string>,
        std::pair<Variable*, size_t>
      >,
      std::map<
        std::pair<Edge*,std::string>,
        std::pair<Variable*, size_t>
      >
    >
  >
> generate_master(Maintenance_Problem& nmp, Graph& graph, Node* source, Node* target){
  Linear_Program lp(true);

  std::set<Edge*> critical = graph.gather_edges({"Selected"});

  for(std::string attr : std::vector({"Selected", "Upper", "Flow"})){
    if(!graph.edge_template(attr).first) {
      std::cout << graph << std::endl;
      throw std::invalid_argument("Maintenance_Problem needs Graph with predetermined attributes present");
    }
  }


  std::vector<
    std::pair<
      std::map<
        std::pair<Node*,std::string>,
        std::pair<Variable*, size_t>
      >,
      std::map<
        std::pair<Edge*,std::string>,
        std::pair<Variable*, size_t>
      >
    >
  > lookup;

  // generate variables and set decision for unmaintained edges
  for(size_t epoch = 0; epoch < nmp.number_of_epochs(); ++epoch){
    std::stringstream name_appendix;
    name_appendix << "epoch_" << epoch;
    lookup.push_back(lp_generator::grow_from_graph(
      lp,
      graph,
      [&critical, epoch](Edge* edge) -> std::vector<constraint_data> {
        std::stringstream non_critical_fix;
        non_critical_fix << "edge_" << edge->description() << "_non_critical_epoch_" << epoch;

        if(critical.find(edge) == critical.end()){
          return {{non_critical_fix.str(), Equality, {{}, {{{edge, "Selected"}, 1}}}, 0}};
        }
        return {};
      },
      [](Node* node) -> std::vector<constraint_data> {
        return {};
      },
      {{"Selected", {Integral, {true, 0}, {true, 1}}}},
      {},
      name_appendix.str()
    ));
  }

  /*
    critical edges processed
  */
  for(Edge* e : critical){
    std::unordered_map<Variable*, Coefficient> lhs;
    for(auto lookup_during_epoch : lookup){
      lhs.insert({lookup_during_epoch.second.find({e, "Selected"})->second.first, {1}});
    }
    std::stringstream name;
    name << "critical_edge_" << e->description() << "_processed";
    lp.polyeder().add_constraint(
      { // constraint
        name.str(),
        Equality,
        lhs,
        1,
      }
    ); // TODO: consider making a inequality
  }

  std::pair<Variable*, size_t> target_var = lp.polyeder().add_variable(Variable("target_variable", Continuous));
  lp.add_direction_coefficient({target_var.first, 1});

  return {lp, lookup};
}

SCIP* generate_nmp_bendersdecomp(Maintenance_Problem& nmp, SCIP* basic_scip, SCIP_SOL* opt){

  container* c = new container;
  *c = container{
    basic_scip,
    opt,
    std::map<SCIP_VAR*, SCIP_VAR*>(),
    nullptr
  };



  // generating programs:
  std::cout << "generating master program" << std::endl;
  auto master_and_lookup = generate_master(nmp, nmp.network(), nmp.source(), nmp.target());
  auto computational_master_and_lookup = master_and_lookup.first.computational_model();


  SCIP_SOL* sol;
  SCIPcreateSol(computational_master_and_lookup.first, &sol, NULL);


  SCIP_VAR** vars = SCIPgetOrigVars(computational_master_and_lookup.first);
  int nvars = SCIPgetNOrigVars(computational_master_and_lookup.first);
  for(int index = 0; index < nvars; index++){
    SCIP_VAR* remote = SCIPfindVar(c->basic_scip, SCIPvarGetName(vars[index]));
    c->trans.insert({vars[index], remote});
    SCIPsetSolVal(computational_master_and_lookup.first, sol, vars[index], SCIPgetSolVal(c->basic_scip, c->opt, remote));
    c->transopt = sol;

    assert(SCIPgetSolVal(computational_master_and_lookup.first, c->transopt, vars[index]) == SCIPgetSolVal(c->basic_scip, c->opt, remote));
  }






  std::cout << "generating subproblems: ";
  std::vector<
    std::pair<
      Linear_Program,
      std::pair<
        std::map<
          std::pair<Node*,std::string>,
          std::pair<Variable*, size_t>
        >,
        std::map<
          std::pair<Edge*,std::string>,
          std::pair<Variable*, size_t>
        >
      >
    >
  > subproblems_with_lookups_lpsols;
  subproblems_with_lookups_lpsols.reserve(nmp.number_of_epochs());
  std::vector<
    std::pair<
      SCIP*,
      std::unordered_map<Variable*, SCIP_VAR*>
    >
  > computational_subproblems_with_lookups_lpsols;
  computational_subproblems_with_lookups_lpsols.reserve(nmp.number_of_epochs());
  std::vector<
    std::pair<
      Linear_Program,
      std::pair<
        std::map<
          std::pair<Node*,std::string>,
          std::pair<Variable*, size_t>
        >,
        std::map<
          std::pair<Edge*,std::string>,
          std::pair<Variable*, size_t>
        >
      >
    >
  > subproblems_with_lookups_heursols;
  subproblems_with_lookups_heursols.reserve(nmp.number_of_epochs());
  std::vector<
    std::pair<
      SCIP*,
      std::unordered_map<Variable*, SCIP_VAR*>
    >
  > computational_subproblems_with_lookups_heursols;
  computational_subproblems_with_lookups_heursols.reserve(nmp.number_of_epochs());

  for( size_t epoch = 0; epoch < nmp.number_of_epochs(); epoch++){
    std::cout << "[" << epoch << "] " << std::flush;
    subproblems_with_lookups_lpsols.push_back(generate_dual_flow_problem(nmp.network(), nmp.source(), nmp.target()));
    computational_subproblems_with_lookups_lpsols.push_back(subproblems_with_lookups_lpsols[epoch].first.computational_model());
    SCIP_CALL_ABORT( SCIPsetMessagehdlr(computational_subproblems_with_lookups_lpsols[epoch].first, NULL));

    subproblems_with_lookups_heursols.push_back(generate_dual_flow_problem(nmp.network(), nmp.source(), nmp.target()));
    computational_subproblems_with_lookups_heursols.push_back(subproblems_with_lookups_heursols[epoch].first.computational_model());
    SCIP_CALL_ABORT( SCIPsetMessagehdlr(computational_subproblems_with_lookups_heursols[epoch].first, NULL));
  }
  std::cout << "\n";

  std::cout << "creating lookup tables to translate between decision variables in master and their flow variables in the subproblems: ";
  for( size_t epoch = 0; epoch < nmp.number_of_epochs(); epoch++){
    std::cout << "[" << epoch << "] " << std::flush;
    /*
      For every edge and epoch combination we have created decision
      variables in the master and a flow Edgepotential variable in a
      subproblem.
      We link these in their respective vardata for quick access.
      (This is in contrast to benders_default.c where this translation is achieved with hashmaps)
    */
    for(Edge* e : nmp.network().edges()){
      Variable* master_var = master_and_lookup.second[epoch].second.find({e, "Selected"})->second.first;
      SCIP_VAR* computational_master_var = computational_master_and_lookup.second.find(master_var)->second;

      Variable* subproblem_var_lpsol = subproblems_with_lookups_lpsols[epoch].second.second.find({e, "Edgepotential"})->second.first;
      SCIP_VAR* computational_subproblem_var_lpsol = computational_subproblems_with_lookups_lpsols[epoch].second.find(subproblem_var_lpsol)->second;

      Variable* subproblem_var_heursol = subproblems_with_lookups_heursols[epoch].second.second.find({e, "Edgepotential"})->second.first;
      SCIP_VAR* computational_subproblem_var_heursol = computational_subproblems_with_lookups_heursols[epoch].second.find(subproblem_var_heursol)->second;

      // linking computational variables by setting vardata appropriately
      SCIP_VarData_Master* master_vardata;
      SCIP_CALL_ABORT( SCIPallocBlockMemory(computational_master_and_lookup.first, &master_vardata));
      *master_vardata = SCIP_VarData_Master{
        computational_subproblems_with_lookups_lpsols[epoch].first,
        computational_subproblem_var_lpsol,
        computational_subproblems_with_lookups_heursols[epoch].first,
        computational_subproblem_var_heursol
      };
      SCIPvarSetData(computational_master_var, (SCIP_VARDATA*) master_vardata);
      SCIPvarSetDelorigData(computational_master_var, del_vardata_master);

      int nedges = nmp.network().edges().size();
      SCIP_VarData_Subproblem* subproblem_vardata_lpsol;
      SCIP_CALL_ABORT( SCIPallocBlockMemory(computational_subproblems_with_lookups_lpsols[epoch].first, &subproblem_vardata_lpsol));
      *subproblem_vardata_lpsol = SCIP_VarData_Subproblem{
        e->attribute_throwing("Upper").value(),
        computational_master_and_lookup.first,
        computational_master_var
      };
      SCIPvarSetData(computational_subproblem_var_lpsol, (SCIP_VARDATA*) subproblem_vardata_lpsol);
      SCIPvarSetDelorigData(computational_subproblem_var_lpsol, del_vardata_subproblem);


      SCIP_VarData_Subproblem* subproblem_vardata_heursol;
      SCIP_CALL_ABORT( SCIPallocBlockMemory(computational_subproblems_with_lookups_heursols[epoch].first, &subproblem_vardata_heursol));
      *subproblem_vardata_heursol = SCIP_VarData_Subproblem{
        e->attribute_throwing("Upper").value(),
        computational_master_and_lookup.first,
        computational_master_var
      };
      SCIPvarSetData(computational_subproblem_var_heursol, (SCIP_VARDATA*) subproblem_vardata_heursol);
      SCIPvarSetDelorigData(computational_subproblem_var_heursol, del_vardata_subproblem);
    }
  }
  std::cout << "\n";

  // copying subproblem ptrs into continuous array (also setting reopt flag and probdata)
  std::cout << "Initializing Benders Conshdlr" << std::endl;
  SCIP** benders_separators_lpsols;
  SCIP_CALL_ABORT( SCIPallocBlockMemoryArray(computational_master_and_lookup.first, &benders_separators_lpsols, nmp.number_of_epochs()));
  SCIP** benders_separators_heursols;
  SCIP_CALL_ABORT( SCIPallocBlockMemoryArray(computational_master_and_lookup.first, &benders_separators_heursols, nmp.number_of_epochs()));

  for(size_t epoch = 0; epoch < nmp.number_of_epochs(); epoch++){
    benders_separators_lpsols[epoch] = computational_subproblems_with_lookups_lpsols[epoch].first;
    SCIP_Probdata_Subproblem* probdata_lpsol;
    SCIP_CALL_ABORT( SCIPallocBlockMemory(benders_separators_lpsols[epoch], &probdata_lpsol));
    *probdata_lpsol = SCIP_Probdata_Subproblem{
      epoch,
      nmp.number_of_epochs(),
      nmp.network().edges().size(),
      0
    };
    SCIP_CALL_ABORT( SCIPsetProbData(benders_separators_lpsols[epoch], (SCIP_PROBDATA*) probdata_lpsol));
    SCIP_CALL_ABORT( SCIPsetProbDelorig(benders_separators_lpsols[epoch], del_probdata_subproblem));


    benders_separators_heursols[epoch] = computational_subproblems_with_lookups_heursols[epoch].first;
    SCIP_Probdata_Subproblem* probdata_heursol;
    SCIP_CALL_ABORT( SCIPallocBlockMemory(benders_separators_heursols[epoch], &probdata_heursol));
    *probdata_heursol = SCIP_Probdata_Subproblem{
      epoch,
      nmp.number_of_epochs(),
      nmp.network().edges().size(),
      0
    };
    SCIP_CALL_ABORT( SCIPsetProbData(benders_separators_heursols[epoch], (SCIP_PROBDATA*) probdata_heursol));
    SCIP_CALL_ABORT( SCIPsetProbDelorig(benders_separators_heursols[epoch], del_probdata_subproblem));

    SCIP_CALL_ABORT( SCIPenableReoptimization( benders_separators_lpsols[epoch], TRUE));
    SCIP_CALL_ABORT( SCIPenableReoptimization( benders_separators_heursols[epoch], TRUE));
  }


jonasseidel's avatar
jonasseidel committed
411 412 413 414 415 416 417
  SCIP_CALL_ABORT( SCIPsetBoolParam(computational_master_and_lookup.first, "constraints/benders/active", TRUE) );
  SCIP_CALL_ABORT( SCIPsetPresolving(computational_master_and_lookup.first, SCIP_PARAMSETTING_OFF, TRUE) );
  SCIP_CALL_ABORT( SCIPsetIntParam(computational_master_and_lookup.first, "propagating/maxrounds", 0) );
  SCIP_CALL_ABORT( SCIPsetIntParam(computational_master_and_lookup.first, "propagating/maxroundsroot", 0) );
  SCIP_CALL_ABORT( SCIPsetIntParam(computational_master_and_lookup.first, "heuristics/trysol/freq", 1) );


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

  SCIP_CALL_ABORT( SCIPincludeConshdlrNMPBenders( computational_master_and_lookup.first, benders_separators_lpsols, benders_separators_heursols, nmp.number_of_epochs(), c));

  SCIPprintOrigProblem(computational_master_and_lookup.first, fopen("lp", "w"), "lp", FALSE);

  SCIP_Bool feasible = false;
  SCIPcheckSolOrig(c->basic_scip, c->opt, &feasible, FALSE, TRUE);
  assert(feasible);
  SCIPprintSol(c->basic_scip, c->opt, NULL, TRUE);
  SCIPprintSol(computational_master_and_lookup.first, c->transopt, NULL, TRUE);

  SCIP_CONS** conss = SCIPgetOrigConss(computational_master_and_lookup.first);
  int nconss = SCIPgetNOrigConss(computational_master_and_lookup.first);
  for(int index = 0; index < nconss; index++){
    SCIP_VAR* vars[1000];
    SCIP_Bool success;
    SCIPgetConsVars(computational_master_and_lookup.first, conss[index], vars, 1000, &success);
    assert(success);
    int nvars;
    SCIPgetConsNVars(computational_master_and_lookup.first, conss[index], &nvars, &success);
    assert(success);
    SCIP_Real coeffs[1000];
    SCIPgetConsVals(computational_master_and_lookup.first, conss[index], coeffs, 1000, &success);

    SCIP_Real lhs = SCIPconsGetLhs(computational_master_and_lookup.first, conss[index], &success);
    assert(success);
    SCIP_Real rhs = SCIPconsGetRhs(computational_master_and_lookup.first, conss[index], &success);
    assert(success);
    std::cout << lhs << " <= ";
    double center = 0;
    for(int var_index = 0; var_index < nvars; var_index++){
      std::cout << " + " << coeffs[var_index] << " " << SCIPvarGetName(vars[var_index]);

      double test = coeffs[var_index] * SCIPgetSolVal(c->basic_scip, c->opt, c->trans.find(vars[var_index])->second);
      assert(coeffs[var_index] == 1);

      std::cout << " (" << center << " + " << test;

      center = center + test;
      std::cout << " = " << center << ") ";
    }
    std::cout << " <= " << rhs << std::endl;

    std::cout << lhs << " <= " << center << " <= " << rhs << std::endl;
    if(SCIPisGT(c->basic_scip, lhs, center) || SCIPisGT(c->basic_scip, center, rhs)){
      for(int var_index = 0; var_index < nvars; var_index++){
        std::cout << "name of benders var " << SCIPvarGetName(vars[var_index]) << std::endl;
        std::cout << "name of basic_scip var " << SCIPvarGetName(c->trans.find(vars[var_index])->second) << std::endl;
        std::cout << "status in benders " << SCIPvarGetStatus(vars[var_index]) << std::endl;
        std::cout << "status in benders " << SCIPvarGetStatus(c->trans.find(vars[var_index])->second) << std::endl;

        std::cout << SCIPgetSolVal(c->basic_scip, c->opt, c->trans.find(vars[var_index])->second) << std::endl;
        assert( SCIPfindVar(c->basic_scip, SCIPvarGetName(vars[var_index])) == c->trans.find(vars[var_index])->second);
        std::cout << "equal" << std::endl;
      }
      SCIPABORT();
    }
  }

jonasseidel's avatar
jonasseidel committed
477 478
  SCIPpresolve(computational_master_and_lookup.first);
  SCIPprintTransProblem(computational_master_and_lookup.first, NULL, NULL, FALSE);
479 480 481 482


  SCIPsolve(computational_master_and_lookup.first);

jonasseidel's avatar
jonasseidel committed
483 484


485
  SCIP_Bool feas = FALSE;
jonasseidel's avatar
jonasseidel committed
486 487
  SCIPcheckSol(computational_master_and_lookup.first, c->transopt, TRUE, TRUE, TRUE, TRUE, TRUE, &feas);
  SCIPprintTransProblem(computational_master_and_lookup.first, NULL, NULL, FALSE);
488 489 490 491 492 493
  assert(feas);
  std::cout << "feas: " << feas << std::endl;

  // returning just the scip ptr to our master
  return computational_master_and_lookup.first;
}