fix typo in comment
[barvinok.git] / barvinok.cc
blobc8104384c11087ce72cc91b68d7595d1c9a41cb5
1 #include <assert.h>
2 #include <iostream>
3 #include <vector>
4 #include <deque>
5 #include <string>
6 #include <sstream>
7 #include <gmp.h>
8 #include <NTL/mat_ZZ.h>
9 #include <NTL/LLL.h>
10 #include <barvinok/util.h>
11 #include <barvinok/evalue.h>
12 #include "config.h"
13 #include <barvinok/barvinok.h>
14 #include <barvinok/genfun.h>
15 #include <barvinok/options.h>
16 #include <barvinok/sample.h>
17 #include "bfcounter.h"
18 #include "conversion.h"
19 #include "counter.h"
20 #include "decomposer.h"
21 #include "euler.h"
22 #include "lattice_point.h"
23 #include "laurent.h"
24 #include "reduce_domain.h"
25 #include "remove_equalities.h"
26 #include "scale.h"
27 #include "volume.h"
28 #include "bernoulli.h"
29 #include "param_util.h"
30 #include "summate.h"
32 #ifdef NTL_STD_CXX
33 using namespace NTL;
34 #endif
35 using std::cerr;
36 using std::cout;
37 using std::endl;
38 using std::vector;
39 using std::deque;
40 using std::string;
41 using std::ostringstream;
43 #define ALLOC(t,p) p = (t*)malloc(sizeof(*p))
45 class dpoly_n {
46 public:
47 Matrix *coeff;
48 ~dpoly_n() {
49 Matrix_Free(coeff);
51 dpoly_n(int d) {
52 Value d0, one;
53 value_init(d0);
54 value_init(one);
55 value_set_si(one, 1);
56 coeff = Matrix_Alloc(d+1, d+1+1);
57 value_set_si(coeff->p[0][0], 1);
58 value_set_si(coeff->p[0][d+1], 1);
59 for (int i = 1; i <= d; ++i) {
60 value_multiply(coeff->p[i][0], coeff->p[i-1][0], d0);
61 Vector_Combine(coeff->p[i-1], coeff->p[i-1]+1, coeff->p[i]+1,
62 one, d0, i);
63 value_set_si(coeff->p[i][d+1], i);
64 value_multiply(coeff->p[i][d+1], coeff->p[i][d+1], coeff->p[i-1][d+1]);
65 value_decrement(d0, d0);
67 value_clear(d0);
68 value_clear(one);
70 void div(dpoly& d, Vector *count, int sign) {
71 int len = coeff->NbRows;
72 Matrix * c = Matrix_Alloc(coeff->NbRows, coeff->NbColumns);
73 Value tmp;
74 value_init(tmp);
75 for (int i = 0; i < len; ++i) {
76 Vector_Copy(coeff->p[i], c->p[i], len+1);
77 for (int j = 1; j <= i; ++j) {
78 value_multiply(tmp, d.coeff->p[j], c->p[i][len]);
79 value_oppose(tmp, tmp);
80 Vector_Combine(c->p[i], c->p[i-j], c->p[i],
81 c->p[i-j][len], tmp, len);
82 value_multiply(c->p[i][len], c->p[i][len], c->p[i-j][len]);
84 value_multiply(c->p[i][len], c->p[i][len], d.coeff->p[0]);
86 if (sign == -1) {
87 value_set_si(tmp, -1);
88 Vector_Scale(c->p[len-1], count->p, tmp, len);
89 value_assign(count->p[len], c->p[len-1][len]);
90 } else
91 Vector_Copy(c->p[len-1], count->p, len+1);
92 Vector_Normalize(count->p, len+1);
93 value_clear(tmp);
94 Matrix_Free(c);
98 const int MAX_TRY=10;
100 * Searches for a vector that is not orthogonal to any
101 * of the rays in rays.
103 static void nonorthog(mat_ZZ& rays, vec_ZZ& lambda)
105 int dim = rays.NumCols();
106 bool found = false;
107 lambda.SetLength(dim);
108 if (dim == 0)
109 return;
111 for (int i = 2; !found && i <= 50*dim; i+=4) {
112 for (int j = 0; j < MAX_TRY; ++j) {
113 for (int k = 0; k < dim; ++k) {
114 int r = random_int(i)+2;
115 int v = (2*(r%2)-1) * (r >> 1);
116 lambda[k] = v;
118 int k = 0;
119 for (; k < rays.NumRows(); ++k)
120 if (lambda * rays[k] == 0)
121 break;
122 if (k == rays.NumRows()) {
123 found = true;
124 break;
128 assert(found);
131 static void add_rays(mat_ZZ& rays, Polyhedron *i, int *r, int nvar = -1,
132 bool all = false)
134 unsigned dim = i->Dimension;
135 if (nvar == -1)
136 nvar = dim;
137 for (int k = 0; k < i->NbRays; ++k) {
138 if (!value_zero_p(i->Ray[k][dim+1]))
139 continue;
140 if (!all && nvar != dim && First_Non_Zero(i->Ray[k]+1, nvar) == -1)
141 continue;
142 values2zz(i->Ray[k]+1, rays[(*r)++], nvar);
146 struct bfe_term : public bfc_term_base {
147 vector<evalue *> factors;
149 bfe_term(int len) : bfc_term_base(len) {
152 ~bfe_term() {
153 for (int i = 0; i < factors.size(); ++i) {
154 if (!factors[i])
155 continue;
156 free_evalue_refs(factors[i]);
157 delete factors[i];
162 static void print_int_vector(int *v, int len, const char *name)
164 cerr << name << endl;
165 for (int j = 0; j < len; ++j) {
166 cerr << v[j] << " ";
168 cerr << endl;
171 static void print_bfc_terms(mat_ZZ& factors, bfc_vec& v)
173 cerr << endl;
174 cerr << "factors" << endl;
175 cerr << factors << endl;
176 for (int i = 0; i < v.size(); ++i) {
177 cerr << "term: " << i << endl;
178 print_int_vector(v[i]->powers, factors.NumRows(), "powers");
179 cerr << "terms" << endl;
180 cerr << v[i]->terms << endl;
181 bfc_term* bfct = static_cast<bfc_term *>(v[i]);
182 cerr << bfct->c << endl;
186 static void print_bfe_terms(mat_ZZ& factors, bfc_vec& v)
188 cerr << endl;
189 cerr << "factors" << endl;
190 cerr << factors << endl;
191 for (int i = 0; i < v.size(); ++i) {
192 cerr << "term: " << i << endl;
193 print_int_vector(v[i]->powers, factors.NumRows(), "powers");
194 cerr << "terms" << endl;
195 cerr << v[i]->terms << endl;
196 bfe_term* bfet = static_cast<bfe_term *>(v[i]);
197 for (int j = 0; j < v[i]->terms.NumRows(); ++j) {
198 const char * test[] = {"a", "b"};
199 print_evalue(stderr, bfet->factors[j], test);
200 fprintf(stderr, "\n");
205 struct bfcounter : public bfcounter_base {
206 mpq_t count;
207 Value tz;
209 bfcounter(unsigned dim) : bfcounter_base(dim) {
210 mpq_init(count);
211 lower = 1;
212 value_init(tz);
214 ~bfcounter() {
215 mpq_clear(count);
216 value_clear(tz);
218 virtual void base(mat_ZZ& factors, bfc_vec& v);
219 virtual void get_count(Value *result) {
220 assert(value_one_p(&count[0]._mp_den));
221 value_assign(*result, &count[0]._mp_num);
225 void bfcounter::base(mat_ZZ& factors, bfc_vec& v)
227 unsigned nf = factors.NumRows();
229 for (int i = 0; i < v.size(); ++i) {
230 bfc_term* bfct = static_cast<bfc_term *>(v[i]);
231 int total_power = 0;
232 // factor is always positive, so we always
233 // change signs
234 for (int k = 0; k < nf; ++k)
235 total_power += v[i]->powers[k];
237 int j;
238 for (j = 0; j < nf; ++j)
239 if (v[i]->powers[j] > 0)
240 break;
242 zz2value(factors[j][0], tz);
243 dpoly D(total_power, tz, 1);
244 for (int k = 1; k < v[i]->powers[j]; ++k) {
245 zz2value(factors[j][0], tz);
246 dpoly fact(total_power, tz, 1);
247 D *= fact;
249 for ( ; ++j < nf; )
250 for (int k = 0; k < v[i]->powers[j]; ++k) {
251 zz2value(factors[j][0], tz);
252 dpoly fact(total_power, tz, 1);
253 D *= fact;
256 for (int k = 0; k < v[i]->terms.NumRows(); ++k) {
257 zz2value(v[i]->terms[k][0], tz);
258 dpoly n(total_power, tz);
259 mpq_set_si(tcount, 0, 1);
260 n.div(D, tcount, 1);
261 if (total_power % 2)
262 bfct->c[k].n = -bfct->c[k].n;
263 zz2value(bfct->c[k].n, tn);
264 zz2value(bfct->c[k].d, td);
266 mpz_mul(mpq_numref(tcount), mpq_numref(tcount), tn);
267 mpz_mul(mpq_denref(tcount), mpq_denref(tcount), td);
268 mpq_canonicalize(tcount);
269 mpq_add(count, count, tcount);
271 delete v[i];
276 /* Check whether the polyhedron is unbounded and if so,
277 * check whether it has any (and therefore an infinite number of)
278 * integer points.
279 * If one of the vertices is integer, then we are done.
280 * Otherwise, transform the polyhedron such that one of the rays
281 * is the first unit vector and cut it off at a height that ensures
282 * that if the whole polyhedron has any points, then the remaining part
283 * has integer points. In particular we add the largest coefficient
284 * of a ray to the highest vertex (rounded up).
286 static bool Polyhedron_is_infinite(Polyhedron *P, Value* result,
287 barvinok_options *options)
289 int r = 0;
290 Matrix *M, *M2;
291 Value c, tmp;
292 Value g;
293 bool first;
294 Vector *v;
295 Value offset, size;
296 Polyhedron *R;
298 if (P->NbBid == 0)
299 for (; r < P->NbRays; ++r)
300 if (value_zero_p(P->Ray[r][P->Dimension+1]))
301 break;
302 if (P->NbBid == 0 && r == P->NbRays)
303 return false;
305 if (options->count_sample_infinite) {
306 Vector *sample;
308 sample = Polyhedron_Sample(P, options);
309 if (!sample)
310 value_set_si(*result, 0);
311 else {
312 value_set_si(*result, -1);
313 Vector_Free(sample);
315 return true;
318 for (int i = 0; i < P->NbRays; ++i)
319 if (value_one_p(P->Ray[i][1+P->Dimension])) {
320 value_set_si(*result, -1);
321 return true;
324 value_init(g);
325 M = Matrix_Alloc(P->Dimension+1, P->Dimension+1);
326 Vector_Gcd(P->Ray[r]+1, P->Dimension, &g);
327 Vector_AntiScale(P->Ray[r]+1, M->p[0], g, P->Dimension+1);
328 int ok = unimodular_complete(M, 1);
329 assert(ok);
330 value_set_si(M->p[P->Dimension][P->Dimension], 1);
331 M2 = Transpose(M);
332 Matrix_Free(M);
333 P = Polyhedron_Preimage(P, M2, 0);
334 Matrix_Free(M2);
335 value_clear(g);
337 first = true;
338 value_init(offset);
339 value_init(size);
340 value_init(tmp);
341 value_set_si(size, 0);
343 for (int i = 0; i < P->NbBid; ++i) {
344 value_absolute(tmp, P->Ray[i][1]);
345 if (value_gt(tmp, size))
346 value_assign(size, tmp);
348 for (int i = P->NbBid; i < P->NbRays; ++i) {
349 if (value_zero_p(P->Ray[i][P->Dimension+1])) {
350 if (value_gt(P->Ray[i][1], size))
351 value_assign(size, P->Ray[i][1]);
352 continue;
354 mpz_cdiv_q(tmp, P->Ray[i][1], P->Ray[i][P->Dimension+1]);
355 if (first || value_gt(tmp, offset)) {
356 value_assign(offset, tmp);
357 first = false;
360 value_addto(offset, offset, size);
361 value_clear(size);
362 value_clear(tmp);
364 v = Vector_Alloc(P->Dimension+2);
365 value_set_si(v->p[0], 1);
366 value_set_si(v->p[1], -1);
367 value_assign(v->p[1+P->Dimension], offset);
368 R = AddConstraints(v->p, 1, P, options->MaxRays);
369 Polyhedron_Free(P);
370 P = R;
372 value_clear(offset);
373 Vector_Free(v);
375 value_init(c);
376 barvinok_count_with_options(P, &c, options);
377 Polyhedron_Free(P);
378 if (value_zero_p(c))
379 value_set_si(*result, 0);
380 else
381 value_set_si(*result, -1);
382 value_clear(c);
384 return true;
387 static void evalue2value(evalue *e, Value *v)
389 if (EVALUE_IS_ZERO(*e)) {
390 value_set_si(*v, 0);
391 return;
394 if (value_notzero_p(e->d)) {
395 assert(value_one_p(e->d));
396 value_assign(*v, e->x.n);
397 return;
400 assert(e->x.p->type == partition);
401 assert(e->x.p->size == 2);
402 assert(EVALUE_DOMAIN(e->x.p->arr[0])->Dimension == 0);
403 evalue2value(&e->x.p->arr[1], v);
406 static void barvinok_count_f(Polyhedron *P, Value* result,
407 barvinok_options *options);
409 void barvinok_count_with_options(Polyhedron *P, Value* result,
410 struct barvinok_options *options)
412 unsigned dim;
413 int allocated = 0;
414 Polyhedron *Q;
415 bool infinite = false;
417 if (P->next)
418 fprintf(stderr,
419 "barvinok_count: input is a union; only first polyhedron is counted\n");
421 if (emptyQ2(P)) {
422 value_set_si(*result, 0);
423 return;
425 if (P->NbEq != 0) {
426 Q = NULL;
427 do {
428 P = remove_equalities(P, options->MaxRays);
429 P = DomainConstraintSimplify(P, options->MaxRays);
430 if (Q)
431 Polyhedron_Free(Q);
432 Q = P;
433 } while (!emptyQ(P) && P->NbEq != 0);
434 if (emptyQ(P)) {
435 Polyhedron_Free(P);
436 value_set_si(*result, 0);
437 return;
439 allocated = 1;
441 if (Polyhedron_is_infinite(P, result, options)) {
442 if (allocated)
443 Polyhedron_Free(P);
444 return;
446 if (P->Dimension == 0) {
447 /* Test whether the constraints are satisfied */
448 POL_ENSURE_VERTICES(P);
449 value_set_si(*result, !emptyQ(P));
450 if (allocated)
451 Polyhedron_Free(P);
452 return;
454 if (options->summation == BV_SUM_BERNOULLI) {
455 Polyhedron *C = Universe_Polyhedron(0);
456 evalue *sum = barvinok_summate_unweighted(P, C, options);
457 Polyhedron_Free(C);
458 evalue2value(sum, result);
459 evalue_free(sum);
460 return;
462 Q = Polyhedron_Factor(P, 0, NULL, options->MaxRays);
463 if (Q) {
464 if (allocated)
465 Polyhedron_Free(P);
466 P = Q;
467 allocated = 1;
470 barvinok_count_f(P, result, options);
471 if (value_neg_p(*result))
472 infinite = true;
473 if (Q && P->next && value_notzero_p(*result)) {
474 Value factor;
475 value_init(factor);
477 for (Q = P->next; Q; Q = Q->next) {
478 barvinok_count_f(Q, &factor, options);
479 if (value_neg_p(factor)) {
480 infinite = true;
481 continue;
482 } else if (Q->next && value_zero_p(factor)) {
483 value_set_si(*result, 0);
484 break;
486 value_multiply(*result, *result, factor);
489 value_clear(factor);
492 if (allocated)
493 Domain_Free(P);
494 if (infinite)
495 value_set_si(*result, -1);
498 void barvinok_count(Polyhedron *P, Value* result, unsigned NbMaxCons)
500 barvinok_options *options = barvinok_options_new_with_defaults();
501 options->MaxRays = NbMaxCons;
502 barvinok_count_with_options(P, result, options);
503 barvinok_options_free(options);
506 static void barvinok_count_f(Polyhedron *P, Value* result,
507 barvinok_options *options)
509 if (emptyQ2(P)) {
510 value_set_si(*result, 0);
511 return;
514 if (P->Dimension == 1)
515 return Line_Length(P, result);
517 int c = P->NbConstraints;
518 POL_ENSURE_FACETS(P);
519 if (c != P->NbConstraints || P->NbEq != 0) {
520 Polyhedron *next = P->next;
521 P->next = NULL;
522 barvinok_count_with_options(P, result, options);
523 P->next = next;
524 return;
527 POL_ENSURE_VERTICES(P);
529 if (Polyhedron_is_infinite(P, result, options))
530 return;
532 np_base *cnt;
533 if (options->incremental_specialization == BV_SPECIALIZATION_BF)
534 cnt = new bfcounter(P->Dimension);
535 else if (options->incremental_specialization == BV_SPECIALIZATION_DF)
536 cnt = new icounter(P->Dimension);
537 else if (options->incremental_specialization == BV_SPECIALIZATION_TODD)
538 cnt = new tcounter(P->Dimension, options->max_index);
539 else
540 cnt = new counter(P->Dimension, options->max_index);
541 cnt->start(P, options);
543 cnt->get_count(result);
544 delete cnt;
547 static void uni_polynom(int param, Vector *c, evalue *EP)
549 unsigned dim = c->Size-2;
550 value_init(EP->d);
551 value_set_si(EP->d,0);
552 EP->x.p = new_enode(polynomial, dim+1, param+1);
553 for (int j = 0; j <= dim; ++j)
554 evalue_set(&EP->x.p->arr[j], c->p[j], c->p[dim+1]);
557 typedef evalue * evalue_p;
559 struct enumerator_base {
560 unsigned dim;
561 evalue ** vE;
562 evalue mone;
563 vertex_decomposer *vpd;
565 enumerator_base(unsigned dim, vertex_decomposer *vpd)
567 this->dim = dim;
568 this->vpd = vpd;
570 vE = new evalue_p[vpd->PP->nbV];
571 for (int j = 0; j < vpd->PP->nbV; ++j)
572 vE[j] = 0;
574 value_init(mone.d);
575 evalue_set_si(&mone, -1, 1);
578 void decompose_at(Param_Vertices *V, int _i, barvinok_options *options) {
579 //this->pVD = pVD;
581 vE[_i] = new evalue;
582 value_init(vE[_i]->d);
583 evalue_set_si(vE[_i], 0, 1);
585 vpd->decompose_at_vertex(V, _i, options);
588 virtual ~enumerator_base() {
589 for (int j = 0; j < vpd->PP->nbV; ++j)
590 if (vE[j]) {
591 free_evalue_refs(vE[j]);
592 delete vE[j];
594 delete [] vE;
596 free_evalue_refs(&mone);
599 static enumerator_base *create(Polyhedron *P, unsigned dim,
600 Param_Polyhedron *PP,
601 barvinok_options *options);
604 struct enumerator : public signed_cone_consumer, public vertex_decomposer,
605 public enumerator_base {
606 vec_ZZ lambda;
607 vec_ZZ den;
608 term_info num;
609 Vector *c;
610 mpq_t count;
611 Value tz;
613 enumerator(Polyhedron *P, unsigned dim, Param_Polyhedron *PP) :
614 vertex_decomposer(PP, *this), enumerator_base(dim, this) {
615 randomvector(P, lambda, dim);
616 den.SetLength(dim);
617 c = Vector_Alloc(dim+2);
619 mpq_init(count);
620 value_init(tz);
623 ~enumerator() {
624 mpq_clear(count);
625 Vector_Free(c);
626 value_clear(tz);
629 virtual void handle(const signed_cone& sc, barvinok_options *options);
632 void enumerator::handle(const signed_cone& sc, barvinok_options *options)
634 int sign = sc.sign;
635 int r = 0;
636 assert(sc.rays.NumRows() == dim);
637 for (int k = 0; k < dim; ++k) {
638 if (lambda * sc.rays[k] == 0)
639 throw Orthogonal;
642 lattice_point(V, sc.rays, lambda, &num, sc.det, options);
643 den = sc.rays * lambda;
645 if (dim % 2)
646 sign = -sign;
648 zz2value(den[0], tz);
649 dpoly n(dim, tz, 1);
650 for (int k = 1; k < dim; ++k) {
651 zz2value(den[k], tz);
652 dpoly fact(dim, tz, 1);
653 n *= fact;
655 if (num.E != NULL) {
656 dpoly_n d(dim);
657 d.div(n, c, sign);
658 for (unsigned long i = 0; i < sc.det; ++i) {
659 evalue *EV = evalue_polynomial(c, num.E[i]);
660 eadd(EV, vE[vert]);
661 evalue_free(EV);
662 evalue_free(num.E[i]);
664 delete [] num.E;
665 } else {
666 mpq_set_si(count, 0, 1);
667 if (num.constant.length() == 1) {
668 zz2value(num.constant[0], tz);
669 dpoly d(dim, tz);
670 d.div(n, count, sign);
671 } else {
672 dpoly_n d(dim);
673 d.div(n, c, sign);
674 Value x, sum, acc;
675 value_init(x);
676 value_init(acc);
677 for (unsigned long i = 0; i < sc.det; ++i) {
678 value_assign(acc, c->p[dim]);
679 zz2value(num.constant[i], x);
680 for (int j = dim-1; j >= 0; --j) {
681 value_multiply(acc, acc, x);
682 value_addto(acc, acc, c->p[j]);
684 value_addto(mpq_numref(count), mpq_numref(count), acc);
686 mpz_set(mpq_denref(count), c->p[dim+1]);
687 value_clear(acc);
688 value_clear(x);
690 evalue EV;
691 value_init(EV.d);
692 evalue_set(&EV, &count[0]._mp_num, &count[0]._mp_den);
693 eadd(&EV, vE[vert]);
694 free_evalue_refs(&EV);
698 struct ienumerator_base : enumerator_base {
699 evalue ** E_vertex;
701 ienumerator_base(unsigned dim, vertex_decomposer *vpd) :
702 enumerator_base(dim,vpd) {
703 E_vertex = new evalue_p[dim];
706 virtual ~ienumerator_base() {
707 delete [] E_vertex;
710 evalue *E_num(int i, int d) {
711 return E_vertex[i + (dim-d)];
715 struct cumulator {
716 evalue *factor;
717 evalue *v;
718 dpoly_r *r;
720 cumulator(evalue *factor, evalue *v, dpoly_r *r) :
721 factor(factor), v(v), r(r) {}
723 void cumulate(barvinok_options *options);
725 virtual void add_term(const vector<int>& powers, evalue *f2) = 0;
726 virtual ~cumulator() {}
729 void cumulator::cumulate(barvinok_options *options)
731 evalue cum; // factor * 1 * E_num[0]/1 * (E_num[0]-1)/2 *...
732 evalue f;
733 evalue t; // E_num[0] - (m-1)
734 evalue *cst;
735 evalue mone;
737 if (options->lookup_table) {
738 value_init(mone.d);
739 evalue_set_si(&mone, -1, 1);
742 value_init(cum.d);
743 evalue_copy(&cum, factor);
744 value_init(f.d);
745 value_init(f.x.n);
746 value_set_si(f.d, 1);
747 value_set_si(f.x.n, 1);
748 value_init(t.d);
749 evalue_copy(&t, v);
751 if (!options->lookup_table) {
752 for (cst = &t; value_zero_p(cst->d); ) {
753 if (cst->x.p->type == fractional)
754 cst = &cst->x.p->arr[1];
755 else
756 cst = &cst->x.p->arr[0];
760 for (int m = 0; m < r->len; ++m) {
761 if (m > 0) {
762 if (m > 1) {
763 value_set_si(f.d, m);
764 emul(&f, &cum);
765 if (!options->lookup_table)
766 value_subtract(cst->x.n, cst->x.n, cst->d);
767 else
768 eadd(&mone, &t);
770 emul(&t, &cum);
772 dpoly_r_term_list& current = r->c[r->len-1-m];
773 dpoly_r_term_list::iterator j;
774 for (j = current.begin(); j != current.end(); ++j) {
775 if ((*j)->coeff == 0)
776 continue;
777 evalue *f2 = new evalue;
778 value_init(f2->d);
779 value_init(f2->x.n);
780 zz2value((*j)->coeff, f2->x.n);
781 zz2value(r->denom, f2->d);
782 emul(&cum, f2);
784 add_term((*j)->powers, f2);
787 free_evalue_refs(&f);
788 free_evalue_refs(&t);
789 free_evalue_refs(&cum);
790 if (options->lookup_table)
791 free_evalue_refs(&mone);
794 struct E_poly_term {
795 vector<int> powers;
796 evalue *E;
799 struct ie_cum : public cumulator {
800 vector<E_poly_term *> terms;
802 ie_cum(evalue *factor, evalue *v, dpoly_r *r) : cumulator(factor, v, r) {}
804 virtual void add_term(const vector<int>& powers, evalue *f2);
807 void ie_cum::add_term(const vector<int>& powers, evalue *f2)
809 int k;
810 for (k = 0; k < terms.size(); ++k) {
811 if (terms[k]->powers == powers) {
812 eadd(f2, terms[k]->E);
813 free_evalue_refs(f2);
814 delete f2;
815 break;
818 if (k >= terms.size()) {
819 E_poly_term *ET = new E_poly_term;
820 ET->powers = powers;
821 ET->E = f2;
822 terms.push_back(ET);
826 struct ienumerator : public signed_cone_consumer, public vertex_decomposer,
827 public ienumerator_base {
828 //Polyhedron *pVD;
829 mat_ZZ den;
830 mat_ZZ vertex;
831 mpq_t tcount;
832 Value tz;
834 ienumerator(Polyhedron *P, unsigned dim, Param_Polyhedron *PP) :
835 vertex_decomposer(PP, *this), ienumerator_base(dim, this) {
836 vertex.SetDims(1, dim);
838 den.SetDims(dim, dim);
839 mpq_init(tcount);
840 value_init(tz);
843 ~ienumerator() {
844 mpq_clear(tcount);
845 value_clear(tz);
848 virtual void handle(const signed_cone& sc, barvinok_options *options);
849 void reduce(evalue *factor, const mat_ZZ& num, const mat_ZZ& den_f,
850 barvinok_options *options);
853 void ienumerator::reduce(evalue *factor, const mat_ZZ& num, const mat_ZZ& den_f,
854 barvinok_options *options)
856 unsigned len = den_f.NumRows(); // number of factors in den
857 unsigned dim = num.NumCols();
858 assert(num.NumRows() == 1);
860 if (dim == 0) {
861 eadd(factor, vE[vert]);
862 return;
865 vec_ZZ den_s;
866 mat_ZZ den_r;
867 vec_ZZ num_s;
868 mat_ZZ num_p;
870 split_one(num, num_s, num_p, den_f, den_s, den_r);
872 vec_ZZ den_p;
873 den_p.SetLength(len);
875 ZZ one;
876 one = 1;
877 normalize(one, num_s, num_p, den_s, den_p, den_r);
878 if (one != 1)
879 emul(&mone, factor);
881 int only_param = 0;
882 int no_param = 0;
883 for (int k = 0; k < len; ++k) {
884 if (den_p[k] == 0)
885 ++no_param;
886 else if (den_s[k] == 0)
887 ++only_param;
889 if (no_param == 0) {
890 reduce(factor, num_p, den_r, options);
891 } else {
892 int k, l;
893 mat_ZZ pden;
894 pden.SetDims(only_param, dim-1);
896 for (k = 0, l = 0; k < len; ++k)
897 if (den_s[k] == 0)
898 pden[l++] = den_r[k];
900 for (k = 0; k < len; ++k)
901 if (den_p[k] == 0)
902 break;
904 zz2value(num_s[0], tz);
905 dpoly n(no_param, tz);
906 zz2value(den_s[k], tz);
907 dpoly D(no_param, tz, 1);
908 for ( ; ++k < len; )
909 if (den_p[k] == 0) {
910 zz2value(den_s[k], tz);
911 dpoly fact(no_param, tz, 1);
912 D *= fact;
915 dpoly_r * r = 0;
916 // if no_param + only_param == len then all powers
917 // below will be all zero
918 if (no_param + only_param == len) {
919 if (E_num(0, dim) != 0)
920 r = new dpoly_r(n, len);
921 else {
922 mpq_set_si(tcount, 0, 1);
923 one = 1;
924 n.div(D, tcount, 1);
926 if (value_notzero_p(mpq_numref(tcount))) {
927 evalue f;
928 value_init(f.d);
929 value_init(f.x.n);
930 value_assign(f.x.n, mpq_numref(tcount));
931 value_assign(f.d, mpq_denref(tcount));
932 emul(&f, factor);
933 reduce(factor, num_p, pden, options);
934 free_evalue_refs(&f);
936 return;
938 } else {
939 for (k = 0; k < len; ++k) {
940 if (den_s[k] == 0 || den_p[k] == 0)
941 continue;
943 zz2value(den_s[k], tz);
944 dpoly pd(no_param-1, tz, 1);
946 int l;
947 for (l = 0; l < k; ++l)
948 if (den_r[l] == den_r[k])
949 break;
951 if (r == 0)
952 r = new dpoly_r(n, pd, l, len);
953 else {
954 dpoly_r *nr = new dpoly_r(r, pd, l, len);
955 delete r;
956 r = nr;
960 dpoly_r *rc = r->div(D);
961 delete r;
962 r = rc;
963 if (E_num(0, dim) == 0) {
964 int common = pden.NumRows();
965 dpoly_r_term_list& final = r->c[r->len-1];
966 int rows;
967 evalue t;
968 evalue f;
969 value_init(f.d);
970 value_init(f.x.n);
971 zz2value(r->denom, f.d);
972 dpoly_r_term_list::iterator j;
973 for (j = final.begin(); j != final.end(); ++j) {
974 if ((*j)->coeff == 0)
975 continue;
976 rows = common;
977 for (int k = 0; k < r->dim; ++k) {
978 int n = (*j)->powers[k];
979 if (n == 0)
980 continue;
981 pden.SetDims(rows+n, pden.NumCols());
982 for (int l = 0; l < n; ++l)
983 pden[rows+l] = den_r[k];
984 rows += n;
986 value_init(t.d);
987 evalue_copy(&t, factor);
988 zz2value((*j)->coeff, f.x.n);
989 emul(&f, &t);
990 reduce(&t, num_p, pden, options);
991 free_evalue_refs(&t);
993 free_evalue_refs(&f);
994 } else {
995 ie_cum cum(factor, E_num(0, dim), r);
996 cum.cumulate(options);
998 int common = pden.NumRows();
999 int rows;
1000 for (int j = 0; j < cum.terms.size(); ++j) {
1001 rows = common;
1002 pden.SetDims(rows, pden.NumCols());
1003 for (int k = 0; k < r->dim; ++k) {
1004 int n = cum.terms[j]->powers[k];
1005 if (n == 0)
1006 continue;
1007 pden.SetDims(rows+n, pden.NumCols());
1008 for (int l = 0; l < n; ++l)
1009 pden[rows+l] = den_r[k];
1010 rows += n;
1012 reduce(cum.terms[j]->E, num_p, pden, options);
1013 free_evalue_refs(cum.terms[j]->E);
1014 delete cum.terms[j]->E;
1015 delete cum.terms[j];
1018 delete r;
1022 static int type_offset(enode *p)
1024 return p->type == fractional ? 1 :
1025 p->type == flooring ? 1 : 0;
1028 static int edegree(evalue *e)
1030 int d = 0;
1031 enode *p;
1033 if (value_notzero_p(e->d))
1034 return 0;
1036 p = e->x.p;
1037 int i = type_offset(p);
1038 if (p->size-i-1 > d)
1039 d = p->size - i - 1;
1040 for (; i < p->size; i++) {
1041 int d2 = edegree(&p->arr[i]);
1042 if (d2 > d)
1043 d = d2;
1045 return d;
1048 void ienumerator::handle(const signed_cone& sc, barvinok_options *options)
1050 assert(sc.det == 1);
1051 assert(sc.rays.NumRows() == dim);
1053 lattice_point(V, sc.rays, vertex[0], E_vertex, options);
1055 den = sc.rays;
1057 evalue one;
1058 value_init(one.d);
1059 evalue_set_si(&one, sc.sign, 1);
1060 reduce(&one, vertex, den, options);
1061 free_evalue_refs(&one);
1063 for (int i = 0; i < dim; ++i)
1064 if (E_vertex[i])
1065 evalue_free(E_vertex[i]);
1068 struct bfenumerator : public vertex_decomposer, public bf_base,
1069 public ienumerator_base {
1070 evalue *factor;
1072 bfenumerator(Polyhedron *P, unsigned dim, Param_Polyhedron *PP) :
1073 vertex_decomposer(PP, *this),
1074 bf_base(dim), ienumerator_base(dim, this) {
1075 lower = 0;
1076 factor = NULL;
1079 ~bfenumerator() {
1082 virtual void handle(const signed_cone& sc, barvinok_options *options);
1083 virtual void base(mat_ZZ& factors, bfc_vec& v);
1085 bfc_term_base* new_bf_term(int len) {
1086 bfe_term* t = new bfe_term(len);
1087 return t;
1090 virtual void set_factor(bfc_term_base *t, int k, int change) {
1091 bfe_term* bfet = static_cast<bfe_term *>(t);
1092 factor = bfet->factors[k];
1093 assert(factor != NULL);
1094 bfet->factors[k] = NULL;
1095 if (change)
1096 emul(&mone, factor);
1099 virtual void set_factor(bfc_term_base *t, int k, mpq_t &q, int change) {
1100 bfe_term* bfet = static_cast<bfe_term *>(t);
1101 factor = bfet->factors[k];
1102 assert(factor != NULL);
1103 bfet->factors[k] = NULL;
1105 evalue f;
1106 value_init(f.d);
1107 value_init(f.x.n);
1108 if (change)
1109 value_oppose(f.x.n, mpq_numref(q));
1110 else
1111 value_assign(f.x.n, mpq_numref(q));
1112 value_assign(f.d, mpq_denref(q));
1113 emul(&f, factor);
1114 free_evalue_refs(&f);
1117 virtual void set_factor(bfc_term_base *t, int k, const QQ& c, int change) {
1118 bfe_term* bfet = static_cast<bfe_term *>(t);
1120 factor = new evalue;
1122 evalue f;
1123 value_init(f.d);
1124 value_init(f.x.n);
1125 zz2value(c.n, f.x.n);
1126 if (change)
1127 value_oppose(f.x.n, f.x.n);
1128 zz2value(c.d, f.d);
1130 value_init(factor->d);
1131 evalue_copy(factor, bfet->factors[k]);
1132 emul(&f, factor);
1133 free_evalue_refs(&f);
1136 void set_factor(evalue *f, int change) {
1137 if (change)
1138 emul(&mone, f);
1139 factor = f;
1142 virtual void insert_term(bfc_term_base *t, int i) {
1143 bfe_term* bfet = static_cast<bfe_term *>(t);
1144 int len = t->terms.NumRows()-1; // already increased by one
1146 bfet->factors.resize(len+1);
1147 for (int j = len; j > i; --j) {
1148 bfet->factors[j] = bfet->factors[j-1];
1149 t->terms[j] = t->terms[j-1];
1151 bfet->factors[i] = factor;
1152 factor = NULL;
1155 virtual void update_term(bfc_term_base *t, int i) {
1156 bfe_term* bfet = static_cast<bfe_term *>(t);
1158 eadd(factor, bfet->factors[i]);
1159 free_evalue_refs(factor);
1160 delete factor;
1163 virtual bool constant_vertex(int dim) { return E_num(0, dim) == 0; }
1165 virtual void cum(bf_reducer *bfr, bfc_term_base *t, int k, dpoly_r *r,
1166 barvinok_options *options);
1169 enumerator_base *enumerator_base::create(Polyhedron *P, unsigned dim,
1170 Param_Polyhedron *PP,
1171 barvinok_options *options)
1173 enumerator_base *eb;
1175 if (options->incremental_specialization == BV_SPECIALIZATION_BF)
1176 eb = new bfenumerator(P, dim, PP);
1177 else if (options->incremental_specialization == BV_SPECIALIZATION_DF)
1178 eb = new ienumerator(P, dim, PP);
1179 else
1180 eb = new enumerator(P, dim, PP);
1182 return eb;
1185 struct bfe_cum : public cumulator {
1186 bfenumerator *bfe;
1187 bfc_term_base *told;
1188 int k;
1189 bf_reducer *bfr;
1191 bfe_cum(evalue *factor, evalue *v, dpoly_r *r, bf_reducer *bfr,
1192 bfc_term_base *t, int k, bfenumerator *e) :
1193 cumulator(factor, v, r), told(t), k(k),
1194 bfr(bfr), bfe(e) {
1197 virtual void add_term(const vector<int>& powers, evalue *f2);
1200 void bfe_cum::add_term(const vector<int>& powers, evalue *f2)
1202 bfr->update_powers(powers);
1204 bfc_term_base * t = bfe->find_bfc_term(bfr->vn, bfr->npowers, bfr->nnf);
1205 bfe->set_factor(f2, bfr->l_changes % 2);
1206 bfe->add_term(t, told->terms[k], bfr->l_extra_num);
1209 void bfenumerator::cum(bf_reducer *bfr, bfc_term_base *t, int k,
1210 dpoly_r *r, barvinok_options *options)
1212 bfe_term* bfet = static_cast<bfe_term *>(t);
1213 bfe_cum cum(bfet->factors[k], E_num(0, bfr->d), r, bfr, t, k, this);
1214 cum.cumulate(options);
1217 void bfenumerator::base(mat_ZZ& factors, bfc_vec& v)
1219 for (int i = 0; i < v.size(); ++i) {
1220 assert(v[i]->terms.NumRows() == 1);
1221 evalue *factor = static_cast<bfe_term *>(v[i])->factors[0];
1222 eadd(factor, vE[vert]);
1223 delete v[i];
1227 void bfenumerator::handle(const signed_cone& sc, barvinok_options *options)
1229 assert(sc.det == 1);
1230 assert(sc.rays.NumRows() == enumerator_base::dim);
1232 bfe_term* t = new bfe_term(enumerator_base::dim);
1233 vector< bfc_term_base * > v;
1234 v.push_back(t);
1236 t->factors.resize(1);
1238 t->terms.SetDims(1, enumerator_base::dim);
1239 lattice_point(V, sc.rays, t->terms[0], E_vertex, options);
1241 // the elements of factors are always lexpositive
1242 mat_ZZ factors;
1243 int s = setup_factors(sc.rays, factors, t, sc.sign);
1245 t->factors[0] = new evalue;
1246 value_init(t->factors[0]->d);
1247 evalue_set_si(t->factors[0], s, 1);
1248 reduce(factors, v, options);
1250 for (int i = 0; i < enumerator_base::dim; ++i)
1251 if (E_vertex[i])
1252 evalue_free(E_vertex[i]);
1255 static evalue* barvinok_enumerate_ev_f(Polyhedron *P, Polyhedron* C,
1256 barvinok_options *options);
1258 /* Destroys C */
1259 static evalue* barvinok_enumerate_cst(Polyhedron *P, Polyhedron* C,
1260 struct barvinok_options *options)
1262 evalue *eres;
1264 if (emptyQ2(C)) {
1265 Polyhedron_Free(C);
1266 return evalue_zero();
1269 ALLOC(evalue, eres);
1270 value_init(eres->d);
1271 value_set_si(eres->d, 0);
1272 eres->x.p = new_enode(partition, 2, C->Dimension);
1273 EVALUE_SET_DOMAIN(eres->x.p->arr[0],
1274 DomainConstraintSimplify(C, options->MaxRays));
1275 value_set_si(eres->x.p->arr[1].d, 1);
1276 value_init(eres->x.p->arr[1].x.n);
1277 if (emptyQ2(P))
1278 value_set_si(eres->x.p->arr[1].x.n, 0);
1279 else
1280 barvinok_count_with_options(P, &eres->x.p->arr[1].x.n, options);
1282 return eres;
1285 static evalue* enumerate(Polyhedron *P, Polyhedron* C,
1286 struct barvinok_options *options)
1288 Polyhedron *next;
1289 Polyhedron *Porig = P;
1290 Polyhedron *Corig = C;
1291 Polyhedron *CEq = NULL, *rVD;
1292 int r = 0;
1293 unsigned nparam = C->Dimension;
1294 evalue *eres;
1295 Matrix *CP = NULL;
1297 evalue factor;
1298 value_init(factor.d);
1299 evalue_set_si(&factor, 1, 1);
1301 /* for now */
1302 POL_ENSURE_FACETS(P);
1303 POL_ENSURE_VERTICES(P);
1304 POL_ENSURE_FACETS(C);
1305 POL_ENSURE_VERTICES(C);
1307 if (C->Dimension == 0 || emptyQ(P) || emptyQ(C)) {
1308 constant:
1309 if (CEq == Porig)
1310 CEq = Polyhedron_Copy(CEq);
1311 eres = barvinok_enumerate_cst(P, CEq ? CEq : Polyhedron_Copy(C), options);
1312 out:
1313 if (CP) {
1314 evalue_backsubstitute(eres, CP, options->MaxRays);
1315 Matrix_Free(CP);
1318 emul(&factor, eres);
1319 if (options->approximation_method == BV_APPROX_DROP) {
1320 if (options->polynomial_approximation == BV_APPROX_SIGN_UPPER)
1321 evalue_frac2polynomial(eres, 1, options->MaxRays);
1322 if (options->polynomial_approximation == BV_APPROX_SIGN_LOWER)
1323 evalue_frac2polynomial(eres, -1, options->MaxRays);
1324 if (options->polynomial_approximation == BV_APPROX_SIGN_APPROX)
1325 evalue_frac2polynomial(eres, 0, options->MaxRays);
1327 reduce_evalue(eres);
1328 free_evalue_refs(&factor);
1329 if (P != Porig)
1330 Domain_Free(P);
1331 if (C != Corig)
1332 Polyhedron_Free(C);
1334 return eres;
1336 if (Polyhedron_is_unbounded(P, nparam, options->MaxRays))
1337 goto constant;
1339 if (P->Dimension == nparam) {
1340 CEq = P;
1341 P = Universe_Polyhedron(0);
1342 goto constant;
1344 if (P->NbEq != 0 || C->NbEq != 0) {
1345 Polyhedron *Q = P;
1346 Polyhedron *D = C;
1347 remove_all_equalities(&P, &C, &CP, NULL, nparam, options->MaxRays);
1348 if (C != D && D != Corig)
1349 Polyhedron_Free(D);
1350 if (P != Q && Q != Porig)
1351 Domain_Free(Q);
1352 eres = enumerate(P, C, options);
1353 goto out;
1356 Polyhedron *T = Polyhedron_Factor(P, nparam, NULL, options->MaxRays);
1357 if (T || (P->Dimension == nparam+1)) {
1358 Polyhedron *C2 = C;
1359 Polyhedron *FC = Factor_Context(T ? T : P, nparam, options->MaxRays);
1360 C = DomainIntersection(C, FC, options->MaxRays);
1361 if (C2 != Corig)
1362 Polyhedron_Free(C2);
1363 Polyhedron_Free(FC);
1365 if (T) {
1366 if (P != Porig)
1367 Polyhedron_Free(P);
1368 P = T;
1369 if (T->Dimension == C->Dimension) {
1370 P = T->next;
1371 T->next = NULL;
1372 Polyhedron_Free(T);
1376 next = P->next;
1377 P->next = NULL;
1378 eres = barvinok_enumerate_ev_f(P, C, options);
1379 P->next = next;
1381 if (P->next) {
1382 Polyhedron *Q;
1383 evalue *f;
1385 for (Q = P->next; Q; Q = Q->next) {
1386 Polyhedron *next = Q->next;
1387 Q->next = NULL;
1389 f = barvinok_enumerate_ev_f(Q, C, options);
1390 emul(f, eres);
1391 evalue_free(f);
1393 Q->next = next;
1397 goto out;
1400 evalue* barvinok_enumerate_with_options(Polyhedron *P, Polyhedron* C,
1401 struct barvinok_options *options)
1403 Polyhedron *next, *Cnext, *C1;
1404 Polyhedron *Corig = C;
1405 evalue *eres;
1407 if (P->next)
1408 fprintf(stderr,
1409 "barvinok_enumerate: input is a union; only first polyhedron is enumerated\n");
1411 if (C->next)
1412 fprintf(stderr,
1413 "barvinok_enumerate: context is a union; only first polyhedron is considered\n");
1415 Cnext = C->next;
1416 C->next = NULL;
1417 C1 = Polyhedron_Project(P, C->Dimension);
1418 C = DomainIntersection(C, C1, options->MaxRays);
1419 Polyhedron_Free(C1);
1420 next = P->next;
1421 P->next = NULL;
1423 if (options->approximation_method == BV_APPROX_BERNOULLI ||
1424 options->summation == BV_SUM_BERNOULLI) {
1425 int summation = options->summation;
1426 options->summation = BV_SUM_BERNOULLI;
1427 eres = barvinok_summate_unweighted(P, C, options);
1428 options->summation = summation;
1429 } else
1430 eres = enumerate(P, C, options);
1431 Domain_Free(C);
1433 P->next= next;
1434 Corig->next = Cnext;
1436 return eres;
1439 evalue* barvinok_enumerate_ev(Polyhedron *P, Polyhedron* C, unsigned MaxRays)
1441 evalue *E;
1442 barvinok_options *options = barvinok_options_new_with_defaults();
1443 options->MaxRays = MaxRays;
1444 E = barvinok_enumerate_with_options(P, C, options);
1445 barvinok_options_free(options);
1446 return E;
1449 evalue *Param_Polyhedron_Enumerate(Param_Polyhedron *PP, Polyhedron *P,
1450 Polyhedron *C,
1451 struct barvinok_options *options)
1453 evalue *eres;
1454 Param_Domain *D;
1455 unsigned nparam = C->Dimension;
1456 unsigned dim = P->Dimension - nparam;
1458 int nd;
1459 for (nd = 0, D=PP->D; D; ++nd, D=D->next);
1460 evalue_section *s = new evalue_section[nd];
1462 enumerator_base *et = NULL;
1463 try_again:
1464 if (et)
1465 delete et;
1467 et = enumerator_base::create(P, dim, PP, options);
1469 Polyhedron *TC = true_context(P, C, options->MaxRays);
1470 FORALL_REDUCED_DOMAIN(PP, TC, nd, options, i, D, rVD)
1471 Param_Vertices *V;
1473 s[i].E = evalue_zero();
1474 s[i].D = rVD;
1476 FORALL_PVertex_in_ParamPolyhedron(V,D,PP) // _i is internal counter
1477 if (!et->vE[_i])
1478 try {
1479 et->decompose_at(V, _i, options);
1480 } catch (OrthogonalException &e) {
1481 FORALL_REDUCED_DOMAIN_RESET;
1482 for (; i >= 0; --i) {
1483 evalue_free(s[i].E);
1484 Domain_Free(s[i].D);
1486 goto try_again;
1488 eadd(et->vE[_i] , s[i].E);
1489 END_FORALL_PVertex_in_ParamPolyhedron;
1490 evalue_range_reduction_in_domain(s[i].E, rVD);
1491 END_FORALL_REDUCED_DOMAIN
1492 Polyhedron_Free(TC);
1494 delete et;
1495 eres = evalue_from_section_array(s, nd);
1496 delete [] s;
1498 return eres;
1501 static evalue* barvinok_enumerate_ev_f(Polyhedron *P, Polyhedron* C,
1502 barvinok_options *options)
1504 unsigned nparam = C->Dimension;
1505 bool do_scale = options->approximation_method == BV_APPROX_SCALE;
1507 if (options->summation == BV_SUM_EULER)
1508 return barvinok_summate_unweighted(P, C, options);
1510 if (options->approximation_method == BV_APPROX_VOLUME)
1511 return Param_Polyhedron_Volume(P, C, options);
1513 if (P->Dimension - nparam == 1 && !do_scale)
1514 return ParamLine_Length(P, C, options);
1516 Param_Polyhedron *PP = NULL;
1517 evalue *eres;
1519 if (do_scale) {
1520 eres = scale_bound(P, C, options);
1521 if (eres)
1522 return eres;
1525 PP = Polyhedron2Param_Polyhedron(P, C, options);
1527 if (do_scale)
1528 eres = scale(PP, P, C, options);
1529 else
1530 eres = Param_Polyhedron_Enumerate(PP, P, C, options);
1532 if (PP)
1533 Param_Polyhedron_Free(PP);
1535 return eres;
1538 Enumeration* barvinok_enumerate(Polyhedron *P, Polyhedron* C, unsigned MaxRays)
1540 evalue *EP = barvinok_enumerate_ev(P, C, MaxRays);
1542 return partition2enumeration(EP);
1545 evalue* barvinok_enumerate_union(Polyhedron *D, Polyhedron* C, unsigned MaxRays)
1547 evalue *EP;
1548 gen_fun *gf = barvinok_enumerate_union_series(D, C, MaxRays);
1549 EP = *gf;
1550 delete gf;
1551 return EP;