/* 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: minimal_vertex_angle.cc,v 1.1 2005/07/07 07:49:09 joswig Exp $"

#include <cmath>
#include <cstdlib>

#include <Poly.h>
#include <Matrix.h>
#include <Vector.h>
#include <SparseMatrix.h>
#include <transform.h>

namespace polymake { namespace polytope {

void minimal_vertex_angle(Poly& p)
{
   const Matrix<double> V=p.give("VERTICES");
   const Vector<double> origin=p.give("VERTEX_BARYCENTER");   // must be affine
   const int d = origin.dim();

   SparseMatrix<double> tau=unit_matrix<double>(d);
   tau[0].slice(1)=-origin.slice(1);
   Poly spherical_p(0, ios::in | ios::out | ios::trunc, "RationalPolytope");
   polytope::transform(spherical_p, p, "", tau);
   Matrix<double> spherical_V=spherical_p.give("VERTICES");
   spherical_V=spherical_V.minor(All,range(1,d-1));

   const int n=spherical_V.rows();
   for (int i=0; i<n; ++i)
      spherical_V[i]/=sqrt(sqr(spherical_V[i]));

   double min_angle=2.0*acos(0.0); // pi

   for (int i=0; i<n; ++i)
      for (int j=i+1; j<n; ++j) {
	 double phi=acos(V[i]*V[j]); // phi==0 means opposite
	 if (0<phi && phi<min_angle) min_angle=phi; 
      }

   p.take("MINIMAL_VERTEX_ANGLE") << min_angle;
}

} }

using namespace polymake;

/** @file minimal_vertex_angle
 *
 *  @synopsis minimal_vertex_angle <file>
 *
 *  @reading  VERTICES, VERTEX_BARYCENTER
 *  @writing  MINIMAL_VERTEX_ANGLE
 */

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