1/*
2 * Copyright 2008-2009 Katholieke Universiteit Leuven
3 *
4 * Use of this software is governed by the MIT license
5 *
6 * Written by Sven Verdoolaege, K.U.Leuven, Departement
7 * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
8 */
9
10#include <assert.h>
11#include <isl/set.h>
12#include <isl/vec.h>
13#include <isl/ilp.h>
14#include <isl/seq.h>
15
16/* The input of this program is the same as that of the "polytope_minimize"
17 * program from the barvinok distribution.
18 *
19 * Constraints of set is PolyLib format.
20 * Linear or affine objective function in PolyLib format.
21 */
22
23static struct isl_vec *isl_vec_lin_to_aff(struct isl_vec *vec)
24{
25	struct isl_vec *aff;
26
27	if (!vec)
28		return NULL;
29	aff = isl_vec_alloc(vec->ctx, 1 + vec->size);
30	if (!aff)
31		goto error;
32	isl_int_set_si(aff->el[0], 0);
33	isl_seq_cpy(aff->el + 1, vec->el, vec->size);
34	isl_vec_free(vec);
35	return aff;
36error:
37	isl_vec_free(vec);
38	return NULL;
39}
40
41/* Rotate elements of vector right.
42 * In particular, move the constant term from the end of the
43 * vector to the start of the vector.
44 */
45static struct isl_vec *vec_ror(struct isl_vec *vec)
46{
47	int i;
48
49	if (!vec)
50		return NULL;
51	for (i = vec->size - 2; i >= 0; --i)
52		isl_int_swap(vec->el[i], vec->el[i + 1]);
53	return vec;
54}
55
56int main(int argc, char **argv)
57{
58	struct isl_ctx *ctx = isl_ctx_alloc();
59	struct isl_basic_set *bset;
60	struct isl_vec *obj;
61	struct isl_vec *sol;
62	isl_int opt;
63	unsigned dim;
64	enum isl_lp_result res;
65	isl_printer *p;
66
67	isl_int_init(opt);
68	bset = isl_basic_set_read_from_file(ctx, stdin);
69	assert(bset);
70	obj = isl_vec_read_from_file(ctx, stdin);
71	assert(obj);
72	dim = isl_basic_set_total_dim(bset);
73	assert(obj->size >= dim && obj->size <= dim + 1);
74	if (obj->size != dim + 1)
75		obj = isl_vec_lin_to_aff(obj);
76	else
77		obj = vec_ror(obj);
78	res = isl_basic_set_solve_ilp(bset, 0, obj->el, &opt, &sol);
79	switch (res) {
80	case isl_lp_error:
81		fprintf(stderr, "error\n");
82		return -1;
83	case isl_lp_empty:
84		fprintf(stdout, "empty\n");
85		break;
86	case isl_lp_unbounded:
87		fprintf(stdout, "unbounded\n");
88		break;
89	case isl_lp_ok:
90		p = isl_printer_to_file(ctx, stdout);
91		p = isl_printer_print_vec(p, sol);
92		p = isl_printer_end_line(p);
93		p = isl_printer_print_isl_int(p, opt);
94		p = isl_printer_end_line(p);
95		isl_printer_free(p);
96	}
97	isl_basic_set_free(bset);
98	isl_vec_free(obj);
99	isl_vec_free(sol);
100	isl_ctx_free(ctx);
101	isl_int_clear(opt);
102
103	return 0;
104}
105