barvinok_enumerate_with_options: compute (exact) Bernoulli sum at request
[barvinok.git] / barvinok.cc
blob7454443dd0e042bcc25f848f07fd520b6f2f3768
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 "reduce_domain.h"
24 #include "remove_equalities.h"
25 #include "scale.h"
26 #include "volume.h"
27 #include "bernoulli.h"
28 #include "param_util.h"
30 #ifdef NTL_STD_CXX
31 using namespace NTL;
32 #endif
33 using std::cerr;
34 using std::cout;
35 using std::endl;
36 using std::vector;
37 using std::deque;
38 using std::string;
39 using std::ostringstream;
41 #define ALLOC(t,p) p = (t*)malloc(sizeof(*p))
43 class dpoly_n {
44 public:
45 Matrix *coeff;
46 ~dpoly_n() {
47 Matrix_Free(coeff);
49 dpoly_n(int d) {
50 Value d0, one;
51 value_init(d0);
52 value_init(one);
53 value_set_si(one, 1);
54 coeff = Matrix_Alloc(d+1, d+1+1);
55 value_set_si(coeff->p[0][0], 1);
56 value_set_si(coeff->p[0][d+1], 1);
57 for (int i = 1; i <= d; ++i) {
58 value_multiply(coeff->p[i][0], coeff->p[i-1][0], d0);
59 Vector_Combine(coeff->p[i-1], coeff->p[i-1]+1, coeff->p[i]+1,
60 one, d0, i);
61 value_set_si(coeff->p[i][d+1], i);
62 value_multiply(coeff->p[i][d+1], coeff->p[i][d+1], coeff->p[i-1][d+1]);
63 value_decrement(d0, d0);
65 value_clear(d0);
66 value_clear(one);
68 void div(dpoly& d, Vector *count, int sign) {
69 int len = coeff->NbRows;
70 Matrix * c = Matrix_Alloc(coeff->NbRows, coeff->NbColumns);
71 Value tmp;
72 value_init(tmp);
73 for (int i = 0; i < len; ++i) {
74 Vector_Copy(coeff->p[i], c->p[i], len+1);
75 for (int j = 1; j <= i; ++j) {
76 value_multiply(tmp, d.coeff->p[j], c->p[i][len]);
77 value_oppose(tmp, tmp);
78 Vector_Combine(c->p[i], c->p[i-j], c->p[i],
79 c->p[i-j][len], tmp, len);
80 value_multiply(c->p[i][len], c->p[i][len], c->p[i-j][len]);
82 value_multiply(c->p[i][len], c->p[i][len], d.coeff->p[0]);
84 if (sign == -1) {
85 value_set_si(tmp, -1);
86 Vector_Scale(c->p[len-1], count->p, tmp, len);
87 value_assign(count->p[len], c->p[len-1][len]);
88 } else
89 Vector_Copy(c->p[len-1], count->p, len+1);
90 Vector_Normalize(count->p, len+1);
91 value_clear(tmp);
92 Matrix_Free(c);
96 const int MAX_TRY=10;
98 * Searches for a vector that is not orthogonal to any
99 * of the rays in rays.
101 static void nonorthog(mat_ZZ& rays, vec_ZZ& lambda)
103 int dim = rays.NumCols();
104 bool found = false;
105 lambda.SetLength(dim);
106 if (dim == 0)
107 return;
109 for (int i = 2; !found && i <= 50*dim; i+=4) {
110 for (int j = 0; j < MAX_TRY; ++j) {
111 for (int k = 0; k < dim; ++k) {
112 int r = random_int(i)+2;
113 int v = (2*(r%2)-1) * (r >> 1);
114 lambda[k] = v;
116 int k = 0;
117 for (; k < rays.NumRows(); ++k)
118 if (lambda * rays[k] == 0)
119 break;
120 if (k == rays.NumRows()) {
121 found = true;
122 break;
126 assert(found);
129 static void add_rays(mat_ZZ& rays, Polyhedron *i, int *r, int nvar = -1,
130 bool all = false)
132 unsigned dim = i->Dimension;
133 if (nvar == -1)
134 nvar = dim;
135 for (int k = 0; k < i->NbRays; ++k) {
136 if (!value_zero_p(i->Ray[k][dim+1]))
137 continue;
138 if (!all && nvar != dim && First_Non_Zero(i->Ray[k]+1, nvar) == -1)
139 continue;
140 values2zz(i->Ray[k]+1, rays[(*r)++], nvar);
144 struct bfe_term : public bfc_term_base {
145 vector<evalue *> factors;
147 bfe_term(int len) : bfc_term_base(len) {
150 ~bfe_term() {
151 for (int i = 0; i < factors.size(); ++i) {
152 if (!factors[i])
153 continue;
154 free_evalue_refs(factors[i]);
155 delete factors[i];
160 static void print_int_vector(int *v, int len, const char *name)
162 cerr << name << endl;
163 for (int j = 0; j < len; ++j) {
164 cerr << v[j] << " ";
166 cerr << endl;
169 static void print_bfc_terms(mat_ZZ& factors, bfc_vec& v)
171 cerr << endl;
172 cerr << "factors" << endl;
173 cerr << factors << endl;
174 for (int i = 0; i < v.size(); ++i) {
175 cerr << "term: " << i << endl;
176 print_int_vector(v[i]->powers, factors.NumRows(), "powers");
177 cerr << "terms" << endl;
178 cerr << v[i]->terms << endl;
179 bfc_term* bfct = static_cast<bfc_term *>(v[i]);
180 cerr << bfct->c << endl;
184 static void print_bfe_terms(mat_ZZ& factors, bfc_vec& v)
186 cerr << endl;
187 cerr << "factors" << endl;
188 cerr << factors << endl;
189 for (int i = 0; i < v.size(); ++i) {
190 cerr << "term: " << i << endl;
191 print_int_vector(v[i]->powers, factors.NumRows(), "powers");
192 cerr << "terms" << endl;
193 cerr << v[i]->terms << endl;
194 bfe_term* bfet = static_cast<bfe_term *>(v[i]);
195 for (int j = 0; j < v[i]->terms.NumRows(); ++j) {
196 const char * test[] = {"a", "b"};
197 print_evalue(stderr, bfet->factors[j], test);
198 fprintf(stderr, "\n");
203 struct bfcounter : public bfcounter_base {
204 mpq_t count;
205 Value tz;
207 bfcounter(unsigned dim) : bfcounter_base(dim) {
208 mpq_init(count);
209 lower = 1;
210 value_init(tz);
212 ~bfcounter() {
213 mpq_clear(count);
214 value_clear(tz);
216 virtual void base(mat_ZZ& factors, bfc_vec& v);
217 virtual void get_count(Value *result) {
218 assert(value_one_p(&count[0]._mp_den));
219 value_assign(*result, &count[0]._mp_num);
223 void bfcounter::base(mat_ZZ& factors, bfc_vec& v)
225 unsigned nf = factors.NumRows();
227 for (int i = 0; i < v.size(); ++i) {
228 bfc_term* bfct = static_cast<bfc_term *>(v[i]);
229 int total_power = 0;
230 // factor is always positive, so we always
231 // change signs
232 for (int k = 0; k < nf; ++k)
233 total_power += v[i]->powers[k];
235 int j;
236 for (j = 0; j < nf; ++j)
237 if (v[i]->powers[j] > 0)
238 break;
240 zz2value(factors[j][0], tz);
241 dpoly D(total_power, tz, 1);
242 for (int k = 1; k < v[i]->powers[j]; ++k) {
243 zz2value(factors[j][0], tz);
244 dpoly fact(total_power, tz, 1);
245 D *= fact;
247 for ( ; ++j < nf; )
248 for (int k = 0; k < v[i]->powers[j]; ++k) {
249 zz2value(factors[j][0], tz);
250 dpoly fact(total_power, tz, 1);
251 D *= fact;
254 for (int k = 0; k < v[i]->terms.NumRows(); ++k) {
255 zz2value(v[i]->terms[k][0], tz);
256 dpoly n(total_power, tz);
257 mpq_set_si(tcount, 0, 1);
258 n.div(D, tcount, 1);
259 if (total_power % 2)
260 bfct->c[k].n = -bfct->c[k].n;
261 zz2value(bfct->c[k].n, tn);
262 zz2value(bfct->c[k].d, td);
264 mpz_mul(mpq_numref(tcount), mpq_numref(tcount), tn);
265 mpz_mul(mpq_denref(tcount), mpq_denref(tcount), td);
266 mpq_canonicalize(tcount);
267 mpq_add(count, count, tcount);
269 delete v[i];
274 /* Check whether the polyhedron is unbounded and if so,
275 * check whether it has any (and therefore an infinite number of)
276 * integer points.
277 * If one of the vertices is integer, then we are done.
278 * Otherwise, transform the polyhedron such that one of the rays
279 * is the first unit vector and cut it off at a height that ensures
280 * that if the whole polyhedron has any points, then the remaining part
281 * has integer points. In particular we add the largest coefficient
282 * of a ray to the highest vertex (rounded up).
284 static bool Polyhedron_is_infinite(Polyhedron *P, Value* result,
285 barvinok_options *options)
287 int r = 0;
288 Matrix *M, *M2;
289 Value c, tmp;
290 Value g;
291 bool first;
292 Vector *v;
293 Value offset, size;
294 Polyhedron *R;
296 if (P->NbBid == 0)
297 for (; r < P->NbRays; ++r)
298 if (value_zero_p(P->Ray[r][P->Dimension+1]))
299 break;
300 if (P->NbBid == 0 && r == P->NbRays)
301 return false;
303 if (options->count_sample_infinite) {
304 Vector *sample;
306 sample = Polyhedron_Sample(P, options);
307 if (!sample)
308 value_set_si(*result, 0);
309 else {
310 value_set_si(*result, -1);
311 Vector_Free(sample);
313 return true;
316 for (int i = 0; i < P->NbRays; ++i)
317 if (value_one_p(P->Ray[i][1+P->Dimension])) {
318 value_set_si(*result, -1);
319 return true;
322 value_init(g);
323 M = Matrix_Alloc(P->Dimension+1, P->Dimension+1);
324 Vector_Gcd(P->Ray[r]+1, P->Dimension, &g);
325 Vector_AntiScale(P->Ray[r]+1, M->p[0], g, P->Dimension+1);
326 int ok = unimodular_complete(M, 1);
327 assert(ok);
328 value_set_si(M->p[P->Dimension][P->Dimension], 1);
329 M2 = Transpose(M);
330 Matrix_Free(M);
331 P = Polyhedron_Preimage(P, M2, 0);
332 Matrix_Free(M2);
333 value_clear(g);
335 first = true;
336 value_init(offset);
337 value_init(size);
338 value_init(tmp);
339 value_set_si(size, 0);
341 for (int i = 0; i < P->NbBid; ++i) {
342 value_absolute(tmp, P->Ray[i][1]);
343 if (value_gt(tmp, size))
344 value_assign(size, tmp);
346 for (int i = P->NbBid; i < P->NbRays; ++i) {
347 if (value_zero_p(P->Ray[i][P->Dimension+1])) {
348 if (value_gt(P->Ray[i][1], size))
349 value_assign(size, P->Ray[i][1]);
350 continue;
352 mpz_cdiv_q(tmp, P->Ray[i][1], P->Ray[i][P->Dimension+1]);
353 if (first || value_gt(tmp, offset)) {
354 value_assign(offset, tmp);
355 first = false;
358 value_addto(offset, offset, size);
359 value_clear(size);
360 value_clear(tmp);
362 v = Vector_Alloc(P->Dimension+2);
363 value_set_si(v->p[0], 1);
364 value_set_si(v->p[1], -1);
365 value_assign(v->p[1+P->Dimension], offset);
366 R = AddConstraints(v->p, 1, P, options->MaxRays);
367 Polyhedron_Free(P);
368 P = R;
370 value_clear(offset);
371 Vector_Free(v);
373 value_init(c);
374 barvinok_count_with_options(P, &c, options);
375 Polyhedron_Free(P);
376 if (value_zero_p(c))
377 value_set_si(*result, 0);
378 else
379 value_set_si(*result, -1);
380 value_clear(c);
382 return true;
385 static void barvinok_count_f(Polyhedron *P, Value* result,
386 barvinok_options *options);
388 void barvinok_count_with_options(Polyhedron *P, Value* result,
389 struct barvinok_options *options)
391 unsigned dim;
392 int allocated = 0;
393 Polyhedron *Q;
394 bool infinite = false;
396 if (P->next)
397 fprintf(stderr,
398 "barvinok_count: input is a union; only first polyhedron is counted\n");
400 if (emptyQ2(P)) {
401 value_set_si(*result, 0);
402 return;
404 if (P->NbEq != 0) {
405 Q = NULL;
406 do {
407 P = remove_equalities(P, options->MaxRays);
408 P = DomainConstraintSimplify(P, options->MaxRays);
409 if (Q)
410 Polyhedron_Free(Q);
411 Q = P;
412 } while (!emptyQ(P) && P->NbEq != 0);
413 if (emptyQ(P)) {
414 Polyhedron_Free(P);
415 value_set_si(*result, 0);
416 return;
418 allocated = 1;
420 if (Polyhedron_is_infinite(P, result, options)) {
421 if (allocated)
422 Polyhedron_Free(P);
423 return;
425 if (P->Dimension == 0) {
426 /* Test whether the constraints are satisfied */
427 POL_ENSURE_VERTICES(P);
428 value_set_si(*result, !emptyQ(P));
429 if (allocated)
430 Polyhedron_Free(P);
431 return;
433 Q = Polyhedron_Factor(P, 0, NULL, options->MaxRays);
434 if (Q) {
435 if (allocated)
436 Polyhedron_Free(P);
437 P = Q;
438 allocated = 1;
441 barvinok_count_f(P, result, options);
442 if (value_neg_p(*result))
443 infinite = true;
444 if (Q && P->next && value_notzero_p(*result)) {
445 Value factor;
446 value_init(factor);
448 for (Q = P->next; Q; Q = Q->next) {
449 barvinok_count_f(Q, &factor, options);
450 if (value_neg_p(factor)) {
451 infinite = true;
452 continue;
453 } else if (Q->next && value_zero_p(factor)) {
454 value_set_si(*result, 0);
455 break;
457 value_multiply(*result, *result, factor);
460 value_clear(factor);
463 if (allocated)
464 Domain_Free(P);
465 if (infinite)
466 value_set_si(*result, -1);
469 void barvinok_count(Polyhedron *P, Value* result, unsigned NbMaxCons)
471 barvinok_options *options = barvinok_options_new_with_defaults();
472 options->MaxRays = NbMaxCons;
473 barvinok_count_with_options(P, result, options);
474 barvinok_options_free(options);
477 static void barvinok_count_f(Polyhedron *P, Value* result,
478 barvinok_options *options)
480 if (emptyQ2(P)) {
481 value_set_si(*result, 0);
482 return;
485 if (P->Dimension == 1)
486 return Line_Length(P, result);
488 int c = P->NbConstraints;
489 POL_ENSURE_FACETS(P);
490 if (c != P->NbConstraints || P->NbEq != 0) {
491 Polyhedron *next = P->next;
492 P->next = NULL;
493 barvinok_count_with_options(P, result, options);
494 P->next = next;
495 return;
498 POL_ENSURE_VERTICES(P);
500 if (Polyhedron_is_infinite(P, result, options))
501 return;
503 np_base *cnt;
504 if (options->incremental_specialization == BV_SPECIALIZATION_BF)
505 cnt = new bfcounter(P->Dimension);
506 else if (options->incremental_specialization == BV_SPECIALIZATION_DF)
507 cnt = new icounter(P->Dimension);
508 else if (options->incremental_specialization == BV_SPECIALIZATION_TODD)
509 cnt = new tcounter(P->Dimension, options->max_index);
510 else
511 cnt = new counter(P->Dimension, options->max_index);
512 cnt->start(P, options);
514 cnt->get_count(result);
515 delete cnt;
518 static void uni_polynom(int param, Vector *c, evalue *EP)
520 unsigned dim = c->Size-2;
521 value_init(EP->d);
522 value_set_si(EP->d,0);
523 EP->x.p = new_enode(polynomial, dim+1, param+1);
524 for (int j = 0; j <= dim; ++j)
525 evalue_set(&EP->x.p->arr[j], c->p[j], c->p[dim+1]);
528 typedef evalue * evalue_p;
530 struct enumerator_base {
531 unsigned dim;
532 evalue ** vE;
533 evalue mone;
534 vertex_decomposer *vpd;
536 enumerator_base(unsigned dim, vertex_decomposer *vpd)
538 this->dim = dim;
539 this->vpd = vpd;
541 vE = new evalue_p[vpd->PP->nbV];
542 for (int j = 0; j < vpd->PP->nbV; ++j)
543 vE[j] = 0;
545 value_init(mone.d);
546 evalue_set_si(&mone, -1, 1);
549 void decompose_at(Param_Vertices *V, int _i, barvinok_options *options) {
550 //this->pVD = pVD;
552 vE[_i] = new evalue;
553 value_init(vE[_i]->d);
554 evalue_set_si(vE[_i], 0, 1);
556 vpd->decompose_at_vertex(V, _i, options);
559 virtual ~enumerator_base() {
560 for (int j = 0; j < vpd->PP->nbV; ++j)
561 if (vE[j]) {
562 free_evalue_refs(vE[j]);
563 delete vE[j];
565 delete [] vE;
567 free_evalue_refs(&mone);
570 static enumerator_base *create(Polyhedron *P, unsigned dim,
571 Param_Polyhedron *PP,
572 barvinok_options *options);
575 struct enumerator : public signed_cone_consumer, public vertex_decomposer,
576 public enumerator_base {
577 vec_ZZ lambda;
578 vec_ZZ den;
579 term_info num;
580 Vector *c;
581 mpq_t count;
582 Value tz;
584 enumerator(Polyhedron *P, unsigned dim, Param_Polyhedron *PP) :
585 vertex_decomposer(PP, *this), enumerator_base(dim, this) {
586 randomvector(P, lambda, dim);
587 den.SetLength(dim);
588 c = Vector_Alloc(dim+2);
590 mpq_init(count);
591 value_init(tz);
594 ~enumerator() {
595 mpq_clear(count);
596 Vector_Free(c);
597 value_clear(tz);
600 virtual void handle(const signed_cone& sc, barvinok_options *options);
603 void enumerator::handle(const signed_cone& sc, barvinok_options *options)
605 int sign = sc.sign;
606 int r = 0;
607 assert(sc.rays.NumRows() == dim);
608 for (int k = 0; k < dim; ++k) {
609 if (lambda * sc.rays[k] == 0)
610 throw Orthogonal;
613 lattice_point(V, sc.rays, lambda, &num, sc.det, options);
614 den = sc.rays * lambda;
616 if (dim % 2)
617 sign = -sign;
619 zz2value(den[0], tz);
620 dpoly n(dim, tz, 1);
621 for (int k = 1; k < dim; ++k) {
622 zz2value(den[k], tz);
623 dpoly fact(dim, tz, 1);
624 n *= fact;
626 if (num.E != NULL) {
627 dpoly_n d(dim);
628 d.div(n, c, sign);
629 for (unsigned long i = 0; i < sc.det; ++i) {
630 evalue *EV = evalue_polynomial(c, num.E[i]);
631 eadd(EV, vE[vert]);
632 evalue_free(EV);
633 free_evalue_refs(num.E[i]);
634 delete num.E[i];
636 delete [] num.E;
637 } else {
638 mpq_set_si(count, 0, 1);
639 if (num.constant.length() == 1) {
640 zz2value(num.constant[0], tz);
641 dpoly d(dim, tz);
642 d.div(n, count, sign);
643 } else {
644 dpoly_n d(dim);
645 d.div(n, c, sign);
646 Value x, sum, acc;
647 value_init(x);
648 value_init(acc);
649 for (unsigned long i = 0; i < sc.det; ++i) {
650 value_assign(acc, c->p[dim]);
651 zz2value(num.constant[i], x);
652 for (int j = dim-1; j >= 0; --j) {
653 value_multiply(acc, acc, x);
654 value_addto(acc, acc, c->p[j]);
656 value_addto(mpq_numref(count), mpq_numref(count), acc);
658 mpz_set(mpq_denref(count), c->p[dim+1]);
659 value_clear(acc);
660 value_clear(x);
662 evalue EV;
663 value_init(EV.d);
664 evalue_set(&EV, &count[0]._mp_num, &count[0]._mp_den);
665 eadd(&EV, vE[vert]);
666 free_evalue_refs(&EV);
670 struct ienumerator_base : enumerator_base {
671 evalue ** E_vertex;
673 ienumerator_base(unsigned dim, vertex_decomposer *vpd) :
674 enumerator_base(dim,vpd) {
675 E_vertex = new evalue_p[dim];
678 virtual ~ienumerator_base() {
679 delete [] E_vertex;
682 evalue *E_num(int i, int d) {
683 return E_vertex[i + (dim-d)];
687 struct cumulator {
688 evalue *factor;
689 evalue *v;
690 dpoly_r *r;
692 cumulator(evalue *factor, evalue *v, dpoly_r *r) :
693 factor(factor), v(v), r(r) {}
695 void cumulate(barvinok_options *options);
697 virtual void add_term(const vector<int>& powers, evalue *f2) = 0;
698 virtual ~cumulator() {}
701 void cumulator::cumulate(barvinok_options *options)
703 evalue cum; // factor * 1 * E_num[0]/1 * (E_num[0]-1)/2 *...
704 evalue f;
705 evalue t; // E_num[0] - (m-1)
706 evalue *cst;
707 evalue mone;
709 if (options->lookup_table) {
710 value_init(mone.d);
711 evalue_set_si(&mone, -1, 1);
714 value_init(cum.d);
715 evalue_copy(&cum, factor);
716 value_init(f.d);
717 value_init(f.x.n);
718 value_set_si(f.d, 1);
719 value_set_si(f.x.n, 1);
720 value_init(t.d);
721 evalue_copy(&t, v);
723 if (!options->lookup_table) {
724 for (cst = &t; value_zero_p(cst->d); ) {
725 if (cst->x.p->type == fractional)
726 cst = &cst->x.p->arr[1];
727 else
728 cst = &cst->x.p->arr[0];
732 for (int m = 0; m < r->len; ++m) {
733 if (m > 0) {
734 if (m > 1) {
735 value_set_si(f.d, m);
736 emul(&f, &cum);
737 if (!options->lookup_table)
738 value_subtract(cst->x.n, cst->x.n, cst->d);
739 else
740 eadd(&mone, &t);
742 emul(&t, &cum);
744 dpoly_r_term_list& current = r->c[r->len-1-m];
745 dpoly_r_term_list::iterator j;
746 for (j = current.begin(); j != current.end(); ++j) {
747 if ((*j)->coeff == 0)
748 continue;
749 evalue *f2 = new evalue;
750 value_init(f2->d);
751 value_init(f2->x.n);
752 zz2value((*j)->coeff, f2->x.n);
753 zz2value(r->denom, f2->d);
754 emul(&cum, f2);
756 add_term((*j)->powers, f2);
759 free_evalue_refs(&f);
760 free_evalue_refs(&t);
761 free_evalue_refs(&cum);
762 if (options->lookup_table)
763 free_evalue_refs(&mone);
766 struct E_poly_term {
767 vector<int> powers;
768 evalue *E;
771 struct ie_cum : public cumulator {
772 vector<E_poly_term *> terms;
774 ie_cum(evalue *factor, evalue *v, dpoly_r *r) : cumulator(factor, v, r) {}
776 virtual void add_term(const vector<int>& powers, evalue *f2);
779 void ie_cum::add_term(const vector<int>& powers, evalue *f2)
781 int k;
782 for (k = 0; k < terms.size(); ++k) {
783 if (terms[k]->powers == powers) {
784 eadd(f2, terms[k]->E);
785 free_evalue_refs(f2);
786 delete f2;
787 break;
790 if (k >= terms.size()) {
791 E_poly_term *ET = new E_poly_term;
792 ET->powers = powers;
793 ET->E = f2;
794 terms.push_back(ET);
798 struct ienumerator : public signed_cone_consumer, public vertex_decomposer,
799 public ienumerator_base {
800 //Polyhedron *pVD;
801 mat_ZZ den;
802 mat_ZZ vertex;
803 mpq_t tcount;
804 Value tz;
806 ienumerator(Polyhedron *P, unsigned dim, Param_Polyhedron *PP) :
807 vertex_decomposer(PP, *this), ienumerator_base(dim, this) {
808 vertex.SetDims(1, dim);
810 den.SetDims(dim, dim);
811 mpq_init(tcount);
812 value_init(tz);
815 ~ienumerator() {
816 mpq_clear(tcount);
817 value_clear(tz);
820 virtual void handle(const signed_cone& sc, barvinok_options *options);
821 void reduce(evalue *factor, const mat_ZZ& num, const mat_ZZ& den_f,
822 barvinok_options *options);
825 void ienumerator::reduce(evalue *factor, const mat_ZZ& num, const mat_ZZ& den_f,
826 barvinok_options *options)
828 unsigned len = den_f.NumRows(); // number of factors in den
829 unsigned dim = num.NumCols();
830 assert(num.NumRows() == 1);
832 if (dim == 0) {
833 eadd(factor, vE[vert]);
834 return;
837 vec_ZZ den_s;
838 mat_ZZ den_r;
839 vec_ZZ num_s;
840 mat_ZZ num_p;
842 split_one(num, num_s, num_p, den_f, den_s, den_r);
844 vec_ZZ den_p;
845 den_p.SetLength(len);
847 ZZ one;
848 one = 1;
849 normalize(one, num_s, num_p, den_s, den_p, den_r);
850 if (one != 1)
851 emul(&mone, factor);
853 int only_param = 0;
854 int no_param = 0;
855 for (int k = 0; k < len; ++k) {
856 if (den_p[k] == 0)
857 ++no_param;
858 else if (den_s[k] == 0)
859 ++only_param;
861 if (no_param == 0) {
862 reduce(factor, num_p, den_r, options);
863 } else {
864 int k, l;
865 mat_ZZ pden;
866 pden.SetDims(only_param, dim-1);
868 for (k = 0, l = 0; k < len; ++k)
869 if (den_s[k] == 0)
870 pden[l++] = den_r[k];
872 for (k = 0; k < len; ++k)
873 if (den_p[k] == 0)
874 break;
876 zz2value(num_s[0], tz);
877 dpoly n(no_param, tz);
878 zz2value(den_s[k], tz);
879 dpoly D(no_param, tz, 1);
880 for ( ; ++k < len; )
881 if (den_p[k] == 0) {
882 zz2value(den_s[k], tz);
883 dpoly fact(no_param, tz, 1);
884 D *= fact;
887 dpoly_r * r = 0;
888 // if no_param + only_param == len then all powers
889 // below will be all zero
890 if (no_param + only_param == len) {
891 if (E_num(0, dim) != 0)
892 r = new dpoly_r(n, len);
893 else {
894 mpq_set_si(tcount, 0, 1);
895 one = 1;
896 n.div(D, tcount, 1);
898 if (value_notzero_p(mpq_numref(tcount))) {
899 evalue f;
900 value_init(f.d);
901 value_init(f.x.n);
902 value_assign(f.x.n, mpq_numref(tcount));
903 value_assign(f.d, mpq_denref(tcount));
904 emul(&f, factor);
905 reduce(factor, num_p, pden, options);
906 free_evalue_refs(&f);
908 return;
910 } else {
911 for (k = 0; k < len; ++k) {
912 if (den_s[k] == 0 || den_p[k] == 0)
913 continue;
915 zz2value(den_s[k], tz);
916 dpoly pd(no_param-1, tz, 1);
918 int l;
919 for (l = 0; l < k; ++l)
920 if (den_r[l] == den_r[k])
921 break;
923 if (r == 0)
924 r = new dpoly_r(n, pd, l, len);
925 else {
926 dpoly_r *nr = new dpoly_r(r, pd, l, len);
927 delete r;
928 r = nr;
932 dpoly_r *rc = r->div(D);
933 delete r;
934 r = rc;
935 if (E_num(0, dim) == 0) {
936 int common = pden.NumRows();
937 dpoly_r_term_list& final = r->c[r->len-1];
938 int rows;
939 evalue t;
940 evalue f;
941 value_init(f.d);
942 value_init(f.x.n);
943 zz2value(r->denom, f.d);
944 dpoly_r_term_list::iterator j;
945 for (j = final.begin(); j != final.end(); ++j) {
946 if ((*j)->coeff == 0)
947 continue;
948 rows = common;
949 for (int k = 0; k < r->dim; ++k) {
950 int n = (*j)->powers[k];
951 if (n == 0)
952 continue;
953 pden.SetDims(rows+n, pden.NumCols());
954 for (int l = 0; l < n; ++l)
955 pden[rows+l] = den_r[k];
956 rows += n;
958 value_init(t.d);
959 evalue_copy(&t, factor);
960 zz2value((*j)->coeff, f.x.n);
961 emul(&f, &t);
962 reduce(&t, num_p, pden, options);
963 free_evalue_refs(&t);
965 free_evalue_refs(&f);
966 } else {
967 ie_cum cum(factor, E_num(0, dim), r);
968 cum.cumulate(options);
970 int common = pden.NumRows();
971 int rows;
972 for (int j = 0; j < cum.terms.size(); ++j) {
973 rows = common;
974 pden.SetDims(rows, pden.NumCols());
975 for (int k = 0; k < r->dim; ++k) {
976 int n = cum.terms[j]->powers[k];
977 if (n == 0)
978 continue;
979 pden.SetDims(rows+n, pden.NumCols());
980 for (int l = 0; l < n; ++l)
981 pden[rows+l] = den_r[k];
982 rows += n;
984 reduce(cum.terms[j]->E, num_p, pden, options);
985 free_evalue_refs(cum.terms[j]->E);
986 delete cum.terms[j]->E;
987 delete cum.terms[j];
990 delete r;
994 static int type_offset(enode *p)
996 return p->type == fractional ? 1 :
997 p->type == flooring ? 1 : 0;
1000 static int edegree(evalue *e)
1002 int d = 0;
1003 enode *p;
1005 if (value_notzero_p(e->d))
1006 return 0;
1008 p = e->x.p;
1009 int i = type_offset(p);
1010 if (p->size-i-1 > d)
1011 d = p->size - i - 1;
1012 for (; i < p->size; i++) {
1013 int d2 = edegree(&p->arr[i]);
1014 if (d2 > d)
1015 d = d2;
1017 return d;
1020 void ienumerator::handle(const signed_cone& sc, barvinok_options *options)
1022 assert(sc.det == 1);
1023 assert(sc.rays.NumRows() == dim);
1025 lattice_point(V, sc.rays, vertex[0], E_vertex, options);
1027 den = sc.rays;
1029 evalue one;
1030 value_init(one.d);
1031 evalue_set_si(&one, sc.sign, 1);
1032 reduce(&one, vertex, den, options);
1033 free_evalue_refs(&one);
1035 for (int i = 0; i < dim; ++i)
1036 if (E_vertex[i]) {
1037 free_evalue_refs(E_vertex[i]);
1038 delete E_vertex[i];
1042 struct bfenumerator : public vertex_decomposer, public bf_base,
1043 public ienumerator_base {
1044 evalue *factor;
1046 bfenumerator(Polyhedron *P, unsigned dim, Param_Polyhedron *PP) :
1047 vertex_decomposer(PP, *this),
1048 bf_base(dim), ienumerator_base(dim, this) {
1049 lower = 0;
1050 factor = NULL;
1053 ~bfenumerator() {
1056 virtual void handle(const signed_cone& sc, barvinok_options *options);
1057 virtual void base(mat_ZZ& factors, bfc_vec& v);
1059 bfc_term_base* new_bf_term(int len) {
1060 bfe_term* t = new bfe_term(len);
1061 return t;
1064 virtual void set_factor(bfc_term_base *t, int k, int change) {
1065 bfe_term* bfet = static_cast<bfe_term *>(t);
1066 factor = bfet->factors[k];
1067 assert(factor != NULL);
1068 bfet->factors[k] = NULL;
1069 if (change)
1070 emul(&mone, factor);
1073 virtual void set_factor(bfc_term_base *t, int k, mpq_t &q, int change) {
1074 bfe_term* bfet = static_cast<bfe_term *>(t);
1075 factor = bfet->factors[k];
1076 assert(factor != NULL);
1077 bfet->factors[k] = NULL;
1079 evalue f;
1080 value_init(f.d);
1081 value_init(f.x.n);
1082 if (change)
1083 value_oppose(f.x.n, mpq_numref(q));
1084 else
1085 value_assign(f.x.n, mpq_numref(q));
1086 value_assign(f.d, mpq_denref(q));
1087 emul(&f, factor);
1088 free_evalue_refs(&f);
1091 virtual void set_factor(bfc_term_base *t, int k, const QQ& c, int change) {
1092 bfe_term* bfet = static_cast<bfe_term *>(t);
1094 factor = new evalue;
1096 evalue f;
1097 value_init(f.d);
1098 value_init(f.x.n);
1099 zz2value(c.n, f.x.n);
1100 if (change)
1101 value_oppose(f.x.n, f.x.n);
1102 zz2value(c.d, f.d);
1104 value_init(factor->d);
1105 evalue_copy(factor, bfet->factors[k]);
1106 emul(&f, factor);
1107 free_evalue_refs(&f);
1110 void set_factor(evalue *f, int change) {
1111 if (change)
1112 emul(&mone, f);
1113 factor = f;
1116 virtual void insert_term(bfc_term_base *t, int i) {
1117 bfe_term* bfet = static_cast<bfe_term *>(t);
1118 int len = t->terms.NumRows()-1; // already increased by one
1120 bfet->factors.resize(len+1);
1121 for (int j = len; j > i; --j) {
1122 bfet->factors[j] = bfet->factors[j-1];
1123 t->terms[j] = t->terms[j-1];
1125 bfet->factors[i] = factor;
1126 factor = NULL;
1129 virtual void update_term(bfc_term_base *t, int i) {
1130 bfe_term* bfet = static_cast<bfe_term *>(t);
1132 eadd(factor, bfet->factors[i]);
1133 free_evalue_refs(factor);
1134 delete factor;
1137 virtual bool constant_vertex(int dim) { return E_num(0, dim) == 0; }
1139 virtual void cum(bf_reducer *bfr, bfc_term_base *t, int k, dpoly_r *r,
1140 barvinok_options *options);
1143 enumerator_base *enumerator_base::create(Polyhedron *P, unsigned dim,
1144 Param_Polyhedron *PP,
1145 barvinok_options *options)
1147 enumerator_base *eb;
1149 if (options->incremental_specialization == BV_SPECIALIZATION_BF)
1150 eb = new bfenumerator(P, dim, PP);
1151 else if (options->incremental_specialization == BV_SPECIALIZATION_DF)
1152 eb = new ienumerator(P, dim, PP);
1153 else
1154 eb = new enumerator(P, dim, PP);
1156 return eb;
1159 struct bfe_cum : public cumulator {
1160 bfenumerator *bfe;
1161 bfc_term_base *told;
1162 int k;
1163 bf_reducer *bfr;
1165 bfe_cum(evalue *factor, evalue *v, dpoly_r *r, bf_reducer *bfr,
1166 bfc_term_base *t, int k, bfenumerator *e) :
1167 cumulator(factor, v, r), told(t), k(k),
1168 bfr(bfr), bfe(e) {
1171 virtual void add_term(const vector<int>& powers, evalue *f2);
1174 void bfe_cum::add_term(const vector<int>& powers, evalue *f2)
1176 bfr->update_powers(powers);
1178 bfc_term_base * t = bfe->find_bfc_term(bfr->vn, bfr->npowers, bfr->nnf);
1179 bfe->set_factor(f2, bfr->l_changes % 2);
1180 bfe->add_term(t, told->terms[k], bfr->l_extra_num);
1183 void bfenumerator::cum(bf_reducer *bfr, bfc_term_base *t, int k,
1184 dpoly_r *r, barvinok_options *options)
1186 bfe_term* bfet = static_cast<bfe_term *>(t);
1187 bfe_cum cum(bfet->factors[k], E_num(0, bfr->d), r, bfr, t, k, this);
1188 cum.cumulate(options);
1191 void bfenumerator::base(mat_ZZ& factors, bfc_vec& v)
1193 for (int i = 0; i < v.size(); ++i) {
1194 assert(v[i]->terms.NumRows() == 1);
1195 evalue *factor = static_cast<bfe_term *>(v[i])->factors[0];
1196 eadd(factor, vE[vert]);
1197 delete v[i];
1201 void bfenumerator::handle(const signed_cone& sc, barvinok_options *options)
1203 assert(sc.det == 1);
1204 assert(sc.rays.NumRows() == enumerator_base::dim);
1206 bfe_term* t = new bfe_term(enumerator_base::dim);
1207 vector< bfc_term_base * > v;
1208 v.push_back(t);
1210 t->factors.resize(1);
1212 t->terms.SetDims(1, enumerator_base::dim);
1213 lattice_point(V, sc.rays, t->terms[0], E_vertex, options);
1215 // the elements of factors are always lexpositive
1216 mat_ZZ factors;
1217 int s = setup_factors(sc.rays, factors, t, sc.sign);
1219 t->factors[0] = new evalue;
1220 value_init(t->factors[0]->d);
1221 evalue_set_si(t->factors[0], s, 1);
1222 reduce(factors, v, options);
1224 for (int i = 0; i < enumerator_base::dim; ++i)
1225 if (E_vertex[i]) {
1226 free_evalue_refs(E_vertex[i]);
1227 delete E_vertex[i];
1231 static evalue* barvinok_enumerate_ev_f(Polyhedron *P, Polyhedron* C,
1232 barvinok_options *options);
1234 /* Destroys C */
1235 static evalue* barvinok_enumerate_cst(Polyhedron *P, Polyhedron* C,
1236 struct barvinok_options *options)
1238 evalue *eres;
1240 if (emptyQ2(C)) {
1241 Polyhedron_Free(C);
1242 return evalue_zero();
1245 ALLOC(evalue, eres);
1246 value_init(eres->d);
1247 value_set_si(eres->d, 0);
1248 eres->x.p = new_enode(partition, 2, C->Dimension);
1249 EVALUE_SET_DOMAIN(eres->x.p->arr[0],
1250 DomainConstraintSimplify(C, options->MaxRays));
1251 value_set_si(eres->x.p->arr[1].d, 1);
1252 value_init(eres->x.p->arr[1].x.n);
1253 if (emptyQ2(P))
1254 value_set_si(eres->x.p->arr[1].x.n, 0);
1255 else
1256 barvinok_count_with_options(P, &eres->x.p->arr[1].x.n, options);
1258 return eres;
1261 static evalue* enumerate(Polyhedron *P, Polyhedron* C,
1262 struct barvinok_options *options)
1264 Polyhedron *next;
1265 Polyhedron *Porig = P;
1266 Polyhedron *Corig = C;
1267 Polyhedron *CEq = NULL, *rVD;
1268 int r = 0;
1269 unsigned nparam = C->Dimension;
1270 evalue *eres;
1271 Matrix *CP = NULL;
1273 evalue factor;
1274 value_init(factor.d);
1275 evalue_set_si(&factor, 1, 1);
1277 /* for now */
1278 POL_ENSURE_FACETS(P);
1279 POL_ENSURE_VERTICES(P);
1280 POL_ENSURE_FACETS(C);
1281 POL_ENSURE_VERTICES(C);
1283 if (C->Dimension == 0 || emptyQ(P) || emptyQ(C)) {
1284 constant:
1285 if (CEq == Porig)
1286 CEq = Polyhedron_Copy(CEq);
1287 eres = barvinok_enumerate_cst(P, CEq ? CEq : Polyhedron_Copy(C), options);
1288 out:
1289 if (CP) {
1290 evalue_backsubstitute(eres, CP, options->MaxRays);
1291 Matrix_Free(CP);
1294 emul(&factor, eres);
1295 if (options->approximation_method == BV_APPROX_DROP) {
1296 if (options->polynomial_approximation == BV_APPROX_SIGN_UPPER)
1297 evalue_frac2polynomial(eres, 1, options->MaxRays);
1298 if (options->polynomial_approximation == BV_APPROX_SIGN_LOWER)
1299 evalue_frac2polynomial(eres, -1, options->MaxRays);
1300 if (options->polynomial_approximation == BV_APPROX_SIGN_APPROX)
1301 evalue_frac2polynomial(eres, 0, options->MaxRays);
1303 reduce_evalue(eres);
1304 free_evalue_refs(&factor);
1305 if (P != Porig)
1306 Domain_Free(P);
1307 if (C != Corig)
1308 Polyhedron_Free(C);
1310 return eres;
1312 if (Polyhedron_is_unbounded(P, nparam, options->MaxRays))
1313 goto constant;
1315 if (P->Dimension == nparam) {
1316 CEq = P;
1317 P = Universe_Polyhedron(0);
1318 goto constant;
1320 if (P->NbEq != 0 || C->NbEq != 0) {
1321 Polyhedron *Q = P;
1322 Polyhedron *D = C;
1323 remove_all_equalities(&P, &C, &CP, NULL, nparam, options->MaxRays);
1324 if (C != D && D != Corig)
1325 Polyhedron_Free(D);
1326 if (P != Q && Q != Porig)
1327 Domain_Free(Q);
1328 eres = enumerate(P, C, options);
1329 goto out;
1332 Polyhedron *T = Polyhedron_Factor(P, nparam, NULL, options->MaxRays);
1333 if (T || (P->Dimension == nparam+1)) {
1334 Polyhedron *Q;
1335 Polyhedron *C2;
1336 for (Q = T ? T : P; Q; Q = Q->next) {
1337 Polyhedron *next = Q->next;
1338 Q->next = NULL;
1340 Polyhedron *QC = Q;
1341 if (Q->Dimension != C->Dimension)
1342 QC = Polyhedron_Project(Q, nparam);
1344 C2 = C;
1345 C = DomainIntersection(C, QC, options->MaxRays);
1346 if (C2 != Corig)
1347 Polyhedron_Free(C2);
1348 if (QC != Q)
1349 Polyhedron_Free(QC);
1351 Q->next = next;
1354 if (T) {
1355 if (P != Porig)
1356 Polyhedron_Free(P);
1357 P = T;
1358 if (T->Dimension == C->Dimension) {
1359 P = T->next;
1360 T->next = NULL;
1361 Polyhedron_Free(T);
1365 next = P->next;
1366 P->next = NULL;
1367 eres = barvinok_enumerate_ev_f(P, C, options);
1368 P->next = next;
1370 if (P->next) {
1371 Polyhedron *Q;
1372 evalue *f;
1374 for (Q = P->next; Q; Q = Q->next) {
1375 Polyhedron *next = Q->next;
1376 Q->next = NULL;
1378 f = barvinok_enumerate_ev_f(Q, C, options);
1379 emul(f, eres);
1380 evalue_free(f);
1382 Q->next = next;
1386 goto out;
1389 evalue* barvinok_enumerate_with_options(Polyhedron *P, Polyhedron* C,
1390 struct barvinok_options *options)
1392 Polyhedron *next, *Cnext, *C1;
1393 Polyhedron *Corig = C;
1394 evalue *eres;
1396 if (P->next)
1397 fprintf(stderr,
1398 "barvinok_enumerate: input is a union; only first polyhedron is enumerated\n");
1400 if (C->next)
1401 fprintf(stderr,
1402 "barvinok_enumerate: context is a union; only first polyhedron is considered\n");
1404 Cnext = C->next;
1405 C->next = NULL;
1406 C1 = Polyhedron_Project(P, C->Dimension);
1407 C = DomainIntersection(C, C1, options->MaxRays);
1408 Polyhedron_Free(C1);
1409 next = P->next;
1410 P->next = NULL;
1412 if (options->approximation_method == BV_APPROX_BERNOULLI ||
1413 options->summation == BV_SUM_BERNOULLI)
1414 eres = Bernoulli_sum(P, C, options);
1415 else
1416 eres = enumerate(P, C, options);
1417 Domain_Free(C);
1419 P->next= next;
1420 Corig->next = Cnext;
1422 return eres;
1425 evalue* barvinok_enumerate_ev(Polyhedron *P, Polyhedron* C, unsigned MaxRays)
1427 evalue *E;
1428 barvinok_options *options = barvinok_options_new_with_defaults();
1429 options->MaxRays = MaxRays;
1430 E = barvinok_enumerate_with_options(P, C, options);
1431 barvinok_options_free(options);
1432 return E;
1435 evalue *Param_Polyhedron_Enumerate(Param_Polyhedron *PP, Polyhedron *P,
1436 Polyhedron *C,
1437 struct barvinok_options *options)
1439 evalue *eres;
1440 Param_Domain *D;
1441 unsigned nparam = C->Dimension;
1442 unsigned dim = P->Dimension - nparam;
1444 int nd;
1445 for (nd = 0, D=PP->D; D; ++nd, D=D->next);
1446 evalue_section *s = new evalue_section[nd];
1448 enumerator_base *et = NULL;
1449 try_again:
1450 if (et)
1451 delete et;
1453 et = enumerator_base::create(P, dim, PP, options);
1455 Polyhedron *TC = true_context(P, C, options->MaxRays);
1456 FORALL_REDUCED_DOMAIN(PP, TC, nd, options, i, D, rVD)
1457 Param_Vertices *V;
1459 s[i].E = evalue_zero();
1460 s[i].D = rVD;
1462 FORALL_PVertex_in_ParamPolyhedron(V,D,PP) // _i is internal counter
1463 if (!et->vE[_i])
1464 try {
1465 et->decompose_at(V, _i, options);
1466 } catch (OrthogonalException &e) {
1467 FORALL_REDUCED_DOMAIN_RESET;
1468 for (; i >= 0; --i) {
1469 evalue_free(s[i].E);
1470 Domain_Free(s[i].D);
1472 goto try_again;
1474 eadd(et->vE[_i] , s[i].E);
1475 END_FORALL_PVertex_in_ParamPolyhedron;
1476 evalue_range_reduction_in_domain(s[i].E, rVD);
1477 END_FORALL_REDUCED_DOMAIN
1478 Polyhedron_Free(TC);
1480 delete et;
1481 eres = evalue_from_section_array(s, nd);
1482 delete [] s;
1484 return eres;
1487 static evalue* barvinok_enumerate_ev_f(Polyhedron *P, Polyhedron* C,
1488 barvinok_options *options)
1490 unsigned nparam = C->Dimension;
1491 bool do_scale = options->approximation_method == BV_APPROX_SCALE;
1493 if (options->approximation_method == BV_APPROX_VOLUME)
1494 return Param_Polyhedron_Volume(P, C, options);
1496 if (P->Dimension - nparam == 1 && !do_scale)
1497 return ParamLine_Length(P, C, options);
1499 Param_Polyhedron *PP = NULL;
1500 evalue *eres;
1502 if (do_scale) {
1503 eres = scale_bound(P, C, options);
1504 if (eres)
1505 return eres;
1508 PP = Polyhedron2Param_Polyhedron(P, C, options);
1510 if (do_scale)
1511 eres = scale(PP, P, C, options);
1512 else
1513 eres = Param_Polyhedron_Enumerate(PP, P, C, options);
1515 if (PP)
1516 Param_Polyhedron_Free(PP);
1518 return eres;
1521 Enumeration* barvinok_enumerate(Polyhedron *P, Polyhedron* C, unsigned MaxRays)
1523 evalue *EP = barvinok_enumerate_ev(P, C, MaxRays);
1525 return partition2enumeration(EP);
1528 evalue* barvinok_enumerate_union(Polyhedron *D, Polyhedron* C, unsigned MaxRays)
1530 evalue *EP;
1531 gen_fun *gf = barvinok_enumerate_union_series(D, C, MaxRays);
1532 EP = *gf;
1533 delete gf;
1534 return EP;
1537 evalue *barvinok_summate(evalue *e, int nvar, struct barvinok_options *options)
1539 if (options->summation == BV_SUM_EULER)
1540 return euler_summate(e, nvar, options);
1541 else if (options->summation == BV_SUM_BERNOULLI)
1542 return Bernoulli_sum_evalue(e, nvar, options);
1543 else
1544 return evalue_sum(e, nvar, options->MaxRays);