/* 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: gale_vertices.cc,v 1.15 2004/09/20 17:11:50 gawrilow Exp $"

#include <algorithm>
#include <Rational.h>
#include <Poly.h>
#include <Vector.h>
#include <Matrix.h>
#include <linalg.h>
#include <random_generators.h>

namespace polymake { namespace polytope {

void gale_vertices(Poly& p)
{
   Matrix<Rational> G=p.give("GALE_TRANSFORM");
   const int n=G.rows();

   UniformRNG<Rational> random(0, log2_ceil(n)+1);

   Vector<Rational> y(G.cols(), Rational(1)), G_y(G.rows());

   bool feasible;
   do {
      G_y=G*y;
      feasible=true;
      for (Entire< Vector<Rational> >::iterator g_y=std::find_if(entire(G_y), operations::logical_not());
	   !g_y.at_end();  g_y=std::find_if(++g_y, operations::logical_not())) {
	 if (G[g_y - G_y.begin()]) {
	    std::copy(translate(random, Rational(-1,2)).begin(), entire(y));
	    feasible=false;
	    break;
	 }
      }
   } while (!feasible);

   Matrix<Rational> P=null_space(y);
   orthogonalize(entire(rows(P)));
   y /= sqr(y);

   Matrix<double> GV(G.rows(), G.cols());

   for (int i=0; i<n; ++i)
      if ( (GV(i,0)=sign(G_y[i])) ) {
	 GV[i].slice(1)=P*(G[i]/G_y[i] - y);
      }

   p.take("GALE_VERTICES") << GV;
}

} }

using namespace polymake;

/** @file gale_vertices
 *
 *  Calculate the coordinates of points for an affine Gale diagram.
 *  First the projection vector $(1, 1, ... )$ is tried, then random vectors.
 *
 *  @synopsis gale_vertices <file>
 *
 *  @reading  GALE_TRANSFORM
 *  @writing  GALE_VERTICES
 */

int main(int argc, const char *argv[]) {
   if (argc != 2 ) {
      cerr << "usage: " << argv[0] << " <file>" << endl;
      return 1;
   }
   try {
      Poly p(argv[1], ios::in | ios::out);
      polytope::gale_vertices(p);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
