/* Copyright (c) 1997-2009
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
   http://www.polymake.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.
--------------------------------------------------------------------------------
   $Project: polymake $$Id: poly2metric.cc 9513 2010-03-01 21:10:37Z herr $
*/

#include <math.h>
#include <polymake.h>
#include <Vector.h>
#include <Matrix.h>

namespace polymake { namespace polytope {

perl::Object poly2metric(perl::Object p, perl::OptionSet options)
{ 

  const bool max = options["max"];
  const Matrix<double> V=p.give("VERTICES");
  const int n=V.rows();
  Matrix<double> dist(n,n);

  perl::Object t("TightSpan");
 

  if (max) {
    for (int i=0; i<n; ++i)
      for (int j=i; j<n; ++j)
	dist(i,j)=dist(j,i)=accumulate(attach_operation(V.row(i)-V.row(j), operations::abs_value()), operations::max());
    t.set_description() << "Metric of max-norm distances of vertices of " << p.name() << endl;
  }
  else {
    for (int i=0; i<n; ++i)
      for (int j=i; j<n; ++j)
	dist(i,j)=dist(j,i)=sqrt(sqr(V.row(i)-V.row(j))); // Euclidean distance
    t.set_description() << "Metric of Euclidean distances of vertices of " << p.name() << endl;
  }
  t.take("METRIC") << dist;
  return t;
}

UserFunction4perl("# @category Tight Span"
		  "# Define a metric by restricting the Euclidean distance function to the vertex set of a given polytope //P//."
		  "# Due to floating point computations (sqrt is used) the metric defined may not be exact."
		  "# If the option //max// is set to true the max-norm is used instead (with exact computation)."
		  "# @param Polytope P"
		  "# @option Bool max triggers the usage of the max-norm (exact computation)"
                  "# @return TightSpan",
                  &poly2metric, "poly2metric(Polytope { max => 0 })");

} }
