/* 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: pseudo-simplex.cc,v 1.26 2004/11/19 12:11:58 gawrilow Exp $"

#include <cstdlib>
#include <list>
#include <Rational.h>
#include <Poly.h>
#include <Vector.h>
#include <Graph.h>
#include <Matrix.h>
#include <Set.h>
#include <argv_options.h>

namespace polymake { namespace polytope {

void pseudo_simplex(Poly& p, bool maximize)
{
   const Matrix<Rational> V=p.give("VERTICES");

   typedef Graph<bool> graph;	// node(x)==true => already visited
   graph G;
   p.give("GRAPH") >> neighborhood_matrix(G);

   const Vector<Rational> objective=p.give("LINEAR_OBJECTIVE");
   const Set<int> far_face=p.give("FAR_FACE");
 
   const int n_vertices = V.rows();

   // start with an affine point
   int current_vertex=(sequence(0,n_vertices)-far_face).front();

   Rational opt=objective * V[current_vertex];
   Set<int> optimal_face=scalar2set(current_vertex);
   G.node(current_vertex) = true;

   bool better, unbounded=false;
   const int sense(maximize ? 1 : -1);

   do {
      better = false;
      // steepest ascent/descent
      for (Entire<graph::out_edge_list>::iterator v=entire(G.out_edges(current_vertex));  !v.at_end();  ++v) {
	 const int neighbor=v.to_node();
	 if (G.node(neighbor))  // this neighbor can't be better
	    continue;
	 if (V(neighbor,0)) {
	    G.node(neighbor)=true;
	    const Rational value = objective * V[neighbor];
	    int diff=sign(value - opt);
	    if (diff == sense) { // this one is better
	       current_vertex = neighbor;
	       opt = value;
	       optimal_face = scalar2set(current_vertex);
	       better = true;
	    } else if (diff==0) { // also belongs to optimal_face
	       optimal_face += neighbor;
	    }
	 } else { // check for an increasing/decreasing unbounded edge
	    if (sign(objective * V[neighbor]) == sense) {
	       unbounded = true;
	       break;
	    }
	 }
      }
   } while (better && !unbounded);

   if (!unbounded) {
      // linear program is bounded, look for the entire optimal face
      std::list<int> optimal_vertices(optimal_face.begin(), optimal_face.end());

      while (!optimal_vertices.empty()) {
	 current_vertex = optimal_vertices.front();
	 optimal_vertices.pop_front();

	 for (Entire<graph::out_edge_list>::iterator v=entire(G.out_edges(current_vertex));  !v.at_end();  ++v) {
	    const int neighbor=v.to_node();
	    if (!G.node(neighbor)) {
	       G.node(neighbor)=true;
	       if (V(neighbor,0) && objective * V[neighbor] == opt) {
		  optimal_face += neighbor;
		  optimal_vertices.push_back(neighbor);
	       }
	    }
	 }
      }

      p.take(maximize ? "MAXIMAL_VALUE" : "MINIMAL_VALUE") << opt;

   } else {
      // linear program is unbounded
      // nonetheless: the optimal face is the subset of the far face
      optimal_face.clear();
      for (Entire< Set<int> >::const_iterator v=entire(far_face); !v.at_end(); ++v) {
	 if (sign(objective * V[*v]) == sense)
	    optimal_face.push_back(*v);
      }

      p.take(maximize ? "MAXIMAL_VALUE" : "MINIMAL_VALUE") << Poly::undefined();
   }

   p.take(maximize ? "MAXIMAL_FACE" : "MINIMAL_FACE") << optimal_face;
}

} }

using namespace polymake;

/** @file pseudo-simplex
 *
 *  Find an optimum of a linear objective function.
 *  The method generalizes the behavior of the simplex algorithm,
 *  but it relies on complete information about the solution polytope.
 *
 *  @b WARNING: this is not an efficient way to solve a linear program.
 *
 *  @synopsis pseudo-simplex <file> { -maximize | -minimize }
 *
 *  @reading  VERTICES, GRAPH, LINEAR_OBJECTIVE, FAR_FACE
 *  @writing  MAXIMAL_VALUE, MAXIMAL_FACE or MINIMAL_VALUE, MINIMAL_FACE
 */

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