/* 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: metric2poly.cc,v 1.4 2006/02/03 16:47:50 joswig Exp $"

#include <Rational.h>
#include <Poly.h>
#include <Vector.h>
#include <Matrix.h>
#include <ListMatrix.h>

namespace polymake { namespace polytope {

void metric2poly(Poly& p) {
   const Matrix<Rational> dist=p.give("METRIC");
   const int d(dist.cols());

   ListMatrix< Vector<Rational> > I = (zero_vector<Rational>(d) | unit_matrix<Rational>(d)); // non-negativity constraints
   for (int i=0; i<d; ++i)
      for (int j=i+1; j<d; ++j) {
	 Vector<Rational> ineq(d+1);
	 ineq[0]=-dist(i,j); ineq[i+1]=ineq[j+1]=1;
	 I /= ineq;
      }

   p.take("INEQUALITIES") << I;
}

} }

using namespace polymake;

/** @file metric2poly
 *
 *  Given a finite metric space (encoded as a symmetric distance matrix), produce an
 *  unbounded polyhedron whose bounded subcomplex is the tight span.
 *
 *  @synopsis metric2poly <file>
 *
 *  @reading  METRIC
 *  @writing  INEQUALITIES
 *
 *  @index clients Tight Spans
 */

int main(int argc, const char *argv[])
{
   if (argc != 2) {
      cerr << "usage: " << argv[0] << " <file>" << endl;
      return 1;
   }

   try {
      Poly p(argv[1], ios::in | ios::out, "TightSpan");
      polytope::metric2poly(p);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
