/* 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_vert.cc,v 1.7 2004/06/22 16:23:08 gawrilow Exp $"

#include <cstdlib>
#include <ctime>
#include <Poly.h>
#include <Matrix.h>
#include <Set.h>
#include <RandomSubset.h>
#include <argv_options.h>

namespace {
   enum { seed };
}

namespace polymake { namespace polytope {

void rand_vert(Poly& p_out, Poly& p_in, int n_vertices_out, const argv_option *options)
{
   const Matrix<Rational> V=p_in.give("VERTICES");
   const int n_vertices_in=V.rows();

   if (n_vertices_out > n_vertices_in)
      throw std::runtime_error("number of output vertices too high\n");

   time_t t;
   Set<int> random_vertices=select_random_subset(sequence(0,n_vertices_in), n_vertices_out,
						 options[seed] ? atol(options[seed]) : (time(&t), t));

   p_out.take("VERTICES") << V.minor(random_vertices, All);
}

} }

using namespace polymake;

/** @file rand_vert
 *
 *  Produce a polytope with $n$ random vertices from input polytope.
 *
 *  This can be used to produce random polytopes which are neither simple nor simplicial as follows.
 *  First produce a simple polytope (for instance at random, by using rand_sphere, rand, or unirand).
 *  Then use this client to choose among the vertices at random.  Generalizes random 0/1-polytopes.
 *
 *  A seed value for the random number generator can be specified.
 *
 *  @synopsis rand_vert <output_file> <input_file> <n> [ seed ]
 *
 *  @writing  VERTICES
 *
 *  @index clients Producing a new polyhedron from others
 */

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