// ---------------------------------------------------------------------------
// - Linear.cpp                                                              -
// - afnix:mth module - generalize linear solver class implementation        -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - 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.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2013 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Vector.hpp"
#include "Linear.hpp"
#include "Krylov.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
 
namespace afnix {

  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------
  
  // the default preconditionning flag
  static const bool LNR_PCF_DEF = true;
  // the default automatic verification flag
  static const bool LNR_AVF_DEF = false;
  // the default maximum number of iterations
  static const long LNR_MNI_DEF = 0;
  // the iteration factor for the linear solver
  static const long SLV_NI_DEF = 5L;

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default linear solver

  Linear::Linear (void) {
    d_pcf = LNR_PCF_DEF;
    d_avf = LNR_AVF_DEF;
    d_mni = LNR_MNI_DEF;
  }
  
  // create a solver by verification flag

  Linear::Linear (const bool avf) {
    d_pcf = LNR_PCF_DEF;
    d_avf = avf;
    d_mni = LNR_MNI_DEF;
  }

  // copy construct this object

  Linear::Linear (const Linear& that) {
    that.rdlock ();
    try {
      d_pcf = that.d_pcf;
      d_avf = that.d_avf;
      d_mni = that.d_mni;
      that.unlock ();
    } catch (...) {
      that.unlock ();
      throw;
    }
  }

  // return the class name
  
  String Linear::repr (void) const {
    return "Linear";
  }
  
  // return a clone of this object
  
  Object* Linear::clone (void) const {
    return new Linear (*this);
  }

  // assign an object to this one

  Linear& Linear::operator = (const Linear& that) {
    // check for self assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.rdlock ();
    try {
      d_pcf = that.d_pcf;
      d_avf = that.d_avf;
      d_mni = that.d_mni;
      unlock ();
      that.unlock ();
      return *this;
    } catch (...) {
      unlock ();
      that.unlock ();
      throw;
    }
  }

  // get a jacobi vector preconditionner by lhs and rhs

  Rvi* Linear::getjp (const Rmi& lhs, const Rvi& rhs) const {
    rdlock ();
    Rvi* pv = nilp;
    try {
      // get the matrix size and vector size
      long size = rhs.getsize ();
      if ((lhs.getrsiz () != size) || (lhs.getcsiz () != size)) {
	throw Exception ("linear-error", "inconsistent lhs/rhs size");
      }
      // clone the calling vector
      pv = dynamic_cast <Rvi*> (rhs.clone ());
      if (pv == nilp) {
	throw Exception ("linear-error", "cannot clone rhs vector");
      }
      // loop in the matrix diagonal
      for (long k = 0; k < size; k++) {
	t_real val = lhs.get (k,k);
	if (val == 0.0) val = 1.0;
	pv->set (k, 1.0 / val);
      }
      unlock ();
      return pv;
    } catch (...) {
      delete pv;
      unlock ();
      throw;
    }
  }

  // solve a system with several iterable solvers
  
  Rvi* Linear::solve (const Rmi& lhs, const Rvi& rhs) const {
    rdlock ();
    Rvi* lxv = nilp;
    Rvi* rmp = nilp;
    try {
      // get the number of iteration
      long ni = (d_mni <= 0) ? rhs.getsize () * SLV_NI_DEF : d_mni;
      // eventually get a jacobi preconditionner
      if (d_pcf == true) rmp = getjp (lhs, rhs);
      // clone the calling vector
      lxv = dynamic_cast <Rvi*> (rhs.clone ());
      if (lxv == nilp) {
	delete rmp;
	throw Exception ("linear-error", "cannot clone rhs vector");
      }
      // try with the krylov cgs solver
      bool status = false;
      if (d_pcf == true) {
	status = Krylov::cgs (*lxv, lhs, *rmp, rhs, ni);
      } else {
	status = Krylov::cgs (*lxv, lhs, rhs, ni);
      }
      status = status && (!d_avf || (d_avf && verify (lhs, rhs, *lxv)));
      if (status == true) {
	delete rmp;
	unlock ();
	return lxv;
      }
      // try with the krylov bcs solver
      if (d_pcf == true) {
	status = Krylov::bcs (*lxv, lhs, *rmp, rhs, ni);
      } else {
	status = Krylov::bcs (*lxv, lhs, rhs, ni);
      }
      status = status && (!d_avf || (d_avf && verify (lhs, rhs, *lxv)));
      if (status == true) {
	delete rmp;
	unlock ();
	return lxv;
      }
      // clean the preconditionner
      delete rmp;
      // solver failure
      delete lxv;
      return nilp;
    } catch (...) {
      delete rmp;
      delete lxv;
      unlock ();
      throw;
    }
  }

  // verify a system with the original solution
  
  bool Linear::verify (const Rmi& lhs, const Rvi& rhs, const Rvi& x) const {
    rdlock ();
    Rvi* rbv = nilp;
    try {
      // clone the right handside
      rbv = dynamic_cast <Rvi*> (rhs.clone ());
      // compute the new solution
      lhs.mul (*rbv, x, 1.0);
      // compare the solution
      bool result = rbv->cmp (rhs);
      // clean and return
      delete rbv;
      return result;
    } catch (...) {
      delete rbv;
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 2;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_GETJP = zone.intern ("get-jacobi-preconditionner");
  static const long QUARK_SOLVE = zone.intern ("solve");

  // create a new object in a generic way
  
  Object* Linear::mknew (Vector* argv) {
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // check for 0 argument
    if (argc == 0) return new Linear;    
    // check for 1 argument
    if (argc == 1) {
      bool avf = argv->getbool (0);
      return new Linear (avf);
    }
    // invalid arguments
    throw Exception ("argument-error", "invalid arguments with linear object");
  }

  // return true if the given quark is defined

  bool Linear::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true){
      unlock ();
      return true;
    }
    bool result = hflg ? Object::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }
  
  // apply this object with a set of arguments and a quark
  
  Object* Linear::apply (Runnable* robj, Nameset* nset, const long quark,
			 Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // dispatch 2 arguments
    if (argc == 2) {
      if (quark == QUARK_GETJP) {
	// get the lhs
	Object* obj = argv->get (0);
	Rmi* lhs = dynamic_cast <Rmi*> (obj);
	if (lhs == nilp) {
	  throw Exception ("type-error", 
			   "invalid object with get-jacobi-preconditionner",
			   Object::repr (obj));
	}
	// get the rhs
	obj = argv->get (1);
	Rvi* rhs = dynamic_cast <Rvi*> (obj);
	if (rhs == nilp) {
	  throw Exception ("type-error",
			   "invalid object with get-jacobi-preconditionner",
			   Object::repr (obj));
	}
	// get the preconditionner
	return getjp (*lhs, *rhs);
      }
      if (quark == QUARK_SOLVE) {
	// get the lhs
	Object* obj = argv->get (0);
	Rmi* lhs = dynamic_cast <Rmi*> (obj);
	if (lhs == nilp) {
	  throw Exception ("type-error", "invalid object with solve",
			   Object::repr (obj));
	}
	// get the rhs
	obj = argv->get (1);
	Rvi* rhs = dynamic_cast <Rvi*> (obj);
	if (rhs == nilp) {
	  throw Exception ("type-error", "invalid object with solve",
			   Object::repr (obj));
	}
	// try to solve the system
	return solve (*lhs, *rhs);
      }
    }
    // call the object
    return Object::apply (robj, nset, quark, argv);
  }
}
