/* Copyright (c) 1997-2004
   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: Goldfarb.cc,v 1.8 2004/06/22 16:23:11 gawrilow Exp $"

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

namespace polymake {
namespace polytope {
   void Goldfarb(Poly& p, int d, const Rational& e, const Rational& g)
   {
      Matrix<Rational> IE(4+2*(d-2),d+1);

      // the first 4 inequaleties
      IE(0,1)=1;
      IE(1,0)=1; IE(1,1)=-1;
      IE(2,1)=-e; IE(2,2)=1;
      IE(3,0)=1; IE(3,1)=-e; IE(3,2)=-1;

      for (int k=2; k<d; ++k) {
	 int i=k*2;                  // row index
	              IE(i,k-1)=e*g;   IE(i,k)=-e;   IE(i,k+1)=1;
	 IE(i+1,0)=1; IE(i+1,k-1)=e*g; IE(i+1,k)=-e; IE(i+1,k+1)=-1;
      }

      p.take("INEQUALITIES") << IE;

      Vector<Rational> LO=unit_vector<Rational>(d+1,d);
      p.take("LINEAR_OBJECTIVE") << LO;
   }
} }

using namespace polymake;

/** @file Goldfarb
 *
 *  Produces a $d$-dimensional Goldfarb cube if $e<1/2$ and $g<=1/4e$.
 *  The Goldfarb cube is a combinatorial cube and yields a bad example
 *  for the Simplex Algorithm using the Shadow Vertex Pivoting Strategy.
 *  Here we use the description as a deformed product due to Amenta and Ziegler. 
 *  For $e<1/2$ and $g=0$ we obtain the Klee-Minty cubes.
 *
 *  @synopsis Goldfarb <file> <d> [<e>] [<g>]
 *
 *  @writing INEQUALITIES, LINEAR_OBJECTIVE
 *
 *  @index clients Producing from scratch
 *
 *  @author Niko Witte <witte@math.tu-berlin.de>
 */

int main(int argc, char *argv[]) {
   if (argc<3 || argc>5) {
      cerr << "usage: " << argv[0] << " <file> <dimension> [<e>] [<g>]" << endl;
      return 1;
   }
   try {
      const int d=atoi(argv[2]),       // dimension
	        m=8 * sizeof(int) - 2; // maximal dimension that can be handled

      const Rational e= argc>3 ? Rational(argv[3]) : Rational(1,3),
	             g= argc>4 ? Rational(argv[4]) : e/4;

      // restriction on d
      if (d < 1 || d > m) {
	 cerr << argv[0] << ": Goldfarb(d): 1 <= d <= " << m << endl;
	 return 1;
      }

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