/* 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: compress_incidence.cc,v 1.13 2006/01/20 15:47:02 gawrilow Exp $"

#include <Rational.h>
#include <Poly.h>
#include <linalg.h>
#include <IncidenceMatrix.h>
#include <FacetList.h>
#include <argv_options.h>
#include <sstream>

namespace polymake { namespace polytope {

/// @retval row indices of (non-facets, hidden equations), first includes second
template <typename IM>
std::pair< Set<int>, Set<int> >
compress_incidence(const GenericIncidenceMatrix<IM>& VIF)
{
   Set<int> non_facets, hidden_equations;
   const int nv=VIF.cols();
   FacetList facets(nv);

   for (typename Entire< Rows<IM> >::const_iterator f=entire(rows(VIF)); !f.at_end(); ++f) {
      if (f->size() == nv) {
	 facets.skip_facet_id();
	 non_facets.push_back(f.index());
	 hidden_equations.push_back(f.index());
      } else if (! facets.replaceMax(*f, inserter(non_facets))) {
	 non_facets.push_back(f.index());
      }
   }
   return std::make_pair(non_facets, hidden_equations);
}

template <typename Coord>
void compress_incidence_primal(Poly& p)
{
   Matrix<Coord> V=p.give("POINTS");
   IncidenceMatrix<> VIF=p.give("POINTS_IN_FACETS");
   cols(VIF).resize(V.rows());	// for the exotic case of the last point(s) being strict inner points

   const std::pair< Set<int>, Set<int> > non_vertices=compress_incidence(T(VIF));
   if (!non_vertices.second.empty() && VIF.cols()>1) {
      std::ostringstream err_msg;
      wrap(err_msg) << "point(s) " << non_vertices.second << " are contained in all facets";
      throw std::runtime_error(err_msg.str());
   }
   if (!non_vertices.first.empty()) {
      VIF=VIF.minor(All, ~non_vertices.first);
      V=V.minor(~non_vertices.first,All);
   }
   p.take("VERTICES") << V;
   p.take("VERTICES_IN_FACETS") << VIF;
}

template <typename Coord>
void compress_incidence_dual(Poly& p)
{
   Matrix<Coord> F=p.give("INEQUALITIES");
   IncidenceMatrix<> VIF=p.give("VERTICES_IN_INEQUALITIES");
   rows(VIF).resize(F.rows()); // for the exotic case of the last hyperplane(s) being strict far hyperplanes

   // we might need the far hyperplane for unbounded polyhedra
   const Set<int> ff=p.give("FAR_FACE");
   if (!ff.empty()) {
      VIF /= ff;
      F /= unit_vector<Coord>(F.cols(),0);
   }

   const std::pair< Set<int>, Set<int> > non_facets=compress_incidence(VIF);

   // we still have to take care of the equations
   Matrix<Coord> E=p.lookup("EQUATIONS");
   E /= F.minor(non_facets.second,All);

   Set<int> b=basis_rows(E);	// compute an affine hull
   if (b.size() < E.rows()) E=E.minor(b,All);

   if (!non_facets.first.empty()) {
      VIF=VIF.minor(~non_facets.first, All);
      F=F.minor(~non_facets.first, All);
   }

   p.take("FACETS") << F;
   p.take("AFFINE_HULL") << E;
   p.take("VERTICES_IN_FACETS") << VIF;
}

} }

using namespace polymake;

/** @file compress_incidence
 *
 *  Detect the vertices (dually: facets) among the given points (dually: inequalities).
 *  Used as postprocessing after the convex hull computation.
 *
 *  @synopsis compress_incidence <file> { -primal, -dual }
 *
 *  @reading  in primal mode: POINTS_IN_FACETS, POINTS
 *            in dual mode:   VERTICES_IN_INEQUALITIES, INEQUALITIES, FAR_FACE, EQUATIONS
 *  @writing  in primal mode: VERTICES_IN_FACETS, VERTICES
 *            in dual mode:   VERTICES_IN_FACETS, FACETS, AFFINE_HULL
 */

int main(int argc, const char *argv[])
{
   argv_option options[]={ { "-primal" }, { "-dual" } };
   enum { primal, dual };
   if (argc!=3 || !extract_options(argc,argv,1,options) || argc!=2) {
      cerr << "usage: " << argv[0] << " <file> { -primal, -dual }" << endl;
      return 1;
   }
   try {
      Poly p(argv[1], ios::in | ios::out);
      if (p.isa("RationalPolytope")) {
	 if (options[primal])
	    polytope::compress_incidence_primal<Rational>(p);
	 else
	    polytope::compress_incidence_dual<Rational>(p);

      } else if (p.isa("FloatPolytope")) {
	 p.lookup("EPSILON") >> conv<double,bool>::global_epsilon;
	 if (options[primal])
	    polytope::compress_incidence_primal<double>(p);
	 else
	    polytope::compress_incidence_dual<double>(p);

      } else {
	 throw std::runtime_error("don't know how to proceed with " + p.type());
      }
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
