Makefile.am: keep better track of failed tests
[barvinok.git] / util.c
blob05391c926cd4b3a4b0a8d19d17cfef012232ca44
1 #include <stdlib.h>
2 #include <assert.h>
3 #include <barvinok/util.h>
4 #include <barvinok/options.h>
5 #include <polylib/ranking.h>
6 #include "config.h"
7 #include "lattice_point.h"
9 #define ALLOC(type) (type*)malloc(sizeof(type))
10 #define ALLOCN(type,n) (type*)malloc((n) * sizeof(type))
12 #ifdef __GNUC__
13 #define NALLOC(p,n) p = (typeof(p))malloc((n) * sizeof(*p))
14 #else
15 #define NALLOC(p,n) p = (void *)malloc((n) * sizeof(*p))
16 #endif
18 void manual_count(Polyhedron *P, Value* result)
20 Polyhedron *U = Universe_Polyhedron(0);
21 Enumeration *en = Polyhedron_Enumerate(P,U,1024,NULL);
22 Value *v = compute_poly(en,NULL);
23 value_assign(*result, *v);
24 value_clear(*v);
25 free(v);
26 Enumeration_Free(en);
27 Polyhedron_Free(U);
30 #include <barvinok/evalue.h>
31 #include <barvinok/util.h>
32 #include <barvinok/barvinok.h>
34 /* Return random value between 0 and max-1 inclusive
36 int random_int(int max) {
37 return (int) (((double)(max))*rand()/(RAND_MAX+1.0));
40 Polyhedron *Polyhedron_Read(unsigned MaxRays)
42 int vertices = 0;
43 unsigned NbRows, NbColumns;
44 Matrix *M;
45 Polyhedron *P;
46 char s[128];
48 while (fgets(s, sizeof(s), stdin)) {
49 if (*s == '#')
50 continue;
51 if (strncasecmp(s, "vertices", sizeof("vertices")-1) == 0)
52 vertices = 1;
53 if (sscanf(s, "%u %u", &NbRows, &NbColumns) == 2)
54 break;
56 if (feof(stdin))
57 return NULL;
58 M = Matrix_Alloc(NbRows,NbColumns);
59 Matrix_Read_Input(M);
60 if (vertices)
61 P = Rays2Polyhedron(M, MaxRays);
62 else
63 P = Constraints2Polyhedron(M, MaxRays);
64 Matrix_Free(M);
65 return P;
68 /* Inplace polarization
70 void Polyhedron_Polarize(Polyhedron *P)
72 unsigned NbRows = P->NbConstraints + P->NbRays;
73 int i;
74 Value **q;
76 q = (Value **)malloc(NbRows * sizeof(Value *));
77 assert(q);
78 for (i = 0; i < P->NbRays; ++i)
79 q[i] = P->Ray[i];
80 for (; i < NbRows; ++i)
81 q[i] = P->Constraint[i-P->NbRays];
82 P->NbConstraints = NbRows - P->NbConstraints;
83 P->NbRays = NbRows - P->NbRays;
84 free(P->Constraint);
85 P->Constraint = q;
86 P->Ray = q + P->NbConstraints;
90 * Rather general polar
91 * We can optimize it significantly if we assume that
92 * P includes zero
94 * Also, we calculate the polar as defined in Schrijver
95 * The opposite should probably work as well and would
96 * eliminate the need for multiplying by -1
98 Polyhedron* Polyhedron_Polar(Polyhedron *P, unsigned NbMaxRays)
100 int i;
101 Value mone;
102 unsigned dim = P->Dimension + 2;
103 Matrix *M = Matrix_Alloc(P->NbRays, dim);
105 assert(M);
106 value_init(mone);
107 value_set_si(mone, -1);
108 for (i = 0; i < P->NbRays; ++i) {
109 Vector_Scale(P->Ray[i], M->p[i], mone, dim);
110 value_multiply(M->p[i][0], M->p[i][0], mone);
111 value_multiply(M->p[i][dim-1], M->p[i][dim-1], mone);
113 P = Constraints2Polyhedron(M, NbMaxRays);
114 assert(P);
115 Matrix_Free(M);
116 value_clear(mone);
117 return P;
121 * Returns the supporting cone of P at the vertex with index v
123 Polyhedron* supporting_cone(Polyhedron *P, int v)
125 Matrix *M;
126 Value tmp;
127 int i, n, j;
128 unsigned char *supporting = (unsigned char *)malloc(P->NbConstraints);
129 unsigned dim = P->Dimension + 2;
131 assert(v >=0 && v < P->NbRays);
132 assert(value_pos_p(P->Ray[v][dim-1]));
133 assert(supporting);
135 value_init(tmp);
136 for (i = 0, n = 0; i < P->NbConstraints; ++i) {
137 Inner_Product(P->Constraint[i] + 1, P->Ray[v] + 1, dim - 1, &tmp);
138 if ((supporting[i] = value_zero_p(tmp)))
139 ++n;
141 assert(n >= dim - 2);
142 value_clear(tmp);
143 M = Matrix_Alloc(n, dim);
144 assert(M);
145 for (i = 0, j = 0; i < P->NbConstraints; ++i)
146 if (supporting[i]) {
147 value_set_si(M->p[j][dim-1], 0);
148 Vector_Copy(P->Constraint[i], M->p[j++], dim-1);
150 free(supporting);
151 P = Constraints2Polyhedron(M, P->NbRays+1);
152 assert(P);
153 Matrix_Free(M);
154 return P;
157 #define INT_BITS (sizeof(unsigned) * 8)
159 unsigned *supporting_constraints(Matrix *Constraints, Param_Vertices *v, int *n)
161 Value lcm, tmp, tmp2;
162 unsigned dim = Constraints->NbColumns;
163 unsigned nparam = v->Vertex->NbColumns - 2;
164 unsigned nvar = dim - nparam - 2;
165 int len = (Constraints->NbRows+INT_BITS-1)/INT_BITS;
166 unsigned *supporting = (unsigned *)calloc(len, sizeof(unsigned));
167 int i, j;
168 Vector *row;
169 int ix;
170 unsigned bx;
172 assert(supporting);
173 row = Vector_Alloc(nparam+1);
174 assert(row);
175 value_init(lcm);
176 value_init(tmp);
177 value_init(tmp2);
178 value_set_si(lcm, 1);
179 for (i = 0, *n = 0, ix = 0, bx = MSB; i < Constraints->NbRows; ++i) {
180 Vector_Set(row->p, 0, nparam+1);
181 for (j = 0 ; j < nvar; ++j) {
182 value_set_si(tmp, 1);
183 value_assign(tmp2, Constraints->p[i][j+1]);
184 if (value_ne(lcm, v->Vertex->p[j][nparam+1])) {
185 value_assign(tmp, lcm);
186 value_lcm(lcm, lcm, v->Vertex->p[j][nparam+1]);
187 value_division(tmp, lcm, tmp);
188 value_multiply(tmp2, tmp2, lcm);
189 value_division(tmp2, tmp2, v->Vertex->p[j][nparam+1]);
191 Vector_Combine(row->p, v->Vertex->p[j], row->p,
192 tmp, tmp2, nparam+1);
194 value_set_si(tmp, 1);
195 Vector_Combine(row->p, Constraints->p[i]+1+nvar, row->p, tmp, lcm, nparam+1);
196 for (j = 0; j < nparam+1; ++j)
197 if (value_notzero_p(row->p[j]))
198 break;
199 if (j == nparam + 1) {
200 supporting[ix] |= bx;
201 ++*n;
203 NEXT(ix, bx);
205 assert(*n >= nvar);
206 value_clear(tmp);
207 value_clear(tmp2);
208 value_clear(lcm);
209 Vector_Free(row);
211 return supporting;
214 Polyhedron* supporting_cone_p(Polyhedron *P, Param_Vertices *v)
216 Matrix *M;
217 unsigned dim = P->Dimension + 2;
218 unsigned nparam = v->Vertex->NbColumns - 2;
219 unsigned nvar = dim - nparam - 2;
220 int i, n, j;
221 int ix;
222 unsigned bx;
223 unsigned *supporting;
224 Matrix View;
226 Polyhedron_Matrix_View(P, &View, P->NbConstraints);
227 supporting = supporting_constraints(&View, v, &n);
228 M = Matrix_Alloc(n, nvar+2);
229 assert(M);
230 for (i = 0, j = 0, ix = 0, bx = MSB; i < P->NbConstraints; ++i) {
231 if (supporting[ix] & bx) {
232 value_set_si(M->p[j][nvar+1], 0);
233 Vector_Copy(P->Constraint[i], M->p[j++], nvar+1);
235 NEXT(ix, bx);
237 free(supporting);
238 P = Constraints2Polyhedron(M, P->NbRays+1);
239 assert(P);
240 Matrix_Free(M);
241 return P;
244 Polyhedron* triangulate_cone(Polyhedron *P, unsigned NbMaxCons)
246 struct barvinok_options *options = barvinok_options_new_with_defaults();
247 options->MaxRays = NbMaxCons;
248 P = triangulate_cone_with_options(P, options);
249 barvinok_options_free(options);
250 return P;
253 Polyhedron* triangulate_cone_with_options(Polyhedron *P,
254 struct barvinok_options *options)
256 const static int MAX_TRY=10;
257 int i, j, r, n, t;
258 Value tmp;
259 unsigned dim = P->Dimension;
260 Matrix *M = Matrix_Alloc(P->NbRays+1, dim+3);
261 Matrix *M2, *M3;
262 Polyhedron *L, *R, *T;
263 assert(P->NbEq == 0);
265 L = NULL;
266 R = NULL;
267 value_init(tmp);
269 Vector_Set(M->p[0]+1, 0, dim+1);
270 value_set_si(M->p[0][0], 1);
271 value_set_si(M->p[0][dim+2], 1);
272 Vector_Set(M->p[P->NbRays]+1, 0, dim+2);
273 value_set_si(M->p[P->NbRays][0], 1);
274 value_set_si(M->p[P->NbRays][dim+1], 1);
276 for (i = 0, r = 1; i < P->NbRays; ++i) {
277 if (value_notzero_p(P->Ray[i][dim+1]))
278 continue;
279 Vector_Copy(P->Ray[i], M->p[r], dim+1);
280 value_set_si(M->p[r][dim+2], 0);
281 ++r;
284 M2 = Matrix_Alloc(dim+1, dim+2);
286 t = 0;
287 if (options->try_Delaunay_triangulation) {
288 /* Delaunay triangulation */
289 for (r = 1; r < P->NbRays; ++r) {
290 Inner_Product(M->p[r]+1, M->p[r]+1, dim, &tmp);
291 value_assign(M->p[r][dim+1], tmp);
293 M3 = Matrix_Copy(M);
294 L = Rays2Polyhedron(M3, options->MaxRays);
295 Matrix_Free(M3);
296 ++t;
297 } else {
298 try_again:
299 /* Usually R should still be 0 */
300 Domain_Free(R);
301 Polyhedron_Free(L);
302 for (r = 1; r < P->NbRays; ++r) {
303 value_set_si(M->p[r][dim+1], random_int((t+1)*dim*P->NbRays)+1);
305 M3 = Matrix_Copy(M);
306 L = Rays2Polyhedron(M3, options->MaxRays);
307 Matrix_Free(M3);
308 ++t;
310 assert(t <= MAX_TRY);
312 R = NULL;
313 n = 0;
315 POL_ENSURE_FACETS(L);
316 for (i = 0; i < L->NbConstraints; ++i) {
317 /* Ignore perpendicular facets, i.e., facets with 0 z-coordinate */
318 if (value_negz_p(L->Constraint[i][dim+1]))
319 continue;
320 if (value_notzero_p(L->Constraint[i][dim+2]))
321 continue;
322 for (j = 1, r = 1; j < M->NbRows; ++j) {
323 Inner_Product(M->p[j]+1, L->Constraint[i]+1, dim+1, &tmp);
324 if (value_notzero_p(tmp))
325 continue;
326 if (r > dim)
327 goto try_again;
328 Vector_Copy(M->p[j]+1, M2->p[r]+1, dim);
329 value_set_si(M2->p[r][0], 1);
330 value_set_si(M2->p[r][dim+1], 0);
331 ++r;
333 assert(r == dim+1);
334 Vector_Set(M2->p[0]+1, 0, dim);
335 value_set_si(M2->p[0][0], 1);
336 value_set_si(M2->p[0][dim+1], 1);
337 T = Rays2Polyhedron(M2, P->NbConstraints+1);
338 T->next = R;
339 R = T;
340 ++n;
342 Matrix_Free(M2);
344 Polyhedron_Free(L);
345 value_clear(tmp);
346 Matrix_Free(M);
348 return R;
351 void check_triangulization(Polyhedron *P, Polyhedron *T)
353 Polyhedron *C, *D, *E, *F, *G, *U;
354 for (C = T; C; C = C->next) {
355 if (C == T)
356 U = C;
357 else
358 U = DomainConvex(DomainUnion(U, C, 100), 100);
359 for (D = C->next; D; D = D->next) {
360 F = C->next;
361 G = D->next;
362 C->next = NULL;
363 D->next = NULL;
364 E = DomainIntersection(C, D, 600);
365 assert(E->NbRays == 0 || E->NbEq >= 1);
366 Polyhedron_Free(E);
367 C->next = F;
368 D->next = G;
371 assert(PolyhedronIncludes(U, P));
372 assert(PolyhedronIncludes(P, U));
375 /* Computes x, y and g such that g = gcd(a,b) and a*x+b*y = g */
376 void Extended_Euclid(Value a, Value b, Value *x, Value *y, Value *g)
378 Value c, d, e, f, tmp;
380 value_init(c);
381 value_init(d);
382 value_init(e);
383 value_init(f);
384 value_init(tmp);
385 value_absolute(c, a);
386 value_absolute(d, b);
387 value_set_si(e, 1);
388 value_set_si(f, 0);
389 while(value_pos_p(d)) {
390 value_division(tmp, c, d);
391 value_multiply(tmp, tmp, f);
392 value_subtract(e, e, tmp);
393 value_division(tmp, c, d);
394 value_multiply(tmp, tmp, d);
395 value_subtract(c, c, tmp);
396 value_swap(c, d);
397 value_swap(e, f);
399 value_assign(*g, c);
400 if (value_zero_p(a))
401 value_set_si(*x, 0);
402 else if (value_pos_p(a))
403 value_assign(*x, e);
404 else value_oppose(*x, e);
405 if (value_zero_p(b))
406 value_set_si(*y, 0);
407 else {
408 value_multiply(tmp, a, *x);
409 value_subtract(tmp, c, tmp);
410 value_division(*y, tmp, b);
412 value_clear(c);
413 value_clear(d);
414 value_clear(e);
415 value_clear(f);
416 value_clear(tmp);
419 static int unimodular_complete_1(Matrix *m)
421 Value g, b, c, old, tmp;
422 unsigned i, j;
423 int ok;
425 value_init(b);
426 value_init(c);
427 value_init(g);
428 value_init(old);
429 value_init(tmp);
430 value_assign(g, m->p[0][0]);
431 for (i = 1; value_zero_p(g) && i < m->NbColumns; ++i) {
432 for (j = 0; j < m->NbColumns; ++j) {
433 if (j == i-1)
434 value_set_si(m->p[i][j], 1);
435 else
436 value_set_si(m->p[i][j], 0);
438 value_assign(g, m->p[0][i]);
440 for (; i < m->NbColumns; ++i) {
441 value_assign(old, g);
442 Extended_Euclid(old, m->p[0][i], &c, &b, &g);
443 value_oppose(b, b);
444 for (j = 0; j < m->NbColumns; ++j) {
445 if (j < i) {
446 value_multiply(tmp, m->p[0][j], b);
447 value_division(m->p[i][j], tmp, old);
448 } else if (j == i)
449 value_assign(m->p[i][j], c);
450 else
451 value_set_si(m->p[i][j], 0);
454 ok = value_one_p(g);
455 value_clear(b);
456 value_clear(c);
457 value_clear(g);
458 value_clear(old);
459 value_clear(tmp);
460 return ok;
463 int unimodular_complete(Matrix *M, int row)
465 int r;
466 int ok = 1;
467 Matrix *H, *Q, *U;
469 if (row == 1)
470 return unimodular_complete_1(M);
472 left_hermite(M, &H, &Q, &U);
473 Matrix_Free(U);
474 for (r = 0; ok && r < row; ++r)
475 if (value_notone_p(H->p[r][r]))
476 ok = 0;
477 Matrix_Free(H);
478 for (r = row; r < M->NbRows; ++r)
479 Vector_Copy(Q->p[r], M->p[r], M->NbColumns);
480 Matrix_Free(Q);
481 return ok;
485 * left_hermite may leave positive entries below the main diagonal in H.
486 * This function postprocesses the output of left_hermite to make
487 * the non-zero entries below the main diagonal negative.
489 void neg_left_hermite(Matrix *A, Matrix **H_p, Matrix **Q_p, Matrix **U_p)
491 int row, col, i, j;
492 Matrix *H, *U, *Q;
494 left_hermite(A, &H, &Q, &U);
495 *H_p = H;
496 *Q_p = Q;
497 *U_p = U;
499 for (row = 0, col = 0; col < H->NbColumns; ++col, ++row) {
500 while (value_zero_p(H->p[row][col]))
501 ++row;
502 for (i = 0; i < col; ++i) {
503 if (value_negz_p(H->p[row][i]))
504 continue;
506 /* subtract column col from column i in H and U */
507 for (j = 0; j < H->NbRows; ++j)
508 value_subtract(H->p[j][i], H->p[j][i], H->p[j][col]);
509 for (j = 0; j < U->NbRows; ++j)
510 value_subtract(U->p[j][i], U->p[j][i], U->p[j][col]);
512 /* add row i to row col in Q */
513 for (j = 0; j < Q->NbColumns; ++j)
514 value_addto(Q->p[col][j], Q->p[col][j], Q->p[i][j]);
520 * Returns a full-dimensional polyhedron with the same number
521 * of integer points as P
523 Polyhedron *remove_equalities(Polyhedron *P, unsigned MaxRays)
525 Polyhedron *Q = Polyhedron_Copy(P);
526 unsigned dim = P->Dimension;
527 Matrix *m1, *m2;
528 int i;
530 if (Q->NbEq == 0)
531 return Q;
533 Q = DomainConstraintSimplify(Q, MaxRays);
534 if (emptyQ2(Q))
535 return Q;
537 m1 = Matrix_Alloc(dim, dim);
538 for (i = 0; i < Q->NbEq; ++i)
539 Vector_Copy(Q->Constraint[i]+1, m1->p[i], dim);
541 /* m1 may not be unimodular, but we won't be throwing anything away */
542 unimodular_complete(m1, Q->NbEq);
544 m2 = Matrix_Alloc(dim+1-Q->NbEq, dim+1);
545 for (i = Q->NbEq; i < dim; ++i)
546 Vector_Copy(m1->p[i], m2->p[i-Q->NbEq], dim);
547 value_set_si(m2->p[dim-Q->NbEq][dim], 1);
548 Matrix_Free(m1);
550 P = Polyhedron_Image(Q, m2, MaxRays);
551 Matrix_Free(m2);
552 Polyhedron_Free(Q);
554 return P;
558 * Returns a full-dimensional polyhedron with the same number
559 * of integer points as P
560 * nvar specifies the number of variables
561 * The remaining dimensions are assumed to be parameters
562 * Destroys P
563 * factor is NbEq x (nparam+2) matrix, containing stride constraints
564 * on the parameters; column nparam is the constant;
565 * column nparam+1 is the stride
567 * if factor is NULL, only remove equalities that don't affect
568 * the number of points
570 Polyhedron *remove_equalities_p(Polyhedron *P, unsigned nvar, Matrix **factor,
571 unsigned MaxRays)
573 Value g;
574 Polyhedron *Q;
575 unsigned dim = P->Dimension;
576 Matrix *m1, *m2, *f;
577 int i, j;
579 if (P->NbEq == 0)
580 return P;
582 m1 = Matrix_Alloc(nvar, nvar);
583 P = DomainConstraintSimplify(P, MaxRays);
584 if (factor) {
585 f = Matrix_Alloc(P->NbEq, dim-nvar+2);
586 *factor = f;
588 value_init(g);
589 for (i = 0, j = 0; i < P->NbEq; ++i) {
590 if (First_Non_Zero(P->Constraint[i]+1, nvar) == -1)
591 continue;
593 Vector_Gcd(P->Constraint[i]+1, nvar, &g);
594 if (!factor && value_notone_p(g))
595 continue;
597 if (factor) {
598 Vector_Copy(P->Constraint[i]+1+nvar, f->p[j], dim-nvar+1);
599 value_assign(f->p[j][dim-nvar+1], g);
602 Vector_Copy(P->Constraint[i]+1, m1->p[j], nvar);
604 ++j;
606 value_clear(g);
608 unimodular_complete(m1, j);
610 m2 = Matrix_Alloc(dim+1-j, dim+1);
611 for (i = 0; i < nvar-j ; ++i)
612 Vector_Copy(m1->p[i+j], m2->p[i], nvar);
613 Matrix_Free(m1);
614 for (i = nvar-j; i <= dim-j; ++i)
615 value_set_si(m2->p[i][i+j], 1);
617 Q = Polyhedron_Image(P, m2, MaxRays);
618 Matrix_Free(m2);
619 Polyhedron_Free(P);
621 return Q;
624 void Line_Length(Polyhedron *P, Value *len)
626 Value tmp, pos, neg;
627 int p = 0, n = 0;
628 int i;
630 assert(P->Dimension == 1);
632 if (P->NbEq > 0) {
633 if (mpz_divisible_p(P->Constraint[0][2], P->Constraint[0][1]))
634 value_set_si(*len, 1);
635 else
636 value_set_si(*len, 0);
637 return;
640 value_init(tmp);
641 value_init(pos);
642 value_init(neg);
644 for (i = 0; i < P->NbConstraints; ++i) {
645 value_oppose(tmp, P->Constraint[i][2]);
646 if (value_pos_p(P->Constraint[i][1])) {
647 mpz_cdiv_q(tmp, tmp, P->Constraint[i][1]);
648 if (!p || value_gt(tmp, pos))
649 value_assign(pos, tmp);
650 p = 1;
651 } else if (value_neg_p(P->Constraint[i][1])) {
652 mpz_fdiv_q(tmp, tmp, P->Constraint[i][1]);
653 if (!n || value_lt(tmp, neg))
654 value_assign(neg, tmp);
655 n = 1;
657 if (n && p) {
658 value_subtract(tmp, neg, pos);
659 value_increment(*len, tmp);
660 } else
661 value_set_si(*len, -1);
664 value_clear(tmp);
665 value_clear(pos);
666 value_clear(neg);
670 * Factors the polyhedron P into polyhedra Q_i such that
671 * the number of integer points in P is equal to the product
672 * of the number of integer points in the individual Q_i
674 * If no factors can be found, NULL is returned.
675 * Otherwise, a linked list of the factors is returned.
677 * If there are factors and if T is not NULL, then a matrix will be
678 * returned through T expressing the old variables in terms of the
679 * new variables as they appear in the sequence of factors.
681 * The algorithm works by first computing the Hermite normal form
682 * and then grouping columns linked by one or more constraints together,
683 * where a constraints "links" two or more columns if the constraint
684 * has nonzero coefficients in the columns.
686 Polyhedron* Polyhedron_Factor(Polyhedron *P, unsigned nparam, Matrix **T,
687 unsigned NbMaxRays)
689 int i, j, k;
690 Matrix *M, *H, *Q, *U;
691 int *pos; /* for each column: row position of pivot */
692 int *group; /* group to which a column belongs */
693 int *cnt; /* number of columns in the group */
694 int *rowgroup; /* group to which a constraint belongs */
695 int nvar = P->Dimension - nparam;
696 Polyhedron *F = NULL;
698 if (nvar <= 1)
699 return NULL;
701 NALLOC(pos, nvar);
702 NALLOC(group, nvar);
703 NALLOC(cnt, nvar);
704 NALLOC(rowgroup, P->NbConstraints);
706 M = Matrix_Alloc(P->NbConstraints, nvar);
707 for (i = 0; i < P->NbConstraints; ++i)
708 Vector_Copy(P->Constraint[i]+1, M->p[i], nvar);
709 left_hermite(M, &H, &Q, &U);
710 Matrix_Free(M);
711 Matrix_Free(Q);
713 for (i = 0; i < P->NbConstraints; ++i)
714 rowgroup[i] = -1;
715 for (i = 0, j = 0; i < H->NbColumns; ++i) {
716 for ( ; j < H->NbRows; ++j)
717 if (value_notzero_p(H->p[j][i]))
718 break;
719 pos[i] = j;
721 for (i = 0; i < nvar; ++i) {
722 group[i] = i;
723 cnt[i] = 1;
725 for (i = 0; i < H->NbColumns && cnt[0] < nvar; ++i) {
726 if (pos[i] == H->NbRows)
727 continue; /* A line direction */
728 if (rowgroup[pos[i]] == -1)
729 rowgroup[pos[i]] = i;
730 for (j = pos[i]+1; j < H->NbRows; ++j) {
731 if (value_zero_p(H->p[j][i]))
732 continue;
733 if (rowgroup[j] != -1)
734 continue;
735 rowgroup[j] = group[i];
736 for (k = i+1; k < H->NbColumns && j >= pos[k]; ++k) {
737 int g = group[k];
738 while (cnt[g] == 0)
739 g = group[g];
740 group[k] = g;
741 if (group[k] != group[i] && value_notzero_p(H->p[j][k])) {
742 assert(cnt[group[k]] != 0);
743 assert(cnt[group[i]] != 0);
744 if (group[i] < group[k]) {
745 cnt[group[i]] += cnt[group[k]];
746 cnt[group[k]] = 0;
747 group[k] = group[i];
748 } else {
749 cnt[group[k]] += cnt[group[i]];
750 cnt[group[i]] = 0;
751 group[i] = group[k];
758 if (cnt[0] != nvar) {
759 /* Extract out pure context constraints separately */
760 Polyhedron **next = &F;
761 int tot_d = 0;
762 if (T)
763 *T = Matrix_Alloc(nvar, nvar);
764 for (i = nparam ? -1 : 0; i < nvar; ++i) {
765 int d;
767 if (i == -1) {
768 for (j = 0, k = 0; j < P->NbConstraints; ++j)
769 if (rowgroup[j] == -1) {
770 if (First_Non_Zero(P->Constraint[j]+1+nvar,
771 nparam) == -1)
772 rowgroup[j] = -2;
773 else
774 ++k;
776 if (k == 0)
777 continue;
778 d = 0;
779 } else {
780 if (cnt[i] == 0)
781 continue;
782 d = cnt[i];
783 for (j = 0, k = 0; j < P->NbConstraints; ++j)
784 if (rowgroup[j] >= 0 && group[rowgroup[j]] == i) {
785 rowgroup[j] = i;
786 ++k;
790 if (T)
791 for (j = 0; j < nvar; ++j) {
792 int l, m;
793 for (l = 0, m = 0; m < d; ++l) {
794 if (group[l] != i)
795 continue;
796 value_assign((*T)->p[j][tot_d+m++], U->p[j][l]);
800 M = Matrix_Alloc(k, d+nparam+2);
801 for (j = 0, k = 0; j < P->NbConstraints; ++j) {
802 int l, m;
803 if (rowgroup[j] != i)
804 continue;
805 value_assign(M->p[k][0], P->Constraint[j][0]);
806 for (l = 0, m = 0; m < d; ++l) {
807 if (group[l] != i)
808 continue;
809 value_assign(M->p[k][1+m++], H->p[j][l]);
811 Vector_Copy(P->Constraint[j]+1+nvar, M->p[k]+1+m, nparam+1);
812 ++k;
814 *next = Constraints2Polyhedron(M, NbMaxRays);
815 next = &(*next)->next;
816 Matrix_Free(M);
817 tot_d += d;
820 Matrix_Free(U);
821 Matrix_Free(H);
822 free(pos);
823 free(group);
824 free(cnt);
825 free(rowgroup);
826 return F;
829 /* Computes the intersection of the contexts of a list of factors */
830 Polyhedron *Factor_Context(Polyhedron *F, unsigned nparam, unsigned MaxRays)
832 Polyhedron *Q;
833 Polyhedron *C = NULL;
835 for (Q = F; Q; Q = Q->next) {
836 Polyhedron *QC = Q;
837 Polyhedron *next = Q->next;
838 Q->next = NULL;
840 if (Q->Dimension != nparam)
841 QC = Polyhedron_Project(Q, nparam);
843 if (!C)
844 C = Q == QC ? Polyhedron_Copy(QC) : QC;
845 else {
846 Polyhedron *C2 = C;
847 C = DomainIntersection(C, QC, MaxRays);
848 Polyhedron_Free(C2);
849 if (QC != Q)
850 Polyhedron_Free(QC);
852 Q->next = next;
854 return C;
858 * Project on final dim dimensions
860 Polyhedron* Polyhedron_Project(Polyhedron *P, int dim)
862 int i;
863 int remove = P->Dimension - dim;
864 Matrix *T;
865 Polyhedron *I;
867 if (P->Dimension == dim)
868 return Polyhedron_Copy(P);
870 T = Matrix_Alloc(dim+1, P->Dimension+1);
871 for (i = 0; i < dim+1; ++i)
872 value_set_si(T->p[i][i+remove], 1);
873 I = Polyhedron_Image(P, T, P->NbConstraints);
874 Matrix_Free(T);
875 return I;
878 /* Constructs a new constraint that ensures that
879 * the first constraint is (strictly) smaller than
880 * the second.
882 static void smaller_constraint(Value *a, Value *b, Value *c, int pos, int shift,
883 int len, int strict, Value *tmp)
885 value_oppose(*tmp, b[pos+1]);
886 value_set_si(c[0], 1);
887 Vector_Combine(a+1+shift, b+1+shift, c+1, *tmp, a[pos+1], len-shift-1);
888 if (strict)
889 value_decrement(c[len-shift-1], c[len-shift-1]);
890 ConstraintSimplify(c, c, len-shift, tmp);
894 /* For each pair of lower and upper bounds on the first variable,
895 * calls fn with the set of constraints on the remaining variables
896 * where these bounds are active, i.e., (stricly) larger/smaller than
897 * the other lower/upper bounds, the lower and upper bound and the
898 * call back data.
900 * If the first variable is equal to an affine combination of the
901 * other variables then fn is called with both lower and upper
902 * pointing to the corresponding equality.
904 * If there is no lower (or upper) bound, then NULL is passed
905 * as the corresponding bound.
907 void for_each_lower_upper_bound(Polyhedron *P,
908 for_each_lower_upper_bound_init init,
909 for_each_lower_upper_bound_fn fn,
910 void *cb_data)
912 unsigned dim = P->Dimension;
913 Matrix *M;
914 int *pos;
915 int i, j, p, n, z;
916 int k, l, k2, l2, q;
917 Value g;
919 if (value_zero_p(P->Constraint[0][0]) &&
920 value_notzero_p(P->Constraint[0][1])) {
921 M = Matrix_Alloc(P->NbConstraints-1, dim-1+2);
922 for (i = 1; i < P->NbConstraints; ++i) {
923 value_assign(M->p[i-1][0], P->Constraint[i][0]);
924 Vector_Copy(P->Constraint[i]+2, M->p[i-1]+1, dim);
926 if (init)
927 init(1, cb_data);
928 fn(M, P->Constraint[0], P->Constraint[0], cb_data);
929 Matrix_Free(M);
930 return;
933 value_init(g);
934 pos = ALLOCN(int, P->NbConstraints);
936 for (i = 0, z = 0; i < P->NbConstraints; ++i)
937 if (value_zero_p(P->Constraint[i][1]))
938 pos[P->NbConstraints-1 - z++] = i;
939 /* put those with positive coefficients first; number: p */
940 for (i = 0, p = 0, n = P->NbConstraints-z-1; i < P->NbConstraints; ++i)
941 if (value_pos_p(P->Constraint[i][1]))
942 pos[p++] = i;
943 else if (value_neg_p(P->Constraint[i][1]))
944 pos[n--] = i;
945 n = P->NbConstraints-z-p;
947 if (init)
948 init(p*n, cb_data);
950 M = Matrix_Alloc((p ? p-1 : 0) + (n ? n-1 : 0) + z + 1, dim-1+2);
951 for (i = 0; i < z; ++i) {
952 value_assign(M->p[i][0], P->Constraint[pos[P->NbConstraints-1 - i]][0]);
953 Vector_Copy(P->Constraint[pos[P->NbConstraints-1 - i]]+2,
954 M->p[i]+1, dim);
956 for (k = p ? 0 : -1; k < p; ++k) {
957 for (k2 = 0; k2 < p; ++k2) {
958 if (k2 == k)
959 continue;
960 q = 1 + z + k2 - (k2 > k);
961 smaller_constraint(
962 P->Constraint[pos[k]],
963 P->Constraint[pos[k2]],
964 M->p[q], 0, 1, dim+2, k2 > k, &g);
966 for (l = n ? p : p-1; l < p+n; ++l) {
967 Value *lower;
968 Value *upper;
969 for (l2 = p; l2 < p+n; ++l2) {
970 if (l2 == l)
971 continue;
972 q = 1 + z + l2-1 - (l2 > l);
973 smaller_constraint(
974 P->Constraint[pos[l2]],
975 P->Constraint[pos[l]],
976 M->p[q], 0, 1, dim+2, l2 > l, &g);
978 if (p && n)
979 smaller_constraint(P->Constraint[pos[k]],
980 P->Constraint[pos[l]],
981 M->p[z], 0, 1, dim+2, 0, &g);
982 lower = p ? P->Constraint[pos[k]] : NULL;
983 upper = n ? P->Constraint[pos[l]] : NULL;
984 fn(M, lower, upper, cb_data);
987 Matrix_Free(M);
989 free(pos);
990 value_clear(g);
993 struct section { Polyhedron * D; evalue E; };
995 struct PLL_data {
996 int nd;
997 unsigned MaxRays;
998 Polyhedron *C;
999 evalue mone;
1000 struct section *s;
1003 static void PLL_init(unsigned n, void *cb_data)
1005 struct PLL_data *data = (struct PLL_data *)cb_data;
1007 data->s = ALLOCN(struct section, n);
1010 /* Computes ceil(-coef/abs(d)) */
1011 static evalue* bv_ceil3(Value *coef, int len, Value d, Polyhedron *P)
1013 Value t;
1014 evalue *EP, *f;
1015 Vector *val = Vector_Alloc(len);
1017 value_init(t);
1018 Vector_Oppose(coef, val->p, len);
1019 value_absolute(t, d);
1021 EP = ceiling(val->p, t, len-1, P);
1023 value_clear(t);
1024 Vector_Free(val);
1026 return EP;
1029 static void PLL_cb(Matrix *M, Value *lower, Value *upper, void *cb_data)
1031 struct PLL_data *data = (struct PLL_data *)cb_data;
1032 unsigned dim = M->NbColumns-1;
1033 Matrix *M2;
1034 Polyhedron *T;
1035 evalue *L, *U;
1037 assert(lower);
1038 assert(upper);
1040 M2 = Matrix_Copy(M);
1041 T = Constraints2Polyhedron(M2, data->MaxRays);
1042 Matrix_Free(M2);
1043 data->s[data->nd].D = DomainIntersection(T, data->C, data->MaxRays);
1044 Domain_Free(T);
1046 POL_ENSURE_VERTICES(data->s[data->nd].D);
1047 if (emptyQ(data->s[data->nd].D)) {
1048 Polyhedron_Free(data->s[data->nd].D);
1049 return;
1051 L = bv_ceil3(lower+1+1, dim-1+1, lower[0+1], data->s[data->nd].D);
1052 U = bv_ceil3(upper+1+1, dim-1+1, upper[0+1], data->s[data->nd].D);
1053 eadd(L, U);
1054 eadd(&data->mone, U);
1055 emul(&data->mone, U);
1056 data->s[data->nd].E = *U;
1057 evalue_free(L);
1058 free(U);
1059 ++data->nd;
1062 static evalue *ParamLine_Length_mod(Polyhedron *P, Polyhedron *C, unsigned MaxRays)
1064 unsigned dim = P->Dimension;
1065 unsigned nvar = dim - C->Dimension;
1066 struct PLL_data data;
1067 evalue *F;
1068 int k;
1070 assert(nvar == 1);
1072 value_init(data.mone.d);
1073 evalue_set_si(&data.mone, -1, 1);
1075 data.nd = 0;
1076 data.MaxRays = MaxRays;
1077 data.C = C;
1078 for_each_lower_upper_bound(P, PLL_init, PLL_cb, &data);
1080 F = ALLOC(evalue);
1081 value_init(F->d);
1082 value_set_si(F->d, 0);
1083 F->x.p = new_enode(partition, 2*data.nd, dim-nvar);
1084 for (k = 0; k < data.nd; ++k) {
1085 EVALUE_SET_DOMAIN(F->x.p->arr[2*k], data.s[k].D);
1086 value_clear(F->x.p->arr[2*k+1].d);
1087 F->x.p->arr[2*k+1] = data.s[k].E;
1089 free(data.s);
1091 free_evalue_refs(&data.mone);
1093 return F;
1096 evalue* ParamLine_Length(Polyhedron *P, Polyhedron *C,
1097 struct barvinok_options *options)
1099 evalue* tmp;
1100 tmp = ParamLine_Length_mod(P, C, options->MaxRays);
1101 if (options->lookup_table) {
1102 evalue_mod2table(tmp, C->Dimension);
1103 reduce_evalue(tmp);
1105 return tmp;
1108 Bool isIdentity(Matrix *M)
1110 unsigned i, j;
1111 if (M->NbRows != M->NbColumns)
1112 return False;
1114 for (i = 0;i < M->NbRows; i ++)
1115 for (j = 0; j < M->NbColumns; j ++)
1116 if (i == j) {
1117 if(value_notone_p(M->p[i][j]))
1118 return False;
1119 } else {
1120 if(value_notzero_p(M->p[i][j]))
1121 return False;
1123 return True;
1126 void Param_Polyhedron_Print(FILE* DST, Param_Polyhedron *PP,
1127 const char **param_names)
1129 Param_Domain *P;
1130 Param_Vertices *V;
1132 for(P=PP->D;P;P=P->next) {
1134 /* prints current val. dom. */
1135 fprintf(DST, "---------------------------------------\n");
1136 fprintf(DST, "Domain :\n");
1137 Print_Domain(DST, P->Domain, param_names);
1139 /* scan the vertices */
1140 fprintf(DST, "Vertices :\n");
1141 FORALL_PVertex_in_ParamPolyhedron(V,P,PP) {
1143 /* prints each vertex */
1144 Print_Vertex(DST, V->Vertex, param_names);
1145 fprintf(DST, "\n");
1147 END_FORALL_PVertex_in_ParamPolyhedron;
1151 void Enumeration_Print(FILE *Dst, Enumeration *en, const char **params)
1153 for (; en; en = en->next) {
1154 Print_Domain(Dst, en->ValidityDomain, params);
1155 print_evalue(Dst, &en->EP, params);
1159 void Enumeration_Free(Enumeration *en)
1161 Enumeration *ee;
1163 while( en )
1165 free_evalue_refs( &(en->EP) );
1166 Domain_Free( en->ValidityDomain );
1167 ee = en ->next;
1168 free( en );
1169 en = ee;
1173 void Enumeration_mod2table(Enumeration *en, unsigned nparam)
1175 for (; en; en = en->next) {
1176 evalue_mod2table(&en->EP, nparam);
1177 reduce_evalue(&en->EP);
1181 size_t Enumeration_size(Enumeration *en)
1183 size_t s = 0;
1185 for (; en; en = en->next) {
1186 s += domain_size(en->ValidityDomain);
1187 s += evalue_size(&en->EP);
1189 return s;
1192 /* Check whether every set in D2 is included in some set of D1 */
1193 int DomainIncludes(Polyhedron *D1, Polyhedron *D2)
1195 for ( ; D2; D2 = D2->next) {
1196 Polyhedron *P1;
1197 for (P1 = D1; P1; P1 = P1->next)
1198 if (PolyhedronIncludes(P1, D2))
1199 break;
1200 if (!P1)
1201 return 0;
1203 return 1;
1206 int line_minmax(Polyhedron *I, Value *min, Value *max)
1208 int i;
1210 if (I->NbEq >= 1) {
1211 value_oppose(I->Constraint[0][2], I->Constraint[0][2]);
1212 /* There should never be a remainder here */
1213 if (value_pos_p(I->Constraint[0][1]))
1214 mpz_fdiv_q(*min, I->Constraint[0][2], I->Constraint[0][1]);
1215 else
1216 mpz_fdiv_q(*min, I->Constraint[0][2], I->Constraint[0][1]);
1217 value_assign(*max, *min);
1218 } else for (i = 0; i < I->NbConstraints; ++i) {
1219 if (value_zero_p(I->Constraint[i][1])) {
1220 Polyhedron_Free(I);
1221 return 0;
1224 value_oppose(I->Constraint[i][2], I->Constraint[i][2]);
1225 if (value_pos_p(I->Constraint[i][1]))
1226 mpz_cdiv_q(*min, I->Constraint[i][2], I->Constraint[i][1]);
1227 else
1228 mpz_fdiv_q(*max, I->Constraint[i][2], I->Constraint[i][1]);
1230 Polyhedron_Free(I);
1231 return 1;
1234 /**
1236 PROCEDURES TO COMPUTE ENUMERATION. recursive procedure, recurse for
1237 each imbriquation
1239 @param pos index position of current loop index (1..hdim-1)
1240 @param P loop domain
1241 @param context context values for fixed indices
1242 @param exist number of existential variables
1243 @return the number of integer points in this
1244 polyhedron
1247 void count_points_e (int pos, Polyhedron *P, int exist, int nparam,
1248 Value *context, Value *res)
1250 Value LB, UB, k, c;
1252 if (emptyQ(P)) {
1253 value_set_si(*res, 0);
1254 return;
1257 if (!exist) {
1258 count_points(pos, P, context, res);
1259 return;
1262 value_init(LB); value_init(UB); value_init(k);
1263 value_set_si(LB,0);
1264 value_set_si(UB,0);
1266 if (lower_upper_bounds(pos,P,context,&LB,&UB) !=0) {
1267 /* Problem if UB or LB is INFINITY */
1268 value_clear(LB); value_clear(UB); value_clear(k);
1269 if (pos > P->Dimension - nparam - exist)
1270 value_set_si(*res, 1);
1271 else
1272 value_set_si(*res, -1);
1273 return;
1276 #ifdef EDEBUG1
1277 if (!P->next) {
1278 int i;
1279 for (value_assign(k,LB); value_le(k,UB); value_increment(k,k)) {
1280 fprintf(stderr, "(");
1281 for (i=1; i<pos; i++) {
1282 value_print(stderr,P_VALUE_FMT,context[i]);
1283 fprintf(stderr,",");
1285 value_print(stderr,P_VALUE_FMT,k);
1286 fprintf(stderr,")\n");
1289 #endif
1291 value_set_si(context[pos],0);
1292 if (value_lt(UB,LB)) {
1293 value_clear(LB); value_clear(UB); value_clear(k);
1294 value_set_si(*res, 0);
1295 return;
1297 if (!P->next) {
1298 if (exist)
1299 value_set_si(*res, 1);
1300 else {
1301 value_subtract(k,UB,LB);
1302 value_add_int(k,k,1);
1303 value_assign(*res, k);
1305 value_clear(LB); value_clear(UB); value_clear(k);
1306 return;
1309 /*-----------------------------------------------------------------*/
1310 /* Optimization idea */
1311 /* If inner loops are not a function of k (the current index) */
1312 /* i.e. if P->Constraint[i][pos]==0 for all P following this and */
1313 /* for all i, */
1314 /* Then CNT = (UB-LB+1)*count_points(pos+1, P->next, context) */
1315 /* (skip the for loop) */
1316 /*-----------------------------------------------------------------*/
1318 value_init(c);
1319 value_set_si(*res, 0);
1320 for (value_assign(k,LB);value_le(k,UB);value_increment(k,k)) {
1321 /* Insert k in context */
1322 value_assign(context[pos],k);
1323 count_points_e(pos+1, P->next, exist, nparam, context, &c);
1324 if(value_notmone_p(c))
1325 value_addto(*res, *res, c);
1326 else {
1327 value_set_si(*res, -1);
1328 break;
1330 if (pos > P->Dimension - nparam - exist &&
1331 value_pos_p(*res))
1332 break;
1334 value_clear(c);
1336 #ifdef EDEBUG11
1337 fprintf(stderr,"%d\n",CNT);
1338 #endif
1340 /* Reset context */
1341 value_set_si(context[pos],0);
1342 value_clear(LB); value_clear(UB); value_clear(k);
1343 return;
1344 } /* count_points_e */
1346 int DomainContains(Polyhedron *P, Value *list_args, int len,
1347 unsigned MaxRays, int set)
1349 int i;
1350 Value m;
1352 if (P->Dimension == len)
1353 return in_domain(P, list_args);
1355 assert(set); // assume list_args is large enough
1356 assert((P->Dimension - len) % 2 == 0);
1357 value_init(m);
1358 for (i = 0; i < P->Dimension - len; i += 2) {
1359 int j, k;
1360 for (j = 0 ; j < P->NbEq; ++j)
1361 if (value_notzero_p(P->Constraint[j][1+len+i]))
1362 break;
1363 assert(j < P->NbEq);
1364 value_absolute(m, P->Constraint[j][1+len+i]);
1365 k = First_Non_Zero(P->Constraint[j]+1, len);
1366 assert(k != -1);
1367 assert(First_Non_Zero(P->Constraint[j]+1+k+1, len - k - 1) == -1);
1368 mpz_fdiv_q(list_args[len+i], list_args[k], m);
1369 mpz_fdiv_r(list_args[len+i+1], list_args[k], m);
1371 value_clear(m);
1373 return in_domain(P, list_args);
1376 Polyhedron *DomainConcat(Polyhedron *head, Polyhedron *tail)
1378 Polyhedron *S;
1379 if (!head)
1380 return tail;
1381 for (S = head; S->next; S = S->next)
1383 S->next = tail;
1384 return head;
1387 evalue *barvinok_lexsmaller_ev(Polyhedron *P, Polyhedron *D, unsigned dim,
1388 Polyhedron *C, unsigned MaxRays)
1390 evalue *ranking;
1391 Polyhedron *RC, *RD, *Q;
1392 unsigned nparam = dim + C->Dimension;
1393 unsigned exist;
1394 Polyhedron *CA;
1396 RC = LexSmaller(P, D, dim, C, MaxRays);
1397 RD = RC->next;
1398 RC->next = NULL;
1400 exist = RD->Dimension - nparam - dim;
1401 CA = align_context(RC, RD->Dimension, MaxRays);
1402 Q = DomainIntersection(RD, CA, MaxRays);
1403 Polyhedron_Free(CA);
1404 Domain_Free(RD);
1405 Polyhedron_Free(RC);
1406 RD = Q;
1408 for (Q = RD; Q; Q = Q->next) {
1409 evalue *t;
1410 Polyhedron *next = Q->next;
1411 Q->next = 0;
1413 t = barvinok_enumerate_e(Q, exist, nparam, MaxRays);
1415 if (Q == RD)
1416 ranking = t;
1417 else {
1418 eadd(t, ranking);
1419 evalue_free(t);
1422 Q->next = next;
1425 Domain_Free(RD);
1427 return ranking;
1430 Enumeration *barvinok_lexsmaller(Polyhedron *P, Polyhedron *D, unsigned dim,
1431 Polyhedron *C, unsigned MaxRays)
1433 evalue *EP = barvinok_lexsmaller_ev(P, D, dim, C, MaxRays);
1435 return partition2enumeration(EP);
1438 /* "align" matrix to have nrows by inserting
1439 * the necessary number of rows and an equal number of columns in front
1441 Matrix *align_matrix(Matrix *M, int nrows)
1443 int i;
1444 int newrows = nrows - M->NbRows;
1445 Matrix *M2 = Matrix_Alloc(nrows, newrows + M->NbColumns);
1446 for (i = 0; i < newrows; ++i)
1447 value_set_si(M2->p[i][i], 1);
1448 for (i = 0; i < M->NbRows; ++i)
1449 Vector_Copy(M->p[i], M2->p[newrows+i]+newrows, M->NbColumns);
1450 return M2;
1453 static void print_varlist(FILE *out, int n, char **names)
1455 int i;
1456 fprintf(out, "[");
1457 for (i = 0; i < n; ++i) {
1458 if (i)
1459 fprintf(out, ",");
1460 fprintf(out, "%s", names[i]);
1462 fprintf(out, "]");
1465 static void print_term(FILE *out, Value v, int pos, int dim, int nparam,
1466 char **iter_names, char **param_names, int *first)
1468 if (value_zero_p(v)) {
1469 if (first && *first && pos >= dim + nparam)
1470 fprintf(out, "0");
1471 return;
1474 if (first) {
1475 if (!*first && value_pos_p(v))
1476 fprintf(out, "+");
1477 *first = 0;
1479 if (pos < dim + nparam) {
1480 if (value_mone_p(v))
1481 fprintf(out, "-");
1482 else if (!value_one_p(v))
1483 value_print(out, VALUE_FMT, v);
1484 if (pos < dim)
1485 fprintf(out, "%s", iter_names[pos]);
1486 else
1487 fprintf(out, "%s", param_names[pos-dim]);
1488 } else
1489 value_print(out, VALUE_FMT, v);
1492 char **util_generate_names(int n, const char *prefix)
1494 int i;
1495 int len = (prefix ? strlen(prefix) : 0) + 10;
1496 char **names = ALLOCN(char*, n);
1497 if (!names) {
1498 fprintf(stderr, "ERROR: memory overflow.\n");
1499 exit(1);
1501 for (i = 0; i < n; ++i) {
1502 names[i] = ALLOCN(char, len);
1503 if (!names[i]) {
1504 fprintf(stderr, "ERROR: memory overflow.\n");
1505 exit(1);
1507 if (!prefix)
1508 snprintf(names[i], len, "%d", i);
1509 else
1510 snprintf(names[i], len, "%s%d", prefix, i);
1513 return names;
1516 void util_free_names(int n, char **names)
1518 int i;
1519 for (i = 0; i < n; ++i)
1520 free(names[i]);
1521 free(names);
1524 void Polyhedron_pprint(FILE *out, Polyhedron *P, int dim, int nparam,
1525 char **iter_names, char **param_names)
1527 int i, j;
1528 Value tmp;
1530 assert(dim + nparam == P->Dimension);
1532 value_init(tmp);
1534 fprintf(out, "{ ");
1535 if (nparam) {
1536 print_varlist(out, nparam, param_names);
1537 fprintf(out, " -> ");
1539 print_varlist(out, dim, iter_names);
1540 fprintf(out, " : ");
1542 if (emptyQ2(P))
1543 fprintf(out, "FALSE");
1544 else for (i = 0; i < P->NbConstraints; ++i) {
1545 int first = 1;
1546 int v = First_Non_Zero(P->Constraint[i]+1, P->Dimension);
1547 if (v == -1 && value_pos_p(P->Constraint[i][0]))
1548 continue;
1549 if (i)
1550 fprintf(out, " && ");
1551 if (v == -1 && value_notzero_p(P->Constraint[i][1+P->Dimension]))
1552 fprintf(out, "FALSE");
1553 else if (value_pos_p(P->Constraint[i][v+1])) {
1554 print_term(out, P->Constraint[i][v+1], v, dim, nparam,
1555 iter_names, param_names, NULL);
1556 if (value_zero_p(P->Constraint[i][0]))
1557 fprintf(out, " = ");
1558 else
1559 fprintf(out, " >= ");
1560 for (j = v+1; j <= dim+nparam; ++j) {
1561 value_oppose(tmp, P->Constraint[i][1+j]);
1562 print_term(out, tmp, j, dim, nparam,
1563 iter_names, param_names, &first);
1565 } else {
1566 value_oppose(tmp, P->Constraint[i][1+v]);
1567 print_term(out, tmp, v, dim, nparam,
1568 iter_names, param_names, NULL);
1569 fprintf(out, " <= ");
1570 for (j = v+1; j <= dim+nparam; ++j)
1571 print_term(out, P->Constraint[i][1+j], j, dim, nparam,
1572 iter_names, param_names, &first);
1576 fprintf(out, " }\n");
1578 value_clear(tmp);
1581 /* Construct a cone over P with P placed at x_d = 1, with
1582 * x_d the coordinate of an extra dimension
1584 * It's probably a mistake to depend so much on the internal
1585 * representation. We should probably simply compute the
1586 * vertices/facets first.
1588 Polyhedron *Cone_over_Polyhedron(Polyhedron *P)
1590 unsigned NbConstraints = 0;
1591 unsigned NbRays = 0;
1592 Polyhedron *C;
1593 int i;
1595 if (POL_HAS(P, POL_INEQUALITIES))
1596 NbConstraints = P->NbConstraints + 1;
1597 if (POL_HAS(P, POL_POINTS))
1598 NbRays = P->NbRays + 1;
1600 C = Polyhedron_Alloc(P->Dimension+1, NbConstraints, NbRays);
1601 if (POL_HAS(P, POL_INEQUALITIES)) {
1602 C->NbEq = P->NbEq;
1603 for (i = 0; i < P->NbConstraints; ++i)
1604 Vector_Copy(P->Constraint[i], C->Constraint[i], P->Dimension+2);
1605 /* n >= 0 */
1606 value_set_si(C->Constraint[P->NbConstraints][0], 1);
1607 value_set_si(C->Constraint[P->NbConstraints][1+P->Dimension], 1);
1609 if (POL_HAS(P, POL_POINTS)) {
1610 C->NbBid = P->NbBid;
1611 for (i = 0; i < P->NbRays; ++i)
1612 Vector_Copy(P->Ray[i], C->Ray[i], P->Dimension+2);
1613 /* vertex 0 */
1614 value_set_si(C->Ray[P->NbRays][0], 1);
1615 value_set_si(C->Ray[P->NbRays][1+C->Dimension], 1);
1617 POL_SET(C, POL_VALID);
1618 if (POL_HAS(P, POL_INEQUALITIES))
1619 POL_SET(C, POL_INEQUALITIES);
1620 if (POL_HAS(P, POL_POINTS))
1621 POL_SET(C, POL_POINTS);
1622 if (POL_HAS(P, POL_VERTICES))
1623 POL_SET(C, POL_VERTICES);
1624 return C;
1627 /* Returns a (dim+nparam+1)x((dim-n)+nparam+1) matrix
1628 * mapping the transformed subspace back to the original space.
1629 * n is the number of equalities involving the variables
1630 * (i.e., not purely the parameters).
1631 * The remaining n coordinates in the transformed space would
1632 * have constant (parametric) values and are therefore not
1633 * included in the variables of the new space.
1635 Matrix *compress_variables(Matrix *Equalities, unsigned nparam)
1637 unsigned dim = (Equalities->NbColumns-2) - nparam;
1638 Matrix *M, *H, *Q, *U, *C, *ratH, *invH, *Ul, *T1, *T2, *T;
1639 Value mone;
1640 int n, i, j;
1641 int ok;
1643 for (n = 0; n < Equalities->NbRows; ++n)
1644 if (First_Non_Zero(Equalities->p[n]+1, dim) == -1)
1645 break;
1646 if (n == 0)
1647 return Identity(dim+nparam+1);
1648 value_init(mone);
1649 value_set_si(mone, -1);
1650 M = Matrix_Alloc(n, dim);
1651 C = Matrix_Alloc(n+1, nparam+1);
1652 for (i = 0; i < n; ++i) {
1653 Vector_Copy(Equalities->p[i]+1, M->p[i], dim);
1654 Vector_Scale(Equalities->p[i]+1+dim, C->p[i], mone, nparam+1);
1656 value_set_si(C->p[n][nparam], 1);
1657 left_hermite(M, &H, &Q, &U);
1658 Matrix_Free(M);
1659 Matrix_Free(Q);
1660 value_clear(mone);
1662 ratH = Matrix_Alloc(n+1, n+1);
1663 invH = Matrix_Alloc(n+1, n+1);
1664 for (i = 0; i < n; ++i)
1665 Vector_Copy(H->p[i], ratH->p[i], n);
1666 value_set_si(ratH->p[n][n], 1);
1667 ok = Matrix_Inverse(ratH, invH);
1668 assert(ok);
1669 Matrix_Free(H);
1670 Matrix_Free(ratH);
1671 T1 = Matrix_Alloc(n+1, nparam+1);
1672 Matrix_Product(invH, C, T1);
1673 Matrix_Free(C);
1674 Matrix_Free(invH);
1675 if (value_notone_p(T1->p[n][nparam])) {
1676 for (i = 0; i < n; ++i) {
1677 if (!mpz_divisible_p(T1->p[i][nparam], T1->p[n][nparam])) {
1678 Matrix_Free(T1);
1679 Matrix_Free(U);
1680 return NULL;
1682 /* compress_params should have taken care of this */
1683 for (j = 0; j < nparam; ++j)
1684 assert(mpz_divisible_p(T1->p[i][j], T1->p[n][nparam]));
1685 Vector_AntiScale(T1->p[i], T1->p[i], T1->p[n][nparam], nparam+1);
1687 value_set_si(T1->p[n][nparam], 1);
1689 Ul = Matrix_Alloc(dim+1, n+1);
1690 for (i = 0; i < dim; ++i)
1691 Vector_Copy(U->p[i], Ul->p[i], n);
1692 value_set_si(Ul->p[dim][n], 1);
1693 T2 = Matrix_Alloc(dim+1, nparam+1);
1694 Matrix_Product(Ul, T1, T2);
1695 Matrix_Free(Ul);
1696 Matrix_Free(T1);
1698 T = Matrix_Alloc(dim+nparam+1, (dim-n)+nparam+1);
1699 for (i = 0; i < dim; ++i) {
1700 Vector_Copy(U->p[i]+n, T->p[i], dim-n);
1701 Vector_Copy(T2->p[i], T->p[i]+dim-n, nparam+1);
1703 for (i = 0; i < nparam+1; ++i)
1704 value_set_si(T->p[dim+i][(dim-n)+i], 1);
1705 assert(value_one_p(T2->p[dim][nparam]));
1706 Matrix_Free(U);
1707 Matrix_Free(T2);
1709 return T;
1712 /* Computes the left inverse of an affine embedding M and, if Eq is not NULL,
1713 * the equalities that define the affine subspace onto which M maps
1714 * its argument.
1716 Matrix *left_inverse(Matrix *M, Matrix **Eq)
1718 int i, ok;
1719 Matrix *L, *H, *Q, *U, *ratH, *invH, *Ut, *inv;
1720 Vector *t;
1722 if (M->NbColumns == 1) {
1723 inv = Matrix_Alloc(1, M->NbRows);
1724 value_set_si(inv->p[0][M->NbRows-1], 1);
1725 if (Eq) {
1726 *Eq = Matrix_Alloc(M->NbRows-1, 1+(M->NbRows-1)+1);
1727 for (i = 0; i < M->NbRows-1; ++i) {
1728 value_oppose((*Eq)->p[i][1+i], M->p[M->NbRows-1][0]);
1729 value_assign((*Eq)->p[i][1+(M->NbRows-1)], M->p[i][0]);
1732 return inv;
1734 if (Eq)
1735 *Eq = NULL;
1736 L = Matrix_Alloc(M->NbRows-1, M->NbColumns-1);
1737 for (i = 0; i < L->NbRows; ++i)
1738 Vector_Copy(M->p[i], L->p[i], L->NbColumns);
1739 right_hermite(L, &H, &U, &Q);
1740 Matrix_Free(L);
1741 Matrix_Free(Q);
1742 t = Vector_Alloc(U->NbColumns);
1743 for (i = 0; i < U->NbColumns; ++i)
1744 value_oppose(t->p[i], M->p[i][M->NbColumns-1]);
1745 if (Eq) {
1746 *Eq = Matrix_Alloc(H->NbRows - H->NbColumns, 2 + U->NbColumns);
1747 for (i = 0; i < H->NbRows - H->NbColumns; ++i) {
1748 Vector_Copy(U->p[H->NbColumns+i], (*Eq)->p[i]+1, U->NbColumns);
1749 Inner_Product(U->p[H->NbColumns+i], t->p, U->NbColumns,
1750 (*Eq)->p[i]+1+U->NbColumns);
1753 ratH = Matrix_Alloc(H->NbColumns+1, H->NbColumns+1);
1754 invH = Matrix_Alloc(H->NbColumns+1, H->NbColumns+1);
1755 for (i = 0; i < H->NbColumns; ++i)
1756 Vector_Copy(H->p[i], ratH->p[i], H->NbColumns);
1757 value_set_si(ratH->p[ratH->NbRows-1][ratH->NbColumns-1], 1);
1758 Matrix_Free(H);
1759 ok = Matrix_Inverse(ratH, invH);
1760 assert(ok);
1761 Matrix_Free(ratH);
1762 Ut = Matrix_Alloc(invH->NbRows, U->NbColumns+1);
1763 for (i = 0; i < Ut->NbRows-1; ++i) {
1764 Vector_Copy(U->p[i], Ut->p[i], U->NbColumns);
1765 Inner_Product(U->p[i], t->p, U->NbColumns, &Ut->p[i][Ut->NbColumns-1]);
1767 Matrix_Free(U);
1768 Vector_Free(t);
1769 value_set_si(Ut->p[Ut->NbRows-1][Ut->NbColumns-1], 1);
1770 inv = Matrix_Alloc(invH->NbRows, Ut->NbColumns);
1771 Matrix_Product(invH, Ut, inv);
1772 Matrix_Free(Ut);
1773 Matrix_Free(invH);
1774 return inv;
1777 /* Check whether all rays are revlex positive in the parameters
1779 int Polyhedron_has_revlex_positive_rays(Polyhedron *P, unsigned nparam)
1781 int r;
1782 for (r = 0; r < P->NbRays; ++r) {
1783 int i;
1784 if (value_notzero_p(P->Ray[r][P->Dimension+1]))
1785 continue;
1786 for (i = P->Dimension-1; i >= P->Dimension-nparam; --i) {
1787 if (value_neg_p(P->Ray[r][i+1]))
1788 return 0;
1789 if (value_pos_p(P->Ray[r][i+1]))
1790 break;
1792 /* A ray independent of the parameters */
1793 if (i < P->Dimension-nparam)
1794 return 0;
1796 return 1;
1799 static Polyhedron *Recession_Cone(Polyhedron *P, unsigned nparam, unsigned MaxRays)
1801 int i;
1802 unsigned nvar = P->Dimension - nparam;
1803 Matrix *M = Matrix_Alloc(P->NbConstraints, 1 + nvar + 1);
1804 Polyhedron *R;
1805 for (i = 0; i < P->NbConstraints; ++i)
1806 Vector_Copy(P->Constraint[i], M->p[i], 1+nvar);
1807 R = Constraints2Polyhedron(M, MaxRays);
1808 Matrix_Free(M);
1809 return R;
1812 int Polyhedron_is_unbounded(Polyhedron *P, unsigned nparam, unsigned MaxRays)
1814 int i;
1815 int is_unbounded;
1816 Polyhedron *R = Recession_Cone(P, nparam, MaxRays);
1817 POL_ENSURE_VERTICES(R);
1818 if (R->NbBid == 0)
1819 for (i = 0; i < R->NbRays; ++i)
1820 if (value_zero_p(R->Ray[i][1+R->Dimension]))
1821 break;
1822 is_unbounded = R->NbBid > 0 || i < R->NbRays;
1823 Polyhedron_Free(R);
1824 return is_unbounded;
1827 static void SwapColumns(Value **V, int n, int i, int j)
1829 int r;
1831 for (r = 0; r < n; ++r)
1832 value_swap(V[r][i], V[r][j]);
1835 void Polyhedron_ExchangeColumns(Polyhedron *P, int Column1, int Column2)
1837 SwapColumns(P->Constraint, P->NbConstraints, Column1, Column2);
1838 SwapColumns(P->Ray, P->NbRays, Column1, Column2);
1839 if (P->NbEq) {
1840 Matrix M;
1841 Polyhedron_Matrix_View(P, &M, P->NbConstraints);
1842 Gauss(&M, P->NbEq, P->Dimension+1);
1846 /* perform transposition inline; assumes M is a square matrix */
1847 void Matrix_Transposition(Matrix *M)
1849 int i, j;
1851 assert(M->NbRows == M->NbColumns);
1852 for (i = 0; i < M->NbRows; ++i)
1853 for (j = i+1; j < M->NbColumns; ++j)
1854 value_swap(M->p[i][j], M->p[j][i]);
1857 /* Matrix "view" of first rows rows */
1858 void Polyhedron_Matrix_View(Polyhedron *P, Matrix *M, unsigned rows)
1860 M->NbRows = rows;
1861 M->NbColumns = P->Dimension+2;
1862 M->p_Init = P->p_Init;
1863 M->p = P->Constraint;