/* Copyright (c) 1997-2006
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
   http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
*/

#ident "$Project: polymake $$Id: associahedron.cc,v 1.13 2006/03/09 16:21:35 gawrilow Exp $"

#include <cstdlib>
#include <Poly.h>
#include <Rational.h>
#include <Matrix.h>

namespace polymake {
namespace polytope {
   void associahedron(Poly& p, int d)
   {
      const int n = d+2; // ambient dimension

      p.take("AMBIENT_DIM") << n;
      p.take("DIM") << d;

      // two equations
      Matrix<Rational> EQ(2,n+1);
      const Rational
	 n2=n*n, n3=n2*n, n4=n3*n, n5=n4*n; // powers of n
      EQ(0,0)=-(n4-n2)/4;
      for (int i=1; i<=n; ++i) EQ(0,i)=i;
      EQ(1,0)=-(6*n5-5*n3-n)/30;
      for (int i=1; i<=n; ++i) EQ(1,i)=i*i;
      p.take("EQUATIONS") << EQ;

      // facets
      Matrix<Rational> F(n*(n-1)/2-1, n+1);
      Rows< Matrix<Rational> >::iterator f=rows(F).begin();
      for (int i=0; i<n-1; ++i)
	 for (int j=i+2; j<=n-(i==0); ++j, ++f) {
	    (*f)[0]=-Integer::binom(j-i+1,3)*Rational(3*(j-i)*(j-i)-2, 10);
	    for (int k=i+1; k<j; ++k) (*f)[k]=(k-i)*(j-k);
	 }
      p.take("INEQUALITIES") << F;
   }
} }

using namespace polymake;

/** @file associahedron
 *
 *  Produce a $d$-dimensional associahedron (or Stasheff polytope).
 *  We use the facet description given in Ziegler's book on polytopes, section 9.2.
 *
 *  @synopsis associahedron <file> <d>
 *
 *  @writing  AMBIENT_DIM, DIM, EQUATIONS, INEQUALITIES
 *
 *  @index clients Producing from scratch
 */

int main(int argc, const char *argv[]) {
   if (argc!=3) {
      cerr << "usage: " << argv[0] << " <file> <dimension>" << endl;
      return 1;
   }
   try {
      // dimensions; note that this description is not full-dimensional
      const int d = atoi(argv[2]);

      Poly p(argv[1], ios::out | ios::trunc);
      polytope::associahedron(p, d);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}


