isl_map_polylib.c: directly include required headers
[barvinok.git] / util.c
blob46c0b223e0f61255fdf3f1df3a5c55d42fa9587f
1 #include <stdlib.h>
2 #include <assert.h>
3 #include <isl/val_gmp.h>
4 #include <isl_set_polylib.h>
5 #include <barvinok/util.h>
6 #include <barvinok/options.h>
7 #include <polylib/ranking.h>
8 #include "config.h"
9 #include "lattice_point.h"
11 #define ALLOC(type) (type*)malloc(sizeof(type))
12 #define ALLOCN(type,n) (type*)malloc((n) * sizeof(type))
14 #ifdef __GNUC__
15 #define NALLOC(p,n) p = (typeof(p))malloc((n) * sizeof(*p))
16 #else
17 #define NALLOC(p,n) p = (void *)malloc((n) * sizeof(*p))
18 #endif
20 void manual_count(Polyhedron *P, Value* result)
22 isl_ctx *ctx = isl_ctx_alloc();
23 isl_space *dim;
24 isl_set *set;
25 isl_val *v;
26 int nvar = P->Dimension;
28 dim = isl_space_set_alloc(ctx, 0, nvar);
29 set = isl_set_new_from_polylib(P, dim);
31 v = isl_set_count_val(set);
32 isl_val_get_num_gmp(v, *result);
33 isl_val_free(v);
35 isl_set_free(set);
36 isl_ctx_free(ctx);
38 assert(v);
41 #include <barvinok/evalue.h>
42 #include <barvinok/util.h>
43 #include <barvinok/barvinok.h>
45 /* Return random value between 0 and max-1 inclusive
47 int random_int(int max) {
48 return (int) (((double)(max))*rand()/(RAND_MAX+1.0));
51 Polyhedron *Polyhedron_Read(unsigned MaxRays)
53 int vertices = 0;
54 unsigned NbRows, NbColumns;
55 Matrix *M;
56 Polyhedron *P;
57 char s[128];
59 while (fgets(s, sizeof(s), stdin)) {
60 if (*s == '#')
61 continue;
62 if (strncasecmp(s, "vertices", sizeof("vertices")-1) == 0)
63 vertices = 1;
64 if (sscanf(s, "%u %u", &NbRows, &NbColumns) == 2)
65 break;
67 if (feof(stdin))
68 return NULL;
69 M = Matrix_Alloc(NbRows,NbColumns);
70 Matrix_Read_Input(M);
71 if (vertices)
72 P = Rays2Polyhedron(M, MaxRays);
73 else
74 P = Constraints2Polyhedron(M, MaxRays);
75 Matrix_Free(M);
76 return P;
79 /* Inplace polarization
81 void Polyhedron_Polarize(Polyhedron *P)
83 unsigned NbRows;
84 int i;
85 Value **q;
87 POL_ENSURE_FACETS(P);
88 POL_ENSURE_VERTICES(P);
89 NbRows = P->NbConstraints + P->NbRays;
90 q = (Value **)malloc(NbRows * sizeof(Value *));
91 assert(q);
92 for (i = 0; i < P->NbRays; ++i)
93 q[i] = P->Ray[i];
94 for (; i < NbRows; ++i)
95 q[i] = P->Constraint[i-P->NbRays];
96 P->NbConstraints = NbRows - P->NbConstraints;
97 P->NbRays = NbRows - P->NbRays;
98 free(P->Constraint);
99 P->Constraint = q;
100 P->Ray = q + P->NbConstraints;
104 * Rather general polar
105 * We can optimize it significantly if we assume that
106 * P includes zero
108 * Also, we calculate the polar as defined in Schrijver
109 * The opposite should probably work as well and would
110 * eliminate the need for multiplying by -1
112 Polyhedron* Polyhedron_Polar(Polyhedron *P, unsigned NbMaxRays)
114 int i;
115 Value mone;
116 unsigned dim = P->Dimension + 2;
117 Matrix *M = Matrix_Alloc(P->NbRays, dim);
119 assert(M);
120 value_init(mone);
121 value_set_si(mone, -1);
122 for (i = 0; i < P->NbRays; ++i) {
123 Vector_Scale(P->Ray[i], M->p[i], mone, dim);
124 value_multiply(M->p[i][0], M->p[i][0], mone);
125 value_multiply(M->p[i][dim-1], M->p[i][dim-1], mone);
127 P = Constraints2Polyhedron(M, NbMaxRays);
128 assert(P);
129 Matrix_Free(M);
130 value_clear(mone);
131 return P;
135 * Returns the supporting cone of P at the vertex with index v
137 Polyhedron* supporting_cone(Polyhedron *P, int v)
139 Matrix *M;
140 Value tmp;
141 int i, n, j;
142 unsigned char *supporting = (unsigned char *)malloc(P->NbConstraints);
143 unsigned dim = P->Dimension + 2;
145 assert(v >=0 && v < P->NbRays);
146 assert(value_pos_p(P->Ray[v][dim-1]));
147 assert(supporting);
149 value_init(tmp);
150 for (i = 0, n = 0; i < P->NbConstraints; ++i) {
151 Inner_Product(P->Constraint[i] + 1, P->Ray[v] + 1, dim - 1, &tmp);
152 if ((supporting[i] = value_zero_p(tmp)))
153 ++n;
155 assert(n >= dim - 2);
156 value_clear(tmp);
157 M = Matrix_Alloc(n, dim);
158 assert(M);
159 for (i = 0, j = 0; i < P->NbConstraints; ++i)
160 if (supporting[i]) {
161 value_set_si(M->p[j][dim-1], 0);
162 Vector_Copy(P->Constraint[i], M->p[j++], dim-1);
164 free(supporting);
165 P = Constraints2Polyhedron(M, P->NbRays+1);
166 assert(P);
167 Matrix_Free(M);
168 return P;
171 #define INT_BITS (sizeof(unsigned) * 8)
173 unsigned *supporting_constraints(Matrix *Constraints, Param_Vertices *v, int *n)
175 Value lcm, tmp, tmp2;
176 unsigned dim = Constraints->NbColumns;
177 unsigned nparam = v->Vertex->NbColumns - 2;
178 unsigned nvar = dim - nparam - 2;
179 int len = (Constraints->NbRows+INT_BITS-1)/INT_BITS;
180 unsigned *supporting = (unsigned *)calloc(len, sizeof(unsigned));
181 int i, j;
182 Vector *row;
183 int ix;
184 unsigned bx;
186 assert(supporting);
187 row = Vector_Alloc(nparam+1);
188 assert(row);
189 value_init(lcm);
190 value_init(tmp);
191 value_init(tmp2);
192 value_set_si(lcm, 1);
193 for (i = 0, *n = 0, ix = 0, bx = MSB; i < Constraints->NbRows; ++i) {
194 Vector_Set(row->p, 0, nparam+1);
195 for (j = 0 ; j < nvar; ++j) {
196 value_set_si(tmp, 1);
197 value_assign(tmp2, Constraints->p[i][j+1]);
198 if (value_ne(lcm, v->Vertex->p[j][nparam+1])) {
199 value_assign(tmp, lcm);
200 value_lcm(lcm, lcm, v->Vertex->p[j][nparam+1]);
201 value_division(tmp, lcm, tmp);
202 value_multiply(tmp2, tmp2, lcm);
203 value_division(tmp2, tmp2, v->Vertex->p[j][nparam+1]);
205 Vector_Combine(row->p, v->Vertex->p[j], row->p,
206 tmp, tmp2, nparam+1);
208 value_set_si(tmp, 1);
209 Vector_Combine(row->p, Constraints->p[i]+1+nvar, row->p, tmp, lcm, nparam+1);
210 for (j = 0; j < nparam+1; ++j)
211 if (value_notzero_p(row->p[j]))
212 break;
213 if (j == nparam + 1) {
214 supporting[ix] |= bx;
215 ++*n;
217 NEXT(ix, bx);
219 assert(*n >= nvar);
220 value_clear(tmp);
221 value_clear(tmp2);
222 value_clear(lcm);
223 Vector_Free(row);
225 return supporting;
228 Polyhedron* supporting_cone_p(Polyhedron *P, Param_Vertices *v)
230 Matrix *M;
231 unsigned dim = P->Dimension + 2;
232 unsigned nparam = v->Vertex->NbColumns - 2;
233 unsigned nvar = dim - nparam - 2;
234 int i, n, j;
235 int ix;
236 unsigned bx;
237 unsigned *supporting;
238 Matrix View;
240 Polyhedron_Matrix_View(P, &View, P->NbConstraints);
241 supporting = supporting_constraints(&View, v, &n);
242 M = Matrix_Alloc(n, nvar+2);
243 assert(M);
244 for (i = 0, j = 0, ix = 0, bx = MSB; i < P->NbConstraints; ++i) {
245 if (supporting[ix] & bx) {
246 value_set_si(M->p[j][nvar+1], 0);
247 Vector_Copy(P->Constraint[i], M->p[j++], nvar+1);
249 NEXT(ix, bx);
251 free(supporting);
252 P = Constraints2Polyhedron(M, P->NbRays+1);
253 assert(P);
254 Matrix_Free(M);
255 return P;
258 Polyhedron* triangulate_cone(Polyhedron *P, unsigned NbMaxCons)
260 struct barvinok_options *options = barvinok_options_new_with_defaults();
261 options->MaxRays = NbMaxCons;
262 P = triangulate_cone_with_options(P, options);
263 barvinok_options_free(options);
264 return P;
267 Polyhedron* triangulate_cone_with_options(Polyhedron *P,
268 struct barvinok_options *options)
270 const static int MAX_TRY=10;
271 int i, j, r, n, t;
272 Value tmp;
273 unsigned dim = P->Dimension;
274 Matrix *M = Matrix_Alloc(P->NbRays+1, dim+3);
275 Matrix *M2, *M3;
276 Polyhedron *L, *R, *T;
277 assert(P->NbEq == 0);
279 L = NULL;
280 R = NULL;
281 value_init(tmp);
283 Vector_Set(M->p[0]+1, 0, dim+1);
284 value_set_si(M->p[0][0], 1);
285 value_set_si(M->p[0][dim+2], 1);
286 Vector_Set(M->p[P->NbRays]+1, 0, dim+2);
287 value_set_si(M->p[P->NbRays][0], 1);
288 value_set_si(M->p[P->NbRays][dim+1], 1);
290 for (i = 0, r = 1; i < P->NbRays; ++i) {
291 if (value_notzero_p(P->Ray[i][dim+1]))
292 continue;
293 Vector_Copy(P->Ray[i], M->p[r], dim+1);
294 value_set_si(M->p[r][dim+2], 0);
295 ++r;
298 M2 = Matrix_Alloc(dim+1, dim+2);
300 t = 0;
301 if (options->try_Delaunay_triangulation) {
302 /* Delaunay triangulation */
303 for (r = 1; r < P->NbRays; ++r) {
304 Inner_Product(M->p[r]+1, M->p[r]+1, dim, &tmp);
305 value_assign(M->p[r][dim+1], tmp);
307 M3 = Matrix_Copy(M);
308 L = Rays2Polyhedron(M3, options->MaxRays);
309 Matrix_Free(M3);
310 ++t;
311 } else {
312 try_again:
313 /* Usually R should still be 0 */
314 Domain_Free(R);
315 Polyhedron_Free(L);
316 for (r = 1; r < P->NbRays; ++r) {
317 value_set_si(M->p[r][dim+1], random_int((t+1)*dim*P->NbRays)+1);
319 M3 = Matrix_Copy(M);
320 L = Rays2Polyhedron(M3, options->MaxRays);
321 Matrix_Free(M3);
322 ++t;
324 assert(t <= MAX_TRY);
326 R = NULL;
327 n = 0;
329 POL_ENSURE_FACETS(L);
330 for (i = 0; i < L->NbConstraints; ++i) {
331 /* Ignore perpendicular facets, i.e., facets with 0 z-coordinate */
332 if (value_negz_p(L->Constraint[i][dim+1]))
333 continue;
334 if (value_notzero_p(L->Constraint[i][dim+2]))
335 continue;
336 for (j = 1, r = 1; j < M->NbRows; ++j) {
337 Inner_Product(M->p[j]+1, L->Constraint[i]+1, dim+1, &tmp);
338 if (value_notzero_p(tmp))
339 continue;
340 if (r > dim)
341 goto try_again;
342 Vector_Copy(M->p[j]+1, M2->p[r]+1, dim);
343 value_set_si(M2->p[r][0], 1);
344 value_set_si(M2->p[r][dim+1], 0);
345 ++r;
347 assert(r == dim+1);
348 Vector_Set(M2->p[0]+1, 0, dim);
349 value_set_si(M2->p[0][0], 1);
350 value_set_si(M2->p[0][dim+1], 1);
351 T = Rays2Polyhedron(M2, P->NbConstraints+1);
352 T->next = R;
353 R = T;
354 ++n;
356 Matrix_Free(M2);
358 Polyhedron_Free(L);
359 value_clear(tmp);
360 Matrix_Free(M);
362 return R;
365 void check_triangulization(Polyhedron *P, Polyhedron *T)
367 Polyhedron *C, *D, *E, *F, *G, *U;
368 for (C = T; C; C = C->next) {
369 if (C == T)
370 U = C;
371 else
372 U = DomainConvex(DomainUnion(U, C, 100), 100);
373 for (D = C->next; D; D = D->next) {
374 F = C->next;
375 G = D->next;
376 C->next = NULL;
377 D->next = NULL;
378 E = DomainIntersection(C, D, 600);
379 assert(E->NbRays == 0 || E->NbEq >= 1);
380 Polyhedron_Free(E);
381 C->next = F;
382 D->next = G;
385 assert(PolyhedronIncludes(U, P));
386 assert(PolyhedronIncludes(P, U));
389 /* Computes x, y and g such that g = gcd(a,b) and a*x+b*y = g */
390 void Extended_Euclid(Value a, Value b, Value *x, Value *y, Value *g)
392 Value c, d, e, f, tmp;
394 value_init(c);
395 value_init(d);
396 value_init(e);
397 value_init(f);
398 value_init(tmp);
399 value_absolute(c, a);
400 value_absolute(d, b);
401 value_set_si(e, 1);
402 value_set_si(f, 0);
403 while(value_pos_p(d)) {
404 value_division(tmp, c, d);
405 value_multiply(tmp, tmp, f);
406 value_subtract(e, e, tmp);
407 value_division(tmp, c, d);
408 value_multiply(tmp, tmp, d);
409 value_subtract(c, c, tmp);
410 value_swap(c, d);
411 value_swap(e, f);
413 value_assign(*g, c);
414 if (value_zero_p(a))
415 value_set_si(*x, 0);
416 else if (value_pos_p(a))
417 value_assign(*x, e);
418 else value_oppose(*x, e);
419 if (value_zero_p(b))
420 value_set_si(*y, 0);
421 else {
422 value_multiply(tmp, a, *x);
423 value_subtract(tmp, c, tmp);
424 value_division(*y, tmp, b);
426 value_clear(c);
427 value_clear(d);
428 value_clear(e);
429 value_clear(f);
430 value_clear(tmp);
433 static int unimodular_complete_1(Matrix *m)
435 Value g, b, c, old, tmp;
436 unsigned i, j;
437 int ok;
439 value_init(b);
440 value_init(c);
441 value_init(g);
442 value_init(old);
443 value_init(tmp);
444 value_assign(g, m->p[0][0]);
445 for (i = 1; value_zero_p(g) && i < m->NbColumns; ++i) {
446 for (j = 0; j < m->NbColumns; ++j) {
447 if (j == i-1)
448 value_set_si(m->p[i][j], 1);
449 else
450 value_set_si(m->p[i][j], 0);
452 value_assign(g, m->p[0][i]);
454 for (; i < m->NbColumns; ++i) {
455 value_assign(old, g);
456 Extended_Euclid(old, m->p[0][i], &c, &b, &g);
457 value_oppose(b, b);
458 for (j = 0; j < m->NbColumns; ++j) {
459 if (j < i) {
460 value_multiply(tmp, m->p[0][j], b);
461 value_division(m->p[i][j], tmp, old);
462 } else if (j == i)
463 value_assign(m->p[i][j], c);
464 else
465 value_set_si(m->p[i][j], 0);
468 ok = value_one_p(g);
469 value_clear(b);
470 value_clear(c);
471 value_clear(g);
472 value_clear(old);
473 value_clear(tmp);
474 return ok;
477 int unimodular_complete(Matrix *M, int row)
479 int r;
480 int ok = 1;
481 Matrix *H, *Q, *U;
483 if (row == 1)
484 return unimodular_complete_1(M);
486 left_hermite(M, &H, &Q, &U);
487 Matrix_Free(U);
488 for (r = 0; ok && r < row; ++r)
489 if (value_notone_p(H->p[r][r]))
490 ok = 0;
491 Matrix_Free(H);
492 for (r = row; r < M->NbRows; ++r)
493 Vector_Copy(Q->p[r], M->p[r], M->NbColumns);
494 Matrix_Free(Q);
495 return ok;
499 * left_hermite may leave positive entries below the main diagonal in H.
500 * This function postprocesses the output of left_hermite to make
501 * the non-zero entries below the main diagonal negative.
503 void neg_left_hermite(Matrix *A, Matrix **H_p, Matrix **Q_p, Matrix **U_p)
505 int row, col, i, j;
506 Matrix *H, *U, *Q;
508 left_hermite(A, &H, &Q, &U);
509 *H_p = H;
510 *Q_p = Q;
511 *U_p = U;
513 for (row = 0, col = 0; col < H->NbColumns; ++col, ++row) {
514 while (value_zero_p(H->p[row][col]))
515 ++row;
516 for (i = 0; i < col; ++i) {
517 if (value_negz_p(H->p[row][i]))
518 continue;
520 /* subtract column col from column i in H and U */
521 for (j = 0; j < H->NbRows; ++j)
522 value_subtract(H->p[j][i], H->p[j][i], H->p[j][col]);
523 for (j = 0; j < U->NbRows; ++j)
524 value_subtract(U->p[j][i], U->p[j][i], U->p[j][col]);
526 /* add row i to row col in Q */
527 for (j = 0; j < Q->NbColumns; ++j)
528 value_addto(Q->p[col][j], Q->p[col][j], Q->p[i][j]);
534 * Returns a full-dimensional polyhedron with the same number
535 * of integer points as P
537 Polyhedron *remove_equalities(Polyhedron *P, unsigned MaxRays)
539 Matrix M;
540 Matrix *T;
541 Polyhedron *Q = Polyhedron_Copy(P);
543 if (Q->NbEq == 0)
544 return Q;
546 Q = DomainConstraintSimplify(Q, MaxRays);
547 if (emptyQ2(Q))
548 return Q;
550 Polyhedron_Matrix_View(Q, &M, Q->NbEq);
551 T = compress_variables(&M, 0);
553 if (!T)
554 P = NULL;
555 else {
556 P = Polyhedron_Preimage(Q, T, MaxRays);
557 Matrix_Free(T);
560 Polyhedron_Free(Q);
562 return P;
566 * Returns a full-dimensional polyhedron with the same number
567 * of integer points as P
568 * nvar specifies the number of variables
569 * The remaining dimensions are assumed to be parameters
570 * Destroys P
571 * factor is NbEq x (nparam+2) matrix, containing stride constraints
572 * on the parameters; column nparam is the constant;
573 * column nparam+1 is the stride
575 * if factor is NULL, only remove equalities that don't affect
576 * the number of points
578 Polyhedron *remove_equalities_p(Polyhedron *P, unsigned nvar, Matrix **factor,
579 unsigned MaxRays)
581 Value g;
582 Polyhedron *Q;
583 unsigned dim = P->Dimension;
584 Matrix *m1, *m2, *f;
585 int i, j;
587 if (P->NbEq == 0)
588 return P;
590 m1 = Matrix_Alloc(nvar, nvar);
591 P = DomainConstraintSimplify(P, MaxRays);
592 if (factor) {
593 f = Matrix_Alloc(P->NbEq, dim-nvar+2);
594 *factor = f;
596 value_init(g);
597 for (i = 0, j = 0; i < P->NbEq; ++i) {
598 if (First_Non_Zero(P->Constraint[i]+1, nvar) == -1)
599 continue;
601 Vector_Gcd(P->Constraint[i]+1, nvar, &g);
602 if (!factor && value_notone_p(g))
603 continue;
605 if (factor) {
606 Vector_Copy(P->Constraint[i]+1+nvar, f->p[j], dim-nvar+1);
607 value_assign(f->p[j][dim-nvar+1], g);
610 Vector_Copy(P->Constraint[i]+1, m1->p[j], nvar);
612 ++j;
614 value_clear(g);
616 unimodular_complete(m1, j);
618 m2 = Matrix_Alloc(dim+1-j, dim+1);
619 for (i = 0; i < nvar-j ; ++i)
620 Vector_Copy(m1->p[i+j], m2->p[i], nvar);
621 Matrix_Free(m1);
622 for (i = nvar-j; i <= dim-j; ++i)
623 value_set_si(m2->p[i][i+j], 1);
625 Q = Polyhedron_Image(P, m2, MaxRays);
626 Matrix_Free(m2);
627 Polyhedron_Free(P);
629 return Q;
632 void Line_Length(Polyhedron *P, Value *len)
634 Value tmp, pos, neg;
635 int p = 0, n = 0;
636 int i;
638 assert(P->Dimension == 1);
640 if (P->NbEq > 0) {
641 if (mpz_divisible_p(P->Constraint[0][2], P->Constraint[0][1]))
642 value_set_si(*len, 1);
643 else
644 value_set_si(*len, 0);
645 return;
648 value_init(tmp);
649 value_init(pos);
650 value_init(neg);
652 for (i = 0; i < P->NbConstraints; ++i) {
653 value_oppose(tmp, P->Constraint[i][2]);
654 if (value_pos_p(P->Constraint[i][1])) {
655 mpz_cdiv_q(tmp, tmp, P->Constraint[i][1]);
656 if (!p || value_gt(tmp, pos))
657 value_assign(pos, tmp);
658 p = 1;
659 } else if (value_neg_p(P->Constraint[i][1])) {
660 mpz_fdiv_q(tmp, tmp, P->Constraint[i][1]);
661 if (!n || value_lt(tmp, neg))
662 value_assign(neg, tmp);
663 n = 1;
665 if (n && p) {
666 value_subtract(tmp, neg, pos);
667 value_increment(*len, tmp);
668 } else
669 value_set_si(*len, -1);
672 value_clear(tmp);
673 value_clear(pos);
674 value_clear(neg);
677 /* Update group[k] to the group column k belongs to.
678 * When merging two groups, only the group of the current
679 * group leader is changed. Here we change the group of
680 * the other members to also point to the group that the
681 * old group leader now points to.
683 static void update_group(int *group, int *cnt, int k)
685 int g = group[k];
686 while (cnt[g] == 0)
687 g = group[g];
688 group[k] = g;
692 * Factors the polyhedron P into polyhedra Q_i such that
693 * the number of integer points in P is equal to the product
694 * of the number of integer points in the individual Q_i
696 * If no factors can be found, NULL is returned.
697 * Otherwise, a linked list of the factors is returned.
699 * If there are factors and if T is not NULL, then a matrix will be
700 * returned through T expressing the old variables in terms of the
701 * new variables as they appear in the sequence of factors.
703 * The algorithm works by first computing the Hermite normal form
704 * and then grouping columns linked by one or more constraints together,
705 * where a constraints "links" two or more columns if the constraint
706 * has nonzero coefficients in the columns.
708 Polyhedron* Polyhedron_Factor(Polyhedron *P, unsigned nparam, Matrix **T,
709 unsigned NbMaxRays)
711 int i, j, k;
712 Matrix *M, *H, *Q, *U;
713 int *pos; /* for each column: row position of pivot */
714 int *group; /* group to which a column belongs */
715 int *cnt; /* number of columns in the group */
716 int *rowgroup; /* group to which a constraint belongs */
717 int nvar = P->Dimension - nparam;
718 Polyhedron *F = NULL;
720 if (nvar <= 1)
721 return NULL;
723 NALLOC(pos, nvar);
724 NALLOC(group, nvar);
725 NALLOC(cnt, nvar);
726 NALLOC(rowgroup, P->NbConstraints);
728 M = Matrix_Alloc(P->NbConstraints, nvar);
729 for (i = 0; i < P->NbConstraints; ++i)
730 Vector_Copy(P->Constraint[i]+1, M->p[i], nvar);
731 left_hermite(M, &H, &Q, &U);
732 Matrix_Free(M);
733 Matrix_Free(Q);
735 for (i = 0; i < P->NbConstraints; ++i)
736 rowgroup[i] = -1;
737 for (i = 0, j = 0; i < H->NbColumns; ++i) {
738 for ( ; j < H->NbRows; ++j)
739 if (value_notzero_p(H->p[j][i]))
740 break;
741 pos[i] = j;
743 for (i = 0; i < nvar; ++i) {
744 group[i] = i;
745 cnt[i] = 1;
747 for (i = 0; i < H->NbColumns && cnt[0] < nvar; ++i) {
748 if (pos[i] == H->NbRows)
749 continue; /* A line direction */
750 if (rowgroup[pos[i]] == -1)
751 rowgroup[pos[i]] = i;
752 for (j = pos[i]+1; j < H->NbRows; ++j) {
753 if (value_zero_p(H->p[j][i]))
754 continue;
755 if (rowgroup[j] != -1)
756 continue;
757 rowgroup[j] = group[i];
758 for (k = i+1; k < H->NbColumns && j >= pos[k]; ++k) {
759 update_group(group, cnt, k);
760 update_group(group, cnt, i);
761 if (group[k] != group[i] && value_notzero_p(H->p[j][k])) {
762 assert(cnt[group[k]] != 0);
763 assert(cnt[group[i]] != 0);
764 if (group[i] < group[k]) {
765 cnt[group[i]] += cnt[group[k]];
766 cnt[group[k]] = 0;
767 group[group[k]] = group[i];
768 } else {
769 cnt[group[k]] += cnt[group[i]];
770 cnt[group[i]] = 0;
771 group[group[i]] = group[k];
777 for (i = 1; i < nvar; ++i)
778 update_group(group, cnt, i);
780 if (cnt[0] != nvar) {
781 /* Extract out pure context constraints separately */
782 Polyhedron **next = &F;
783 int tot_d = 0;
784 if (T)
785 *T = Matrix_Alloc(nvar, nvar);
786 for (i = nparam ? -1 : 0; i < nvar; ++i) {
787 int d;
789 if (i == -1) {
790 for (j = 0, k = 0; j < P->NbConstraints; ++j)
791 if (rowgroup[j] == -1) {
792 if (First_Non_Zero(P->Constraint[j]+1+nvar,
793 nparam) == -1)
794 rowgroup[j] = -2;
795 else
796 ++k;
798 if (k == 0)
799 continue;
800 d = 0;
801 } else {
802 if (cnt[i] == 0)
803 continue;
804 d = cnt[i];
805 for (j = 0, k = 0; j < P->NbConstraints; ++j)
806 if (rowgroup[j] >= 0 && group[rowgroup[j]] == i) {
807 rowgroup[j] = i;
808 ++k;
812 if (T)
813 for (j = 0; j < nvar; ++j) {
814 int l, m;
815 for (l = 0, m = 0; m < d; ++l) {
816 if (group[l] != i)
817 continue;
818 value_assign((*T)->p[j][tot_d+m++], U->p[j][l]);
822 M = Matrix_Alloc(k, d+nparam+2);
823 for (j = 0, k = 0; j < P->NbConstraints; ++j) {
824 int l, m;
825 if (rowgroup[j] != i)
826 continue;
827 value_assign(M->p[k][0], P->Constraint[j][0]);
828 for (l = 0, m = 0; m < d; ++l) {
829 if (group[l] != i)
830 continue;
831 value_assign(M->p[k][1+m++], H->p[j][l]);
833 Vector_Copy(P->Constraint[j]+1+nvar, M->p[k]+1+m, nparam+1);
834 ++k;
836 *next = Constraints2Polyhedron(M, NbMaxRays);
837 next = &(*next)->next;
838 Matrix_Free(M);
839 tot_d += d;
842 Matrix_Free(U);
843 Matrix_Free(H);
844 free(pos);
845 free(group);
846 free(cnt);
847 free(rowgroup);
848 return F;
851 /* Computes the intersection of the contexts of a list of factors */
852 Polyhedron *Factor_Context(Polyhedron *F, unsigned nparam, unsigned MaxRays)
854 Polyhedron *Q;
855 Polyhedron *C = NULL;
857 for (Q = F; Q; Q = Q->next) {
858 Polyhedron *QC = Q;
859 Polyhedron *next = Q->next;
860 Q->next = NULL;
862 if (Q->Dimension != nparam)
863 QC = Polyhedron_Project(Q, nparam);
865 if (!C)
866 C = Q == QC ? Polyhedron_Copy(QC) : QC;
867 else {
868 Polyhedron *C2 = C;
869 C = DomainIntersection(C, QC, MaxRays);
870 Polyhedron_Free(C2);
871 if (QC != Q)
872 Polyhedron_Free(QC);
874 Q->next = next;
876 return C;
880 * Project on final dim dimensions
882 Polyhedron* Polyhedron_Project(Polyhedron *P, int dim)
884 int i;
885 int remove = P->Dimension - dim;
886 Matrix *T;
887 Polyhedron *I;
889 if (P->Dimension == dim)
890 return Polyhedron_Copy(P);
892 T = Matrix_Alloc(dim+1, P->Dimension+1);
893 for (i = 0; i < dim+1; ++i)
894 value_set_si(T->p[i][i+remove], 1);
895 I = Polyhedron_Image(P, T, P->NbConstraints);
896 Matrix_Free(T);
897 return I;
900 /* Constructs a new constraint that ensures that
901 * the first constraint is (strictly) smaller than
902 * the second.
904 static void smaller_constraint(Value *a, Value *b, Value *c, int pos, int shift,
905 int len, int strict, Value *tmp)
907 value_oppose(*tmp, b[pos+1]);
908 value_set_si(c[0], 1);
909 Vector_Combine(a+1+shift, b+1+shift, c+1, *tmp, a[pos+1], len-shift-1);
910 if (strict)
911 value_decrement(c[len-shift-1], c[len-shift-1]);
912 ConstraintSimplify(c, c, len-shift, tmp);
916 /* For each pair of lower and upper bounds on the first variable,
917 * calls fn with the set of constraints on the remaining variables
918 * where these bounds are active, i.e., (stricly) larger/smaller than
919 * the other lower/upper bounds, the lower and upper bound and the
920 * call back data.
922 * If the first variable is equal to an affine combination of the
923 * other variables then fn is called with both lower and upper
924 * pointing to the corresponding equality.
926 * If there is no lower (or upper) bound, then NULL is passed
927 * as the corresponding bound.
929 void for_each_lower_upper_bound(Polyhedron *P,
930 for_each_lower_upper_bound_init init,
931 for_each_lower_upper_bound_fn fn,
932 void *cb_data)
934 unsigned dim = P->Dimension;
935 Matrix *M;
936 int *pos;
937 int i, p, n, z;
938 int k, l, k2, l2, q;
939 Value g;
941 if (value_zero_p(P->Constraint[0][0]) &&
942 value_notzero_p(P->Constraint[0][1])) {
943 M = Matrix_Alloc(P->NbConstraints-1, dim-1+2);
944 for (i = 1; i < P->NbConstraints; ++i) {
945 value_assign(M->p[i-1][0], P->Constraint[i][0]);
946 Vector_Copy(P->Constraint[i]+2, M->p[i-1]+1, dim);
948 if (init)
949 init(1, cb_data);
950 fn(M, P->Constraint[0], P->Constraint[0], cb_data);
951 Matrix_Free(M);
952 return;
955 value_init(g);
956 pos = ALLOCN(int, P->NbConstraints);
958 for (i = 0, z = 0; i < P->NbConstraints; ++i)
959 if (value_zero_p(P->Constraint[i][1]))
960 pos[P->NbConstraints-1 - z++] = i;
961 /* put those with positive coefficients first; number: p */
962 for (i = 0, p = 0, n = P->NbConstraints-z-1; i < P->NbConstraints; ++i)
963 if (value_pos_p(P->Constraint[i][1]))
964 pos[p++] = i;
965 else if (value_neg_p(P->Constraint[i][1]))
966 pos[n--] = i;
967 n = P->NbConstraints-z-p;
969 if (init)
970 init(p*n, cb_data);
972 M = Matrix_Alloc((p ? p-1 : 0) + (n ? n-1 : 0) + z + 1, dim-1+2);
973 for (i = 0; i < z; ++i) {
974 value_assign(M->p[i][0], P->Constraint[pos[P->NbConstraints-1 - i]][0]);
975 Vector_Copy(P->Constraint[pos[P->NbConstraints-1 - i]]+2,
976 M->p[i]+1, dim);
978 for (k = p ? 0 : -1; k < p; ++k) {
979 for (k2 = 0; k2 < p; ++k2) {
980 if (k2 == k)
981 continue;
982 q = 1 + z + k2 - (k2 > k);
983 smaller_constraint(
984 P->Constraint[pos[k]],
985 P->Constraint[pos[k2]],
986 M->p[q], 0, 1, dim+2, k2 > k, &g);
988 for (l = n ? p : p-1; l < p+n; ++l) {
989 Value *lower;
990 Value *upper;
991 for (l2 = p; l2 < p+n; ++l2) {
992 if (l2 == l)
993 continue;
994 q = 1 + z + l2-1 - (l2 > l);
995 smaller_constraint(
996 P->Constraint[pos[l2]],
997 P->Constraint[pos[l]],
998 M->p[q], 0, 1, dim+2, l2 > l, &g);
1000 if (p && n)
1001 smaller_constraint(P->Constraint[pos[k]],
1002 P->Constraint[pos[l]],
1003 M->p[z], 0, 1, dim+2, 0, &g);
1004 lower = p ? P->Constraint[pos[k]] : NULL;
1005 upper = n ? P->Constraint[pos[l]] : NULL;
1006 fn(M, lower, upper, cb_data);
1009 Matrix_Free(M);
1011 free(pos);
1012 value_clear(g);
1015 struct section { Polyhedron * D; evalue E; };
1017 struct PLL_data {
1018 int nd;
1019 unsigned MaxRays;
1020 Polyhedron *C;
1021 evalue mone;
1022 struct section *s;
1025 static void PLL_init(unsigned n, void *cb_data)
1027 struct PLL_data *data = (struct PLL_data *)cb_data;
1029 data->s = ALLOCN(struct section, n);
1032 /* Computes ceil(-coef/abs(d)) */
1033 static evalue* bv_ceil3(Value *coef, int len, Value d, Polyhedron *P)
1035 Value t;
1036 evalue *EP;
1037 Vector *val = Vector_Alloc(len);
1039 value_init(t);
1040 Vector_Oppose(coef, val->p, len);
1041 value_absolute(t, d);
1043 EP = ceiling(val->p, t, len-1, P);
1045 value_clear(t);
1046 Vector_Free(val);
1048 return EP;
1051 static void PLL_cb(Matrix *M, Value *lower, Value *upper, void *cb_data)
1053 struct PLL_data *data = (struct PLL_data *)cb_data;
1054 unsigned dim = M->NbColumns-1;
1055 Matrix *M2;
1056 Polyhedron *T;
1057 evalue *L, *U;
1059 assert(lower);
1060 assert(upper);
1062 M2 = Matrix_Copy(M);
1063 T = Constraints2Polyhedron(M2, data->MaxRays);
1064 Matrix_Free(M2);
1065 data->s[data->nd].D = DomainIntersection(T, data->C, data->MaxRays);
1066 Domain_Free(T);
1068 POL_ENSURE_VERTICES(data->s[data->nd].D);
1069 if (emptyQ(data->s[data->nd].D)) {
1070 Polyhedron_Free(data->s[data->nd].D);
1071 return;
1073 L = bv_ceil3(lower+1+1, dim-1+1, lower[0+1], data->s[data->nd].D);
1074 U = bv_ceil3(upper+1+1, dim-1+1, upper[0+1], data->s[data->nd].D);
1075 eadd(L, U);
1076 eadd(&data->mone, U);
1077 emul(&data->mone, U);
1078 data->s[data->nd].E = *U;
1079 evalue_free(L);
1080 free(U);
1081 ++data->nd;
1084 static evalue *ParamLine_Length_mod(Polyhedron *P, Polyhedron *C, unsigned MaxRays)
1086 unsigned dim = P->Dimension;
1087 unsigned nvar = dim - C->Dimension;
1088 struct PLL_data data;
1089 evalue *F;
1090 int k;
1092 assert(nvar == 1);
1094 value_init(data.mone.d);
1095 evalue_set_si(&data.mone, -1, 1);
1097 data.nd = 0;
1098 data.MaxRays = MaxRays;
1099 data.C = C;
1100 for_each_lower_upper_bound(P, PLL_init, PLL_cb, &data);
1102 free_evalue_refs(&data.mone);
1104 if (data.nd == 0) {
1105 free(data.s);
1106 return evalue_zero();
1109 F = ALLOC(evalue);
1110 value_init(F->d);
1111 value_set_si(F->d, 0);
1112 F->x.p = new_enode(partition, 2*data.nd, dim-nvar);
1113 for (k = 0; k < data.nd; ++k) {
1114 EVALUE_SET_DOMAIN(F->x.p->arr[2*k], data.s[k].D);
1115 value_clear(F->x.p->arr[2*k+1].d);
1116 F->x.p->arr[2*k+1] = data.s[k].E;
1118 free(data.s);
1120 return F;
1123 evalue* ParamLine_Length(Polyhedron *P, Polyhedron *C,
1124 struct barvinok_options *options)
1126 evalue* tmp;
1127 tmp = ParamLine_Length_mod(P, C, options->MaxRays);
1128 if (options->lookup_table) {
1129 evalue_mod2table(tmp, C->Dimension);
1130 reduce_evalue(tmp);
1132 return tmp;
1135 Bool isIdentity(Matrix *M)
1137 unsigned i, j;
1138 if (M->NbRows != M->NbColumns)
1139 return False;
1141 for (i = 0;i < M->NbRows; i ++)
1142 for (j = 0; j < M->NbColumns; j ++)
1143 if (i == j) {
1144 if(value_notone_p(M->p[i][j]))
1145 return False;
1146 } else {
1147 if(value_notzero_p(M->p[i][j]))
1148 return False;
1150 return True;
1153 void Param_Polyhedron_Print(FILE* DST, Param_Polyhedron *PP,
1154 const char **param_names)
1156 Param_Domain *P;
1157 Param_Vertices *V;
1159 for(P=PP->D;P;P=P->next) {
1161 /* prints current val. dom. */
1162 fprintf(DST, "---------------------------------------\n");
1163 fprintf(DST, "Domain :\n");
1164 Print_Domain(DST, P->Domain, param_names);
1166 /* scan the vertices */
1167 fprintf(DST, "Vertices :\n");
1168 FORALL_PVertex_in_ParamPolyhedron(V,P,PP) {
1170 /* prints each vertex */
1171 Print_Vertex(DST, V->Vertex, param_names);
1172 fprintf(DST, "\n");
1174 END_FORALL_PVertex_in_ParamPolyhedron;
1178 void Enumeration_Print(FILE *Dst, Enumeration *en, const char **params)
1180 for (; en; en = en->next) {
1181 Print_Domain(Dst, en->ValidityDomain, params);
1182 print_evalue(Dst, &en->EP, params);
1186 void Enumeration_Free(Enumeration *en)
1188 Enumeration *ee;
1190 while( en )
1192 free_evalue_refs( &(en->EP) );
1193 Domain_Free( en->ValidityDomain );
1194 ee = en ->next;
1195 free( en );
1196 en = ee;
1200 void Enumeration_mod2table(Enumeration *en, unsigned nparam)
1202 for (; en; en = en->next) {
1203 evalue_mod2table(&en->EP, nparam);
1204 reduce_evalue(&en->EP);
1208 size_t Enumeration_size(Enumeration *en)
1210 size_t s = 0;
1212 for (; en; en = en->next) {
1213 s += domain_size(en->ValidityDomain);
1214 s += evalue_size(&en->EP);
1216 return s;
1219 /* Check whether every set in D2 is included in some set of D1 */
1220 int DomainIncludes(Polyhedron *D1, Polyhedron *D2)
1222 for ( ; D2; D2 = D2->next) {
1223 Polyhedron *P1;
1224 for (P1 = D1; P1; P1 = P1->next)
1225 if (PolyhedronIncludes(P1, D2))
1226 break;
1227 if (!P1)
1228 return 0;
1230 return 1;
1233 int line_minmax(Polyhedron *I, Value *min, Value *max)
1235 int i;
1237 if (I->NbEq >= 1) {
1238 value_oppose(I->Constraint[0][2], I->Constraint[0][2]);
1239 /* There should never be a remainder here */
1240 if (value_pos_p(I->Constraint[0][1]))
1241 mpz_fdiv_q(*min, I->Constraint[0][2], I->Constraint[0][1]);
1242 else
1243 mpz_fdiv_q(*min, I->Constraint[0][2], I->Constraint[0][1]);
1244 value_assign(*max, *min);
1245 } else for (i = 0; i < I->NbConstraints; ++i) {
1246 if (value_zero_p(I->Constraint[i][1])) {
1247 Polyhedron_Free(I);
1248 return 0;
1251 value_oppose(I->Constraint[i][2], I->Constraint[i][2]);
1252 if (value_pos_p(I->Constraint[i][1]))
1253 mpz_cdiv_q(*min, I->Constraint[i][2], I->Constraint[i][1]);
1254 else
1255 mpz_fdiv_q(*max, I->Constraint[i][2], I->Constraint[i][1]);
1257 Polyhedron_Free(I);
1258 return 1;
1261 int DomainContains(Polyhedron *P, Value *list_args, int len,
1262 unsigned MaxRays, int set)
1264 int i;
1265 Value m;
1267 if (P->Dimension == len)
1268 return in_domain(P, list_args);
1270 assert(set); // assume list_args is large enough
1271 assert((P->Dimension - len) % 2 == 0);
1272 value_init(m);
1273 for (i = 0; i < P->Dimension - len; i += 2) {
1274 int j, k;
1275 for (j = 0 ; j < P->NbEq; ++j)
1276 if (value_notzero_p(P->Constraint[j][1+len+i]))
1277 break;
1278 assert(j < P->NbEq);
1279 value_absolute(m, P->Constraint[j][1+len+i]);
1280 k = First_Non_Zero(P->Constraint[j]+1, len);
1281 assert(k != -1);
1282 assert(First_Non_Zero(P->Constraint[j]+1+k+1, len - k - 1) == -1);
1283 mpz_fdiv_q(list_args[len+i], list_args[k], m);
1284 mpz_fdiv_r(list_args[len+i+1], list_args[k], m);
1286 value_clear(m);
1288 return in_domain(P, list_args);
1291 Polyhedron *DomainConcat(Polyhedron *head, Polyhedron *tail)
1293 Polyhedron *S;
1294 if (!head)
1295 return tail;
1296 for (S = head; S->next; S = S->next)
1298 S->next = tail;
1299 return head;
1302 evalue *barvinok_lexsmaller_ev(Polyhedron *P, Polyhedron *D, unsigned dim,
1303 Polyhedron *C, unsigned MaxRays)
1305 evalue *ranking;
1306 Polyhedron *RC, *RD, *Q;
1307 unsigned nparam = dim + C->Dimension;
1308 unsigned exist;
1309 Polyhedron *CA;
1311 RC = LexSmaller(P, D, dim, C, MaxRays);
1312 RD = RC->next;
1313 RC->next = NULL;
1315 exist = RD->Dimension - nparam - dim;
1316 CA = align_context(RC, RD->Dimension, MaxRays);
1317 Q = DomainIntersection(RD, CA, MaxRays);
1318 Polyhedron_Free(CA);
1319 Domain_Free(RD);
1320 Polyhedron_Free(RC);
1321 RD = Q;
1323 for (Q = RD; Q; Q = Q->next) {
1324 evalue *t;
1325 Polyhedron *next = Q->next;
1326 Q->next = 0;
1328 t = barvinok_enumerate_e(Q, exist, nparam, MaxRays);
1330 if (Q == RD)
1331 ranking = t;
1332 else {
1333 eadd(t, ranking);
1334 evalue_free(t);
1337 Q->next = next;
1340 Domain_Free(RD);
1342 return ranking;
1345 Enumeration *barvinok_lexsmaller(Polyhedron *P, Polyhedron *D, unsigned dim,
1346 Polyhedron *C, unsigned MaxRays)
1348 evalue *EP = barvinok_lexsmaller_ev(P, D, dim, C, MaxRays);
1350 return partition2enumeration(EP);
1353 /* "align" matrix to have nrows by inserting
1354 * the necessary number of rows and an equal number of columns in front
1356 Matrix *align_matrix(Matrix *M, int nrows)
1358 int i;
1359 int newrows = nrows - M->NbRows;
1360 Matrix *M2 = Matrix_Alloc(nrows, newrows + M->NbColumns);
1361 for (i = 0; i < newrows; ++i)
1362 value_set_si(M2->p[i][i], 1);
1363 for (i = 0; i < M->NbRows; ++i)
1364 Vector_Copy(M->p[i], M2->p[newrows+i]+newrows, M->NbColumns);
1365 return M2;
1368 static void print_varlist(FILE *out, int n, char **names)
1370 int i;
1371 fprintf(out, "[");
1372 for (i = 0; i < n; ++i) {
1373 if (i)
1374 fprintf(out, ",");
1375 fprintf(out, "%s", names[i]);
1377 fprintf(out, "]");
1380 static void print_term(FILE *out, Value v, int pos, int dim, int nparam,
1381 char **iter_names, char **param_names, int *first)
1383 if (value_zero_p(v)) {
1384 if (first && *first && pos >= dim + nparam)
1385 fprintf(out, "0");
1386 return;
1389 if (first) {
1390 if (!*first && value_pos_p(v))
1391 fprintf(out, "+");
1392 *first = 0;
1394 if (pos < dim + nparam) {
1395 if (value_mone_p(v))
1396 fprintf(out, "-");
1397 else if (!value_one_p(v))
1398 value_print(out, VALUE_FMT, v);
1399 if (pos < dim)
1400 fprintf(out, "%s", iter_names[pos]);
1401 else
1402 fprintf(out, "%s", param_names[pos-dim]);
1403 } else
1404 value_print(out, VALUE_FMT, v);
1407 char **util_generate_names(int n, const char *prefix)
1409 int i;
1410 int len = (prefix ? strlen(prefix) : 0) + 10;
1411 char **names = ALLOCN(char*, n);
1412 if (!names) {
1413 fprintf(stderr, "ERROR: memory overflow.\n");
1414 exit(1);
1416 for (i = 0; i < n; ++i) {
1417 names[i] = ALLOCN(char, len);
1418 if (!names[i]) {
1419 fprintf(stderr, "ERROR: memory overflow.\n");
1420 exit(1);
1422 if (!prefix)
1423 snprintf(names[i], len, "%d", i);
1424 else
1425 snprintf(names[i], len, "%s%d", prefix, i);
1428 return names;
1431 void util_free_names(int n, char **names)
1433 int i;
1434 for (i = 0; i < n; ++i)
1435 free(names[i]);
1436 free(names);
1439 void Polyhedron_pprint(FILE *out, Polyhedron *P, int dim, int nparam,
1440 char **iter_names, char **param_names)
1442 int i, j;
1443 Value tmp;
1445 assert(dim + nparam == P->Dimension);
1447 value_init(tmp);
1449 fprintf(out, "{ ");
1450 if (nparam) {
1451 print_varlist(out, nparam, param_names);
1452 fprintf(out, " -> ");
1454 print_varlist(out, dim, iter_names);
1455 fprintf(out, " : ");
1457 if (emptyQ2(P))
1458 fprintf(out, "FALSE");
1459 else for (i = 0; i < P->NbConstraints; ++i) {
1460 int first = 1;
1461 int v = First_Non_Zero(P->Constraint[i]+1, P->Dimension);
1462 if (v == -1 && value_pos_p(P->Constraint[i][0]))
1463 continue;
1464 if (i)
1465 fprintf(out, " && ");
1466 if (v == -1 && value_notzero_p(P->Constraint[i][1+P->Dimension]))
1467 fprintf(out, "FALSE");
1468 else if (value_pos_p(P->Constraint[i][v+1])) {
1469 print_term(out, P->Constraint[i][v+1], v, dim, nparam,
1470 iter_names, param_names, NULL);
1471 if (value_zero_p(P->Constraint[i][0]))
1472 fprintf(out, " = ");
1473 else
1474 fprintf(out, " >= ");
1475 for (j = v+1; j <= dim+nparam; ++j) {
1476 value_oppose(tmp, P->Constraint[i][1+j]);
1477 print_term(out, tmp, j, dim, nparam,
1478 iter_names, param_names, &first);
1480 } else {
1481 value_oppose(tmp, P->Constraint[i][1+v]);
1482 print_term(out, tmp, v, dim, nparam,
1483 iter_names, param_names, NULL);
1484 fprintf(out, " <= ");
1485 for (j = v+1; j <= dim+nparam; ++j)
1486 print_term(out, P->Constraint[i][1+j], j, dim, nparam,
1487 iter_names, param_names, &first);
1491 fprintf(out, " }\n");
1493 value_clear(tmp);
1496 /* Construct a cone over P with P placed at x_d = 1, with
1497 * x_d the coordinate of an extra dimension
1499 * It's probably a mistake to depend so much on the internal
1500 * representation. We should probably simply compute the
1501 * vertices/facets first.
1503 Polyhedron *Cone_over_Polyhedron(Polyhedron *P)
1505 unsigned NbConstraints = 0;
1506 unsigned NbRays = 0;
1507 Polyhedron *C;
1508 int i;
1510 if (POL_HAS(P, POL_INEQUALITIES))
1511 NbConstraints = P->NbConstraints + 1;
1512 if (POL_HAS(P, POL_POINTS))
1513 NbRays = P->NbRays + 1;
1515 C = Polyhedron_Alloc(P->Dimension+1, NbConstraints, NbRays);
1516 if (POL_HAS(P, POL_INEQUALITIES)) {
1517 C->NbEq = P->NbEq;
1518 for (i = 0; i < P->NbConstraints; ++i)
1519 Vector_Copy(P->Constraint[i], C->Constraint[i], P->Dimension+2);
1520 /* n >= 0 */
1521 value_set_si(C->Constraint[P->NbConstraints][0], 1);
1522 value_set_si(C->Constraint[P->NbConstraints][1+P->Dimension], 1);
1524 if (POL_HAS(P, POL_POINTS)) {
1525 C->NbBid = P->NbBid;
1526 for (i = 0; i < P->NbRays; ++i)
1527 Vector_Copy(P->Ray[i], C->Ray[i], P->Dimension+2);
1528 /* vertex 0 */
1529 value_set_si(C->Ray[P->NbRays][0], 1);
1530 value_set_si(C->Ray[P->NbRays][1+C->Dimension], 1);
1532 POL_SET(C, POL_VALID);
1533 if (POL_HAS(P, POL_INEQUALITIES))
1534 POL_SET(C, POL_INEQUALITIES);
1535 if (POL_HAS(P, POL_POINTS))
1536 POL_SET(C, POL_POINTS);
1537 if (POL_HAS(P, POL_VERTICES))
1538 POL_SET(C, POL_VERTICES);
1539 return C;
1542 /* Returns a (dim+nparam+1)x((dim-n)+nparam+1) matrix
1543 * mapping the transformed subspace back to the original space.
1544 * n is the number of equalities involving the variables
1545 * (i.e., not purely the parameters).
1546 * The remaining n coordinates in the transformed space would
1547 * have constant (parametric) values and are therefore not
1548 * included in the variables of the new space.
1550 Matrix *compress_variables(Matrix *Equalities, unsigned nparam)
1552 unsigned dim = (Equalities->NbColumns-2) - nparam;
1553 Matrix *M, *H, *Q, *U, *C, *ratH, *invH, *Ul, *T1, *T2, *T;
1554 Value mone;
1555 int n, i, j;
1556 int ok;
1558 for (n = 0; n < Equalities->NbRows; ++n)
1559 if (First_Non_Zero(Equalities->p[n]+1, dim) == -1)
1560 break;
1561 if (n == 0)
1562 return Identity(dim+nparam+1);
1563 value_init(mone);
1564 value_set_si(mone, -1);
1565 M = Matrix_Alloc(n, dim);
1566 C = Matrix_Alloc(n+1, nparam+1);
1567 for (i = 0; i < n; ++i) {
1568 Vector_Copy(Equalities->p[i]+1, M->p[i], dim);
1569 Vector_Scale(Equalities->p[i]+1+dim, C->p[i], mone, nparam+1);
1571 value_set_si(C->p[n][nparam], 1);
1572 left_hermite(M, &H, &Q, &U);
1573 Matrix_Free(M);
1574 Matrix_Free(Q);
1575 value_clear(mone);
1577 ratH = Matrix_Alloc(n+1, n+1);
1578 invH = Matrix_Alloc(n+1, n+1);
1579 for (i = 0; i < n; ++i)
1580 Vector_Copy(H->p[i], ratH->p[i], n);
1581 value_set_si(ratH->p[n][n], 1);
1582 ok = Matrix_Inverse(ratH, invH);
1583 assert(ok);
1584 Matrix_Free(H);
1585 Matrix_Free(ratH);
1586 T1 = Matrix_Alloc(n+1, nparam+1);
1587 Matrix_Product(invH, C, T1);
1588 Matrix_Free(C);
1589 Matrix_Free(invH);
1590 if (value_notone_p(T1->p[n][nparam])) {
1591 for (i = 0; i < n; ++i) {
1592 if (!mpz_divisible_p(T1->p[i][nparam], T1->p[n][nparam])) {
1593 Matrix_Free(T1);
1594 Matrix_Free(U);
1595 return NULL;
1597 /* compress_params should have taken care of this */
1598 for (j = 0; j < nparam; ++j)
1599 assert(mpz_divisible_p(T1->p[i][j], T1->p[n][nparam]));
1600 Vector_AntiScale(T1->p[i], T1->p[i], T1->p[n][nparam], nparam+1);
1602 value_set_si(T1->p[n][nparam], 1);
1604 Ul = Matrix_Alloc(dim+1, n+1);
1605 for (i = 0; i < dim; ++i)
1606 Vector_Copy(U->p[i], Ul->p[i], n);
1607 value_set_si(Ul->p[dim][n], 1);
1608 T2 = Matrix_Alloc(dim+1, nparam+1);
1609 Matrix_Product(Ul, T1, T2);
1610 Matrix_Free(Ul);
1611 Matrix_Free(T1);
1613 T = Matrix_Alloc(dim+nparam+1, (dim-n)+nparam+1);
1614 for (i = 0; i < dim; ++i) {
1615 Vector_Copy(U->p[i]+n, T->p[i], dim-n);
1616 Vector_Copy(T2->p[i], T->p[i]+dim-n, nparam+1);
1618 for (i = 0; i < nparam+1; ++i)
1619 value_set_si(T->p[dim+i][(dim-n)+i], 1);
1620 assert(value_one_p(T2->p[dim][nparam]));
1621 Matrix_Free(U);
1622 Matrix_Free(T2);
1624 return T;
1627 /* Computes the left inverse of an affine embedding M and, if Eq is not NULL,
1628 * the equalities that define the affine subspace onto which M maps
1629 * its argument.
1631 Matrix *left_inverse(Matrix *M, Matrix **Eq)
1633 int i, ok;
1634 Matrix *L, *H, *Q, *U, *ratH, *invH, *Ut, *inv;
1635 Vector *t;
1637 if (M->NbColumns == 1) {
1638 inv = Matrix_Alloc(1, M->NbRows);
1639 value_set_si(inv->p[0][M->NbRows-1], 1);
1640 if (Eq) {
1641 *Eq = Matrix_Alloc(M->NbRows-1, 1+(M->NbRows-1)+1);
1642 for (i = 0; i < M->NbRows-1; ++i) {
1643 value_oppose((*Eq)->p[i][1+i], M->p[M->NbRows-1][0]);
1644 value_assign((*Eq)->p[i][1+(M->NbRows-1)], M->p[i][0]);
1647 return inv;
1649 if (Eq)
1650 *Eq = NULL;
1651 L = Matrix_Alloc(M->NbRows-1, M->NbColumns-1);
1652 for (i = 0; i < L->NbRows; ++i)
1653 Vector_Copy(M->p[i], L->p[i], L->NbColumns);
1654 right_hermite(L, &H, &U, &Q);
1655 Matrix_Free(L);
1656 Matrix_Free(Q);
1657 t = Vector_Alloc(U->NbColumns);
1658 for (i = 0; i < U->NbColumns; ++i)
1659 value_oppose(t->p[i], M->p[i][M->NbColumns-1]);
1660 if (Eq) {
1661 *Eq = Matrix_Alloc(H->NbRows - H->NbColumns, 2 + U->NbColumns);
1662 for (i = 0; i < H->NbRows - H->NbColumns; ++i) {
1663 Vector_Copy(U->p[H->NbColumns+i], (*Eq)->p[i]+1, U->NbColumns);
1664 Inner_Product(U->p[H->NbColumns+i], t->p, U->NbColumns,
1665 (*Eq)->p[i]+1+U->NbColumns);
1668 ratH = Matrix_Alloc(H->NbColumns+1, H->NbColumns+1);
1669 invH = Matrix_Alloc(H->NbColumns+1, H->NbColumns+1);
1670 for (i = 0; i < H->NbColumns; ++i)
1671 Vector_Copy(H->p[i], ratH->p[i], H->NbColumns);
1672 value_set_si(ratH->p[ratH->NbRows-1][ratH->NbColumns-1], 1);
1673 Matrix_Free(H);
1674 ok = Matrix_Inverse(ratH, invH);
1675 assert(ok);
1676 Matrix_Free(ratH);
1677 Ut = Matrix_Alloc(invH->NbRows, U->NbColumns+1);
1678 for (i = 0; i < Ut->NbRows-1; ++i) {
1679 Vector_Copy(U->p[i], Ut->p[i], U->NbColumns);
1680 Inner_Product(U->p[i], t->p, U->NbColumns, &Ut->p[i][Ut->NbColumns-1]);
1682 Matrix_Free(U);
1683 Vector_Free(t);
1684 value_set_si(Ut->p[Ut->NbRows-1][Ut->NbColumns-1], 1);
1685 inv = Matrix_Alloc(invH->NbRows, Ut->NbColumns);
1686 Matrix_Product(invH, Ut, inv);
1687 Matrix_Free(Ut);
1688 Matrix_Free(invH);
1689 return inv;
1692 /* Check whether all rays are revlex positive in the parameters
1694 int Polyhedron_has_revlex_positive_rays(Polyhedron *P, unsigned nparam)
1696 int r;
1697 for (r = 0; r < P->NbRays; ++r) {
1698 int i;
1699 if (value_notzero_p(P->Ray[r][P->Dimension+1]))
1700 continue;
1701 for (i = P->Dimension-1; i >= P->Dimension-nparam; --i) {
1702 if (value_neg_p(P->Ray[r][i+1]))
1703 return 0;
1704 if (value_pos_p(P->Ray[r][i+1]))
1705 break;
1707 /* A ray independent of the parameters */
1708 if (i < P->Dimension-nparam)
1709 return 0;
1711 return 1;
1714 static Polyhedron *Recession_Cone(Polyhedron *P, unsigned nparam, unsigned MaxRays)
1716 int i;
1717 unsigned nvar = P->Dimension - nparam;
1718 Matrix *M = Matrix_Alloc(P->NbConstraints, 1 + nvar + 1);
1719 Polyhedron *R;
1720 for (i = 0; i < P->NbConstraints; ++i)
1721 Vector_Copy(P->Constraint[i], M->p[i], 1+nvar);
1722 R = Constraints2Polyhedron(M, MaxRays);
1723 Matrix_Free(M);
1724 return R;
1727 int Polyhedron_is_unbounded(Polyhedron *P, unsigned nparam, unsigned MaxRays)
1729 int i;
1730 int is_unbounded;
1731 Polyhedron *R = Recession_Cone(P, nparam, MaxRays);
1732 POL_ENSURE_VERTICES(R);
1733 if (R->NbBid == 0)
1734 for (i = 0; i < R->NbRays; ++i)
1735 if (value_zero_p(R->Ray[i][1+R->Dimension]))
1736 break;
1737 is_unbounded = R->NbBid > 0 || i < R->NbRays;
1738 Polyhedron_Free(R);
1739 return is_unbounded;
1742 static void SwapColumns(Value **V, int n, int i, int j)
1744 int r;
1746 for (r = 0; r < n; ++r)
1747 value_swap(V[r][i], V[r][j]);
1750 void Polyhedron_ExchangeColumns(Polyhedron *P, int Column1, int Column2)
1752 SwapColumns(P->Constraint, P->NbConstraints, Column1, Column2);
1753 SwapColumns(P->Ray, P->NbRays, Column1, Column2);
1754 if (P->NbEq) {
1755 Matrix M;
1756 Polyhedron_Matrix_View(P, &M, P->NbConstraints);
1757 Gauss(&M, P->NbEq, P->Dimension+1);
1761 /* perform transposition inline; assumes M is a square matrix */
1762 void Matrix_Transposition(Matrix *M)
1764 int i, j;
1766 assert(M->NbRows == M->NbColumns);
1767 for (i = 0; i < M->NbRows; ++i)
1768 for (j = i+1; j < M->NbColumns; ++j)
1769 value_swap(M->p[i][j], M->p[j][i]);
1772 /* Matrix "view" of first rows rows */
1773 void Polyhedron_Matrix_View(Polyhedron *P, Matrix *M, unsigned rows)
1775 M->NbRows = rows;
1776 M->NbColumns = P->Dimension+2;
1777 M->p_Init = P->p_Init;
1778 M->p = P->Constraint;
1781 int Last_Non_Zero(Value *p, unsigned len)
1783 int i;
1785 for (i = len - 1; i >= 0; --i)
1786 if (value_notzero_p(p[i]))
1787 return i;
1789 return -1;