Constraint.cpp 2.15 KB
Newer Older
1 2
#include "Constraint.h"

jonasseidel's avatar
jonasseidel committed
3
Constraint::Constraint(std::string description, relation relation_type, std::unordered_map<Variable*, Coefficient> lhs, Coefficient rhs)
4
  : _description(description), _relation(relation_type), _lhs(lhs), _rhs(rhs){}
Jonas Seidel's avatar
Jonas Seidel committed
5

jonasseidel's avatar
jonasseidel committed
6
Constraint::Constraint(relation relation_type, std::unordered_map<Variable*, Coefficient> lhs, Coefficient rhs)
7
  : _relation(relation_type), _lhs(lhs), _rhs(rhs){}
8

Jonas Seidel's avatar
Jonas Seidel committed
9 10 11 12
std::string Constraint::description(){
  return this->_description;
}

13 14 15 16
relation Constraint::is_equality(){
  return this->_relation;
}

jonasseidel's avatar
jonasseidel committed
17
std::unordered_map<Variable*, Coefficient> Constraint::lhs(){
18 19 20
  return this->_lhs;
}

21
Coefficient Constraint::lhs_coefficient(Variable* var){
22 23
  auto tmp = this->_lhs.find(var);
  if(tmp == this->_lhs.end()){
24
    return {0};
25 26
  }
  return tmp->second;
27 28
}

29
Coefficient Constraint::rhs(){
30 31 32
  return this->_rhs;
}

jonasseidel's avatar
jonasseidel committed
33 34 35 36
SCIP_CONS* Constraint::computational_con(SCIP* scip, std::unordered_map<Variable*, SCIP_VAR*>& variable_lookup){
  SCIP_CONS* cons;
  SCIP_Real right_inequality = this->_rhs.value();
  SCIP_Real left_inequality = (this->is_equality() ? right_inequality : -SCIPinfinity(scip));
jonasseidel's avatar
jonasseidel committed
37 38

  SCIP_CALL_ABORT( SCIPcreateConsBasicLinear(scip, &cons, this->description().c_str(),
jonasseidel's avatar
jonasseidel committed
39 40 41 42 43 44 45 46
                                   0, NULL, NULL, left_inequality, right_inequality));

  for(std::pair<Variable*, Coefficient> pair : this->_lhs){
    SCIP_CALL_ABORT( SCIPaddCoefLinear(scip, cons, variable_lookup.find(pair.first)->second, pair.second.value()));
  }
  return cons;
}

47
std::ostream& operator<<(std::ostream& os, Constraint& constraint){
48
  os << constraint.description() << ":\t";
Jonas Seidel's avatar
Jonas Seidel committed
49
  bool empty = true;
50 51 52

  bool add_plus = false;
  for(auto summand : constraint.lhs()){
53
    if(summand.second.is_non_zero()){
54
      empty = false;
55
      if(add_plus && !Coefficient::always_add_sign){
56 57 58
        os << " + ";
      }
      add_plus = true;
59
      os << summand.second << *summand.first;
Jonas Seidel's avatar
Jonas Seidel committed
60 61 62 63
    }
  }
  if(empty){
    os << "0";
64 65
  }
  if(constraint.is_equality()){
Jonas Seidel's avatar
Jonas Seidel committed
66
    os << " = ";
67
  }else{
Jonas Seidel's avatar
Jonas Seidel committed
68
    os << " <= ";
69
  }
70 71 72 73 74 75 76
  if(!constraint.rhs().is_non_zero()){
    os << "0";
  }else if(constraint.rhs().is_unity()){
    os << "1";
  }else{
    os << constraint.rhs();
  }
77 78
  return os;
}