/* 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: rand_aof.cc,v 1.14 2004/07/27 18:07:48 gawrilow Exp $"

#include <cstdlib>
#include <ctime>
#include <vector>
#include <list>
#include <argv_options.h>
#include <random_generators.h>
#include <Poly.h>
#include <Array.h>
#include <IncidenceMatrix.h>
#include <FacetList.h>

namespace {
   enum { seed };
}

namespace polymake { namespace polytope {

void rand_aof(Poly& p_out, Poly& p_in, int start, const argv_option *options)
{
   const bool simple=p_in.give("SIMPLE");
   if (!simple)
      throw std::runtime_error("polytope is not simple");

   const IncidenceMatrix<> Boundary=p_in.give("VERTICES_IN_FACETS");
   const int n=Boundary.cols(); // number of facets of the complex = number of vertices of the polytope
   const int d=Boundary.col(0).size()-1; // dimension of the boundary complex

   time_t t;
   const long s=options[seed] ? atol(options[seed]) : (time(&t), t);
   UniformRNG<long> random(s);

   if (start>=0) {
      if (start>=n)
	 throw std::runtime_error("start vertex out of range");
   } else {
      // take a random start vertex unless specified
      start=random.get() % n;
   }

   // abstract objective function with minimum at start
   typedef std::list<int> vertex_list;
   vertex_list AOF;
   AOF.push_back(start);

   // facets of the complex/vertices of the polytope not considered yet
   Set<int> available(sequence(0,start)+sequence(start+1,n-start-1));

   // union of all the facets shelled so far; i.e. a ball
   Set<int> ball(Boundary.col(start));

   std::vector<int> candidates;
   candidates.reserve(n);
   while (available.size()>1) {
      // determine which of the facets could continue the shelling
      for (Entire< Set<int> >::const_iterator it=entire(available); !it.at_end(); ++it) {
	 const Set<int> intersection_with_previous(Boundary.col(*it) * ball);
	 switch (intersection_with_previous.size()-d) {
	 case 0: // must be contained in a unique facet
	    for (Entire<vertex_list>::const_iterator v=entire(AOF); !v.at_end(); ++v)
	       if (incl(intersection_with_previous, Boundary.col(*v))<=0) { // contained in this facet
		  candidates.push_back(*it);
		  break;
		  }
	    break;
	 case 1: {
	    FacetList intersection_as_a_complex(n);
	    for (Entire<vertex_list>::const_iterator v=entire(AOF); !v.at_end(); ++v)
	       intersection_as_a_complex.replaceMax(Boundary.col(*it) * Boundary.col(*v));
	    if (intersection_as_a_complex.size()>d)
	       break;
	    bool pure=true;
	    for (Entire<FacetList>::const_iterator s=entire(intersection_as_a_complex); !s.at_end(); ++s)
	       if (s->size()!=d) {
		  pure=false;
		  break;
	       }
	    if (pure)
	       candidates.push_back(*it);
	    break;
	 }
	 default:
	    break;
	 }
      }
      if (candidates.empty()) // shelling cannot be extended
	 break;

      // choose one at random
      const int this_one=candidates[random.get() % candidates.size()];
      candidates.clear();
      AOF.push_back(this_one);
      ball += Boundary.col(this_one);
      available -= this_one;
   }

   p_out.take("VERTICES_IN_FACETS") << Boundary;
   if (available.size()!=1) {
      p_out.take("NON_EXTENDIBLE_PARTIAL_SHELLING") << AOF;
   } else {
      AOF.push_back(available.front());
      Array<int> AOF_Array(n);
      int cnt=0;
      for (Entire<vertex_list>::iterator x=entire(AOF); !x.at_end(); ++x)
	 AOF_Array[*x]=cnt++;
      p_out.take("ABSTRACT_OBJECTIVE") << AOF_Array;
   }
}

} }

using namespace polymake;

/** @file rand_aof
 *
 *  Produce a random abstract objective function on a given simple polytope.
 *  It is assumed that the boundary complex of the dual polytope is extendibly shellable.
 *  If, during the computation, it turns out that a certain partial shelling cannot be extended,
 *  then this is given instead of an abstract objective function.
 *
 *  It is possible (but not required) to specify the starting vertex.  Also a seed value for the random
 *  number generator may be given.
 *
 *  @synopsis rand_aof <out_file> <in_file> [ <vertex> ] [ -seed <s> ]
 *
 *  @reading  SIMPLE, VERTICES_IN_FACETS
 *  @writing  VERTICES_IN_FACETS, ABSTRACT_OBJECTIVE or NON_EXTENDIBLE_PARTIAL_SHELLING
 *
 *  @index clients Other
 */

int main(int argc, const char *argv[])
{
   argv_option options[]={ { "-seed", true } };
   if (!extract_options(argc,argv,2,options) || argc<3 || argc>4) {
      cerr << "usage: " << argv[0] << " <out_file> <in_file> [ <vertex ] [ -seed <s> ]" << endl;
      return 1;
   }
   try {
      Poly p_out(argv[1], ios::out | ios::trunc);
      Poly p_in(argv[2], ios::in);
      const int start= argc==4 ? atoi(argv[3]) : -1;
      polytope::rand_aof(p_out, p_in, start, options);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
