// ---------------------------------------------------------------------------
// - 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-2011 amaury darsch                                   -
// ---------------------------------------------------------------------------

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

  // 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_csf = false;
    d_mni = 0;
  }
  
  // create a solver by cramer flag

  Linear::Linear (const bool csf) {
    d_csf = csf;
    d_mni = 0;
  }

  // create a solver by cramer flag and mni value

  Linear::Linear (const bool csf, const long mni) {
    d_csf = csf;
    d_mni = mni;
  }

  // copy construct this object

  Linear::Linear (const Linear& that) {
    that.rdlock ();
    try {
      d_csf = that.d_csf;
      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_csf = that.d_csf;
      d_mni = that.d_mni;
      unlock ();
      that.unlock ();
      return *this;
    } catch (...) {
      unlock ();
      that.unlock ();
      throw;
    }
  }

  // solve a system with several iterable solvers
  
  Rvi* Linear::solve (const Rmi& lhs, const Rvi& rhs) const {
    rdlock ();
    Rvi* lxv = nilp;
    try {
      // get the number of iteration
      long ni = (d_mni <= 0) ? rhs.getsize () * SLV_NI_DEF : d_mni;
      // clone the calling vector
      lxv = dynamic_cast <Rvi*> (rhs.clone ());
      if (lxv == nilp) {
	throw Exception ("linear-error", "cannot clone rhs vector");
      }
      // try with the krylov cgs solver
      if (Krylov::cgs (*lxv, lhs, rhs, ni) == true) {
	unlock ();
	return lxv;
      }
      // try with the krylov bcs solver
      if (Krylov::bcs (*lxv, lhs, rhs, ni) == true) {
	unlock ();
	return lxv;
      }
      // try with the cramer circuit solver if enabled
      if ((d_csf == true) && (Cramer::solve (*lxv, lhs, rhs) == true)) {
	unlock ();
	return lxv;
      }
      // solver failure
      delete lxv;
      return nilp;
    } catch (...) {
      delete lxv;
      unlock ();
      throw;
    }
  }

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

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

  // the rvi supported quarks
  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 csf = argv->getbool (0);
      return new Linear (csf);
    }
    // check for 2 arguments
    if (argc == 2) {
      bool csf = argv->getbool (0);
      long mni = argv->getlong (1);
      return new Linear (csf, mni);
    }
    // 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_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);
  }
}
