ipcomp.cpp
2.3 KB
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
#include <iostream>
#include <time.h>
#include <cfloat>
#include <tuple>
#include <algorithm>
#include "ipcomp.h"
Ipcomp::Ipcomp(const std::vector < unsigned int > &v,
const std::vector < float > &w,
const std::vector < std::vector < unsigned int > > &NvBs,
unsigned int ncores)
{
vertices = std::vector < unsigned int > (v);
weights = std::vector < float > (w);
NvB = std::vector < std::vector < unsigned int > > (NvBs);
ip_ = new IP(IP::MIN, int(ncores));
/*creating variables and objective function*/
for(size_t i=0, size = vertices.size(); i != size; i++)
{
v_.push_back(ip_->make_variable(double(weights[vertices[i]])));
}
ip_->update();
/*creating constraints*/
/*for each vertice*/
for (size_t i = 0, size = vertices.size(); i != size; i++)
{
//std::cout << "i = " << i << std::endl;
int row = ip_->make_constraint(IP::UP, 0, double(NvB[i].size()));
ip_->add_constraint(row, v_[i], double(NvB[i].size()));
for (size_t j = 0, size2 = NvB[i].size(); j != size2; j++)
{
ip_->add_constraint(row, v_[NvB[i][j]], 1);
}
}
}
Ipcomp::~Ipcomp()
{
delete ip_;
}
void Ipcomp::add_bj_ct(std::vector< unsigned int > c)
{
int row = ip_->make_constraint(IP::LO, 0, 0);
int B(0);
for(size_t i = 0, size = vertices.size(); i != size; i++)
{
if(std::find(c.begin(), c.end(), int(i)) != c.end())
{
ip_->add_constraint(row, v_[i], 1);
B++;
}
else
{
ip_->add_constraint(row, v_[i], -1);
}
}
ip_->chg_constraint(row, IP::UP, -DBL_MAX, B-1);
}
int Ipcomp::solve(std::vector< unsigned int > &c, float &score)
{
time_t start, end; /* returns elapsed time in sec */
double total_time;
start = clock();
int status = ip_->solve();
end = clock();
total_time = double(end - start)/double(CLOCKS_PER_SEC);
printf( "\nElapsed time SOLVE IP: %0.3f \n", total_time );
if(status == 0){
score = float(ip_->get_obj());
//recover decision variable values
for(size_t i=0, size = v_.size(); i != size; i++)
{
if(ip_->get_value(v_[i]) > 0.5)
c.push_back(uint(i));
}
}
return status;
}