outsourced some functionality
[libfirm] / ir / lpp / lpp_cplex.c
1 /**
2  * Author:      Daniel Grund
3  * Date:        02.06.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  */
7 #include "config.h"
8
9 #include "lpp_cplex.h"
10
11 #include <stdio.h>
12 #include <stdlib.h>
13
14 #ifdef WITH_CPLEX
15
16
17 #ifdef _WIN32
18 #include <malloc.h>
19 #else
20 #include <sys/time.h>
21 #include <alloca.h>
22 #endif
23
24 #include "obst.h"
25
26 #include <ilcplex/cplex.h>
27
28 #include "assert.h"
29 #include "sp_matrix.h"
30
31 static char cpx_cst_encoding[4] = "?ELG";
32 static char cpx_var_encoding[4] = "??CB";
33
34 #define my_timersub(tvp, uvp, vvp)                     \
35     do {                                \
36         (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;      \
37         (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;   \
38         if ((vvp)->tv_usec < 0) {               \
39             (vvp)->tv_sec--;                \
40             (vvp)->tv_usec += 1000000;          \
41         }                           \
42     } while (0)
43
44 typedef struct _cpx_t {
45         lpp_t *lpp;
46         CPXENVptr env;
47         CPXLPptr prob;
48         int status;
49         char buf[1024];
50 } cpx_t;
51
52 static void chk_cpx_err(cpx_t *cpx) {
53         if (cpx->status) {
54                 if (CPXgeterrorstring(cpx->env, cpx->status, cpx->buf))
55                         printf("%s", cpx->buf);
56                 else
57                         printf("Unknown CPLEX error\n");
58                 assert(0);
59         }
60 }
61
62 static cpx_t *new_cpx(lpp_t *lpp) {
63         cpx_t *cpx = XMALLOCZ(cpx_t);
64         cpx->lpp = lpp;
65         cpx->env = CPXopenCPLEX(&cpx->status);
66         chk_cpx_err(cpx);
67         cpx->prob = CPXcreateprob(cpx->env, &cpx->status, lpp->name);
68         chk_cpx_err(cpx);
69         CPXchgobjsen(cpx->env, cpx->prob, (lpp->opt_type == lpp_minimize)?1:-1);
70         chk_cpx_err(cpx);
71         if (lpp->log && CPXsetlogfile(cpx->env, lpp->log))
72                 lpp->log = NULL;
73         return cpx;
74 }
75
76 static void free_cpx(cpx_t *cpx) {
77         CPXfreeprob(cpx->env, &cpx->prob);
78         CPXcloseCPLEX(&cpx->env);
79         free(cpx);
80 }
81
82 /**
83  * Build CPLEX data structure from LPP matrix.
84  * @note: The LPP matrix is freed after this step, to save memory.
85  */
86 static void cpx_construct(cpx_t *cpx) {
87         const matrix_elem_t *elem;
88         int                  i, o, sv_cnt;
89         int                  numcols, numrows, numentries;
90         int                  objsen, *matbeg, *matcnt, *matind, *indices;
91         double               *obj, *rhs, *matval, *lb, *ub, *startv;
92         char                 *sense, *vartype;
93         char                 **colname, **rowname;
94         struct obstack       obst;
95         lpp_t                *lpp = cpx->lpp;
96
97         numcols    = lpp->var_next-1;
98         numrows    = lpp->cst_next-1;
99         numentries = matrix_get_entries(lpp->m);
100         objsen     = lpp->opt_type == lpp_minimize ? 1 : -1;
101         obstack_init(&obst);
102
103         obj     = obstack_alloc(&obst, numcols * sizeof(*obj));
104         lb      = obstack_alloc(&obst, numcols * sizeof(*lb));
105         ub      = obstack_alloc(&obst, numcols * sizeof(*ub));
106         colname = obstack_alloc(&obst, numcols * sizeof(*colname));
107         rowname = obstack_alloc(&obst, numrows * sizeof(*rowname));
108         vartype = obstack_alloc(&obst, numcols * sizeof(*vartype));
109         indices = obstack_alloc(&obst, numcols * sizeof(*indices));
110         startv  = obstack_alloc(&obst, numcols * sizeof(*startv));
111         matbeg  = obstack_alloc(&obst, numcols * sizeof(*matbeg));
112         matcnt  = obstack_alloc(&obst, numcols * sizeof(*matcnt));
113         matind  = obstack_alloc(&obst, numentries * sizeof(*matind));
114         matval  = obstack_alloc(&obst, numentries * sizeof(*matval));
115         rhs     = obstack_alloc(&obst, numrows * sizeof(*rhs));
116         sense   = obstack_alloc(&obst, numrows * sizeof(*sense));
117
118         o      = 0;
119         sv_cnt = 0;
120         /* fill the CPLEX matrix*/
121         for (i = 0; i < numcols; ++i) {
122                 lpp_name_t *curr_var = lpp->vars[1+i];
123
124                 obj[i] = matrix_get(lpp->m, 0, 1+i);
125                 lb[i]  = 0.0;
126                 ub[i]  = CPX_INFBOUND;
127
128                 colname[i] = (char*) curr_var->name;
129                 vartype[i] = cpx_var_encoding[curr_var->type.var_type];
130
131                 if (curr_var->value_kind == lpp_value_start) {
132                         indices[sv_cnt]  = i;
133                         startv[sv_cnt++] = curr_var->value;
134                 }
135
136                 matbeg[i] = o;
137                 matcnt[i] = 0;
138                 matrix_foreach_in_col(lpp->m, 1 + i, elem) {
139                         if (elem->row == 0)
140                                 continue;
141                         matind[o] = elem->row-1;
142                         matval[o] = elem->val;
143                         matcnt[i]++;
144                         o++;
145                 }
146         }
147
148         /* get constraint stuff (right hand side, type, name) */
149         for (i = 0; i < numrows; ++i) {
150                 lpp_name_t *curr_cst = lpp->csts[1 + i];
151
152                 rhs[i]     = matrix_get(lpp->m, 1 + i, 0);
153                 sense[i]   = cpx_cst_encoding[curr_cst->type.cst_type];
154                 rowname[i] = (char*) curr_cst->name;
155         }
156
157         cpx->status = CPXcopylpwnames(cpx->env, cpx->prob,
158                                                 numcols, numrows, objsen,
159                                                 obj, rhs, sense,
160                                                 matbeg, matcnt, matind, matval,
161                                                 lb, ub, NULL,
162                                                 colname, rowname);
163         chk_cpx_err(cpx);
164
165         cpx->status = CPXcopyctype(cpx->env, cpx->prob, vartype);
166         chk_cpx_err(cpx);
167         cpx->status = CPXcopymipstart(cpx->env, cpx->prob, sv_cnt, indices, startv);
168         chk_cpx_err(cpx);
169
170         obstack_free(&obst, NULL);
171         free_lpp_matrix(lpp);
172 }
173
174 static void cpx_solve(cpx_t *cpx) {
175         int i, CPX_state, numcols;
176         double *values;
177         struct timeval tvb, tva, tvdiff;
178
179         lpp_t *lpp = cpx->lpp;
180         numcols = CPXgetnumcols(cpx->env, cpx->prob);
181         chk_cpx_err(cpx);
182
183         /* set performance parameters */
184         // CPXsetintparam(cpx->env, CPX_PARAM_MIPSTART, CPX_ON);
185         CPXsetintparam(cpx->env, CPX_PARAM_MIPORDTYPE, CPX_MIPORDER_COST);
186         /* output every search tree node */
187         // CPXsetintparam(cpx->env, CPX_PARAM_MIPINTERVAL, 1);
188
189         /* experimental switches */
190         // CPXsetintparam(cpx->env, CPX_PARAM_VARSEL, CPX_VARSEL_STRONG);
191         // CPXsetdblparam(cpx->env, CPX_PARAM_BTTOL, 1.0);
192         // CPXsetintparam(cpx->env, CPX_PARAM_BRDIR, CPX_BRDIR_UP);
193
194
195         /* Set the time limit appropriately */
196         if(lpp->time_limit_secs > 0.0)
197                 CPXsetdblparam(cpx->env, CPX_PARAM_TILIM, lpp->time_limit_secs);
198
199         /*
200          * If we have enough time, we instruct cplex to imply some
201          * of its higher order magic to pursue the best solution
202          */
203         if(lpp->emphasis) {
204           CPXsetintparam(cpx->env, CPX_PARAM_MIPEMPHASIS, lpp->emphasis);
205         }
206
207         /*
208          * If a bound of the objective function is supplied,
209          * set it accordingly, dependign on minimization or maximization.
210          */
211         if(lpp->set_bound) {
212                 CPXsetdblparam(cpx->env, (lpp->opt_type == lpp_minimize
213                                         ? CPX_PARAM_OBJLLIM : CPX_PARAM_OBJULIM), lpp->bound);
214         }
215
216         /* turn on the fancy messages :) */
217         // CPXsetintparam (cpx->env, CPX_PARAM_SCRIND, CPX_ON);
218
219         /* solve */
220         gettimeofday(&tvb, NULL);
221         cpx->status = CPXmipopt(cpx->env, cpx->prob);
222         gettimeofday(&tva, NULL);
223         chk_cpx_err(cpx);
224
225         /* get solution status */
226         CPX_state = CPXgetstat(cpx->env, cpx->prob);
227         {
228           char buf[512];
229           CPXgetstatstring(cpx->env, CPX_state, buf);
230           fprintf(stderr, "%s\n", buf);
231         }
232         switch (CPX_state) {
233                 case CPXMIP_INFEASIBLE:
234                 case CPX_STAT_INFEASIBLE:   lpp->sol_state = lpp_infeasible; break;
235                 case CPXMIP_INForUNBD:
236                 case CPX_STAT_INForUNBD:    lpp->sol_state = lpp_inforunb; break;
237                 case CPXMIP_UNBOUNDED:
238                 case CPX_STAT_UNBOUNDED:    lpp->sol_state = lpp_unbounded; break;
239                 case CPXMIP_ABORT_FEAS:
240                 case CPXMIP_FAIL_FEAS:
241                 case CPXMIP_MEM_LIM_FEAS:
242                 case CPXMIP_NODE_LIM_FEAS:
243                 case CPXMIP_TIME_LIM_FEAS:  lpp->sol_state = lpp_feasible; break;
244                 case CPXMIP_OPTIMAL:
245                 case CPXMIP_OPTIMAL_TOL:    /* TODO: Is this ok? Read the docu more closely */
246                 case CPX_STAT_OPTIMAL:      lpp->sol_state = lpp_optimal; break;
247                 default:                    lpp->sol_state = lpp_unknown;
248         }
249
250         /* get variable solution values */
251         values = alloca(numcols * sizeof(*values));
252         CPXgetmipx(cpx->env, cpx->prob, values, 0, numcols-1);
253         chk_cpx_err(cpx);
254         for(i=0; i<numcols; ++i) {
255                 lpp->vars[1+i]->value = values[i];
256                 lpp->vars[1+i]->value_kind = lpp_value_solution;
257         }
258
259         /* Get the value of the objective function. */
260         CPXgetmipobjval(cpx->env, cpx->prob, &lpp->objval);
261         CPXgetbestobjval(cpx->env, cpx->prob, &lpp->best_bound);
262
263         /* get some statistics */
264         my_timersub(&tva, &tvb, &tvdiff);
265         lpp->sol_time = tvdiff.tv_sec + tvdiff.tv_usec / 1e6;
266         lpp->iterations = CPXgetmipitcnt(cpx->env, cpx->prob);
267 }
268
269 void lpp_solve_cplex(lpp_t *lpp) {
270         cpx_t *cpx = new_cpx(lpp);
271         cpx_construct(cpx);
272         cpx_solve(cpx);
273         free_cpx(cpx);
274 }
275
276 #endif