/* 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: proj.cc,v 1.26 2005/09/01 09:36:37 joswig Exp $"

#include <cstdlib>
#include <Rational.h>
#include <argv_options.h>
#include <Poly.h>
#include <Vector.h>
#include <Matrix.h>
#include <ListMatrix.h>
#include <linalg.h>
#include <Array.h>

enum { negation, no_fourier_motzkin };

namespace polymake { namespace polytope {

   void proj(Poly& p_out, Poly& p_in, const Array<int>& indices, const argv_option* options)
{
   const int ambient_dim=p_in.give("AMBIENT_DIM");
   bool points_read=false, inequalities_read=false;
   
   Matrix<Rational> Points, Inequalities, Equations;

   Set<int> coords;   // set of columns which remain in the projection
   if (indices.empty() || options[no_fourier_motzkin]) {
      p_in.give("VERTICES | POINTS") >> Points;
      points_read=true;
   }
   if (indices.empty())
      coords=basis_cols(Points);
   else {
      for (Entire< Array<int> >::const_iterator i=entire(indices); !i.at_end(); ++i) {
	 if (*i<1 || *i>ambient_dim)
	    throw std::runtime_error("index out of range");
	 coords+=*i;
      }
      if (options[negation])
	 coords=range(0,ambient_dim)-coords;
      else 
	 coords+=0;
   }

   if (points_read || (p_in.lookup("VERTICES | POINTS") >> Points))
      p_out.take("POINTS") << Points.minor(All,coords);

   if (!options[no_fourier_motzkin]) {
      if (p_in.lookup("FACETS | INEQUALITIES") >> Inequalities)
	 inequalities_read=true;
      
      if ((p_in.lookup("AFFINE_HULL | EQUATIONS") >> Equations) && Equations.rows()) {
	 inequalities_read=true;
	 Inequalities /= Equations / (-Equations);
      }
      
      if (inequalities_read) {
	 Set<int> eliminate_coords=range(0,ambient_dim)-coords; // perform Fourier-Motzkin elimination on these columns
	 for (Set<int>::reverse_iterator c=eliminate_coords.rbegin(); c!=eliminate_coords.rend(); ++c) {
	    Set<int> negative, zero, positive;
	    // normalize Inequalities such that there is a -1,0, or 1 in the next column to be eliminated
	    for (int i=0; i<Inequalities.rows(); ++i) {
	       Rational x=Inequalities(i,*c);
	       if (sign(x)!=0) {
		  if (sign(x)<0)
		     negative += i;
		  else
		     positive += i;
		  Inequalities[i] /= abs(x);
	       } else
		  zero += i;
	    }
	    Set<int> remaining_coords=range(0,Inequalities.cols()-1)-(*c);
	    Inequalities = Inequalities.minor(All,remaining_coords);
	    ListMatrix< Vector<Rational> > Combined_Ineqs=Inequalities.minor(zero,All);
	    for (Entire< Set<int> >::const_iterator i=entire(negative); !i.at_end(); ++i)
	       for (Entire< Set<int> >::const_iterator k=entire(positive); !k.at_end(); ++k)
		  Combined_Ineqs /= Inequalities[*i]+Inequalities[*k];
	    Inequalities = Combined_Ineqs;
	 }
	 p_out.take("INEQUALITIES") << Inequalities;
      }
   }
}

} }

using namespace polymake;

/** @file proj
 *
 *  Orthogonally project a polyhedron to a coordinate subspace.
 *
 *  @synopsis proj <output_file> <input_file> [-] [ <k1> [ <k2> ... ] ] [-nofm]
 *  @usage    The subspace the polyhedron is projected on is given by the coordinate indices $k<sub>i</sub>$.
 *            The dash argument inverts the coordinate list. If no coordinates are specified the polytope is
 *            projected by omitting "redundant" columns, i.e., the projection becomes full-dimensional without
 *            changing the combinatorial type.
 *            The client scans for all coordinate sections and produces proper output from each.
 *            If a description in terms of inequalities is found, the client performs Fourier-Motzkin elimination
 *            unless the -nofm option is set.  Setting the -nofm option is useful if the corank of the projection
 *            is large; in this case the number of inequalities produced grows quickly.
 *
 *  @reading  AMBIENT_DIM, POINTS | VERTICES, FACETS | INEQUALITIES, AFFINE_HULL | EQUATIONS
 *  @writing  POINTS, INEQUALITIES
 *
 *  @index clients Producing a new polyhedron from others
 */

int main(int argc, const char *argv[]) {
   argv_option options[]={ {"-"}, { "-nofm" } };
   if (!extract_options(argc,argv,2,options) || argc<3) {
      cerr << "usage: " << argv[0] << " <outfile> <infile> [ [-] <k1> [<k2> ...] ] [-nofm]" << endl;
      return 1;
   }
   try {
      Poly p_in(argv[2], ios::in);
      Poly p_out(argv[1], ios::out | ios::trunc);
      const Array<int> indices(argc-3, attach_converter<int>(ptr2container(argv+3)).begin());
      polytope::proj(p_out, p_in, indices, options);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
