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