/* 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 9804 2010-09-20 18:36:10Z sherrmann $
*/

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

namespace polymake { namespace polytope {

Matrix<double> poly2metric_Euclidean(perl::Object p)
{ 
  const Matrix<double> V=p.give("VERTICES");
  const int n=V.rows();
  Matrix<double> dist(n,n);

  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
  return dist;
}

template <typename Scalar>
Matrix<Scalar> poly2metric_max(perl::Object p)
{
  const Matrix<Scalar> V=p.give("VERTICES");
  const int n=V.rows();
  Matrix<Scalar> dist(n,n);
  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());
  return dist;
}

template <typename Scalar>
Matrix<Scalar> poly2metric_l1(perl::Object p)
{
  const Matrix<Scalar> V=p.give("VERTICES");
  const int n=V.rows();
  Matrix<Scalar> dist(n,n);
  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::add());
  return dist;
}
Function4perl(&poly2metric_Euclidean,"poly2metric_Euclidean(Polytope)");

FunctionTemplate4perl("poly2metric_max<Scalar>(Polytope<Scalar>)");

FunctionTemplate4perl("poly2metric_l1<Scalar>(Polytope<Scalar>)");


InsertEmbeddedRule("# @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// or //l1// is set to true the max-norm or l1-nomr is used instead (with exact computation)."
		  "# @param Polytope P"
		  "# @option Bool max triggers the usage of the max-norm (exact computation)"
                  "# @return Matrix\n"
                  "user_function poly2metric(Polytope { max => 0, l1 => 0 }) { if ($_[1]->{'max'}) { return poly2metric_max($_[0]); } if ($_[1]->{'l1'}) { return poly2metric_l1($_[0]); } poly2metric_Euclidean($_[0]); }\n"); 

} }
