/* 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: rigidity_matrix.cc,v 1.1 2005/11/10 10:29:12 thilosch Exp $"

#include <Poly.h>
#include <Vector.h>
#include <Matrix.h>
#include <SparseMatrix.h>
#include <SparseVector.h>
#include <Rational.h>
#include <Graph.h>
#include <linalg.h>

namespace polymake { namespace polytope {
  namespace {
     typedef Graph< Vector< Rational > > Framework;
  }
   
  void rigidity_matrix(Poly& p) {
     Framework F = p.give("FRAMEWORK");
     const int dim = F.node(0).size();

     SparseMatrix< Rational > R(edges(F).size(), F.nodes()*dim);
     Entire< Rows< SparseMatrix< Rational > > >::iterator ri = entire(rows(R));
     
     for(Entire< Edges< Framework > >::const_iterator ei = entire(edges(F)); !ei.at_end(); ++ei, ++ri) {
	const int from_node = ei.from_node();
	const int to_node = ei.to_node();
	const Vector<Rational> diff = ( F.node(from_node)-F.node(to_node) );
	(*ri).slice(from_node*dim,dim) = diff;
	(*ri).slice(to_node*dim,dim) = -diff;
     }

     if(F.nodes() >= dim) {
	p.take("INFINITESIMALLY_RIGID") << (rank(R) == dim*F.nodes() - ((dim+1)*dim)/2);
     }

     p.take("DIM") << dim;
     p.take("RIGIDITY_MATRIX") << R;
  }
} }

using namespace polymake;

/** @file rigidity_matrix
 *
 *  Compute the the rigidity matrix of a bar and joint framework
 *
 *  @synopsis rigidity_matrix <file>
 *
 *  @reading  FRAMEWORK
 *  @writing  INFINITESIMALLY_RIGID, RIGIDITY_MATRIX, DIM
 */

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);
    polytope::rigidity_matrix(p);
  }
  catch (const std::exception& e) {
    cerr << e.what() << endl;
    return 1;
  }
  return 0;
}
