// ---------------------------------------------------------------------------
// - Rvi.cpp                                                                 -
// - afnix:mth module - real vector interface 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 "Rvi.hpp"
#include "Math.hpp"
#include "Real.hpp"
#include "Mthsid.hxx"
#include "Vector.hpp"
#include "Boolean.hpp"
#include "Integer.hpp"
#include "Utility.hpp"
#include "Algebra.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "OutputStream.hpp"
 
namespace afnix {

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

  // create a default vector

  Rvi::Rvi (void) {
    d_size = 0;
  }

  // create a vector by size

  Rvi::Rvi (const t_long size) {
    // check the size
    if (size < 0) {
      throw Exception ("size-error", "invalid real vector size");
    }
    d_size = size;
  }

  // return the anonymous rvi serial code

  t_byte Rvi::serialid (void) const {
    return SERIAL_ARVI_ID;
  }

  // serialize this object
  
  void Rvi::wrstream (OutputStream& os) const {
    rdlock ();
    try {
      // write the vector size
      mth_wrlong (d_size, os);
      // write the vector data
      for (long k = 0; k < d_size; k++) {
	// get the vector value
	t_real val = get (k);
	if (val == 0.0) continue;
	// write by position
	mth_wrlong (k,   os);
	mth_wrreal (val, os);
      }
      // write marker for end
      mth_wrlong (-1, os);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // deserialize this object

  void Rvi::rdstream (InputStream& is) {
    wrlock ();
    try {
      // get the vector size
      long size = mth_rdlong (is);
      // resize the vector
      resize (size);
      // get the vector data by position
      for (long k = 0; k < size; k++) {
	long idx = mth_rdlong (is);
	// check for marker
	if (idx == -1) {
	  unlock ();
	  return;
	}
	t_real val = mth_rdreal (is);
	set (idx, val);
      }
      // get the remaining marker
      if (mth_rdlong (is) != -1) {
	throw Exception ("rvi-error", "inconsistent serialized vector");
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // compare two vectors

  bool Rvi::operator == (const Rvi& x) const {
    rdlock ();
    x.rdlock ();
    try {
      // check size first
      if (d_size != x.d_size) {
	throw Exception ("vector-error",
			 "incompatible vector size with compare");
      }
      // initialize result
      bool result = true;
      // loop in vector
      for (t_long i = 0; i < d_size; i++) {
	if (get (i) != x.get (i)) {
	  result = false;
	  break;
	}
      }
      // unlock and return
      unlock ();
      x.unlock ();
      return result;
    } catch (...) {
      unlock ();
      x.unlock ();
      throw;
    }
  }

  // compare two vectors

  bool Rvi::operator != (const Rvi& x) const {
    return !(*this == x);
  }

  // add this vector by a scalar

  Rvi& Rvi::operator += (const t_real s) {
    return this->add (*this, s);
  }

  // add this vector with a vector

  Rvi& Rvi::operator += (const Rvi& x) {
    return this->aeq (x);
  }

  // substract this vector by a scalar

  Rvi& Rvi::operator -= (const t_real s) {
    return this->sub (*this, s);
  }

  // multiply this vector by a scalar

  Rvi& Rvi::operator *= (const t_real s) {
    return this->mul (*this, s);
  }
  
  // compute the vector dot product

  t_real Rvi::operator ^ (const Rvi& x) const {
    rdlock ();
    x.rdlock ();
    try {
      // check size compatibility
      if (d_size != x.d_size) {
	throw Exception ("vector-error", 
			 "incompatible vector size with dot product");
      }
      // dot product loop with kahan algorithm
      t_real        sum = 0.0;
      volatile t_real c = 0.0;
      for (t_long i = 0; i < d_size; i++) {
	volatile t_real y = get (i) * x.get (i) - c;
	volatile t_real t = sum + y;
	c = (t - sum) - y;
	sum = t;
      }
      // unlock and return
      unlock ();
      x.unlock ();
      return sum;
    } catch (...) {
      unlock ();
      x.unlock ();
      throw;
    }
  }

  // return the vector size

  t_long Rvi::getsize (void) const {
    rdlock ();
    try {
      t_long result = d_size;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // clear this vector

  void Rvi::clear (void) {
    wrlock ();
    try {
      for (t_long i = 0; i < d_size; i++) set (i, 0.0);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a vector by value

  void Rvi::set (const t_real val) {
    wrlock ();
    try {
      for (t_long i = 0; i < d_size; i++) set (i, val);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // compare two vectors by precision

  bool Rvi::cmp (const Rvi& x) const {
    rdlock ();
    x.rdlock ();
    try {
      // check size first
      if (d_size != x.d_size) {
	throw Exception ("vector-error",
			 "incompatible vector size with compare");
      }
      // initialize result
      bool result = true;
      // loop in vector
      for (t_long i = 0; i < d_size; i++) {
	t_real ti = get (i);
	t_real xi = x.get (i);
	if (Math::acmp (ti, xi) == false) {
	  result = false;
	  break;
	}
      }
      // unlock and return
      unlock ();
      x.unlock ();
      return result;
    } catch (...) {
      unlock ();
      x.unlock ();
      throw;
    }
  }

  // compute the vector norm

  t_real Rvi::norm (void) const {
    rdlock ();
    try {
      // compute vector norm with kahan algorithm
      t_real        sum = 0.0;
      volatile t_real c = 0.0;
      for (t_long i = 0; i < d_size; i++) {
	volatile t_real xi = get (i);
	volatile t_real  y = (xi * xi) - c;
	volatile t_real  t = sum + y;
	c = (t - sum) - y;
	sum = t;
      }
      t_real result = Math::sqrt (sum);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // copy a vector into this one

  Rvi& Rvi::cpy (const Rvi& x) {
    wrlock ();
    try {
      Algebra::cpy (*this, x);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a vector with a scalar

  Rvi& Rvi::add (const Rvi& x, const t_real s) {
    wrlock ();
    try {
      Algebra::add (*this, x, s);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a vector with another one

  Rvi& Rvi::add (const Rvi& x, const Rvi& y) {
    wrlock ();
    try {
      Algebra::add (*this, x, y);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a vector with another scaled one

  Rvi& Rvi::add (const Rvi& x, const Rvi& y, const t_real s) {
    wrlock ();
    try {
      Algebra::add (*this, x, y, s);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // substract a vector with a scalar

  Rvi& Rvi::sub (const Rvi& x, const t_real s) {
    wrlock ();
    try {
      Algebra::sub (*this, x, s);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // substract a vector with another one

  Rvi& Rvi::sub (const Rvi& x, const Rvi& y) {
    wrlock ();
    try {
      Algebra::sub (*this, x, y);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // multiply a vector with a scaled factor

  Rvi& Rvi::mul (const Rvi& x, const t_real s) {
    wrlock ();
    try {
      Algebra::mul (*this, x, s);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // multiply a vector with another one

  Rvi& Rvi::mul (const Rvi& x, const Rvi& y) {
    wrlock ();
    try {
      Algebra::mul (*this, x, y);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add equal with a vector

  Rvi& Rvi::aeq (const Rvi& x) {
    wrlock ();
    try {
      Algebra::aeq (*this, x);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add equal with a scaled vector

  Rvi& Rvi::aeq (const Rvi& x, const t_real s) {
    wrlock ();
    try {
      Algebra::aeq (*this, x, s);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // rescale equal with a vector

  Rvi& Rvi::req (const Rvi& x, const t_real s) {
    wrlock ();
    try {
      Algebra::req (*this, x, s);
      unlock ();
      return *this;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // dump the vector to an output stream

  void Rvi::dump (OutputStream& os) const {
    rdlock ();
    try {
      for (long k = 0; k < d_size; k++) {
	os << Utility::tostring (get (k), true);
	if (k < (d_size - 1)) os << ',';
	os << eolc;
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

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

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

  // the rvi supported quarks
  static const long QUARK_DOT     = zone.intern ("dot");
  static const long QUARK_QEQ     = zone.intern ("?=");
  static const long QUARK_AEQ     = zone.intern ("+=");
  static const long QUARK_SEQ     = zone.intern ("-=");
  static const long QUARK_MEQ     = zone.intern ("*=");
  static const long QUARK_DEQ     = zone.intern ("/=");
  static const long QUARK_SET     = zone.intern ("set");
  static const long QUARK_GET     = zone.intern ("get");
  static const long QUARK_DUMP    = zone.intern ("dump");
  static const long QUARK_NORM    = zone.intern ("norm");
  static const long QUARK_CLEAR   = zone.intern ("clear");
  static const long QUARK_GETSIZE = zone.intern ("get-size");

  // return true if the given quark is defined

  bool Rvi::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* Rvi::apply (Runnable* robj, Nameset* nset, const long quark,
                      Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();

    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_NORM)    return new Real (norm ());
      if (quark == QUARK_GETSIZE) return new Integer (getsize ());
      if (quark == QUARK_CLEAR) {
	clear ();
	return nilp;
      }
      if (quark == QUARK_DUMP) {
        OutputStream* os = robj->getos ();
        dump (*os);
        return nilp;
      }
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_GET) {
        t_long pos = argv->getlong (0);
        return new Real (get (pos));
      }
      if (quark == QUARK_DOT) {
	Object* obj = argv->get (0);
	Rvi*    rvo = dynamic_cast <Rvi*> (obj);
	if (rvo == nilp) {
	  throw Exception ("type-error", "invalid object for dot product",
			   Object::repr (obj));
	}
	return new Real (*this ^ *rvo);
      }
      if (quark == QUARK_QEQ) {
	Object* obj = argv->get (0);
	Rvi*    rvo = dynamic_cast <Rvi*> (obj);
	if (rvo == nilp) {
	  throw Exception ("type-error", "invalid object for compare",
			   Object::repr (obj));
	}
	return new Boolean (cmp (*rvo));
      }
      if (quark == QUARK_AEQ) {
	wrlock ();
	try {
	  Object* obj = argv->get (0);
	  // check for an integer
	  Integer* iobj = dynamic_cast <Integer*> (obj);
	  if (iobj != nilp) {
	    t_real rval = iobj->tolong ();
	    *this += rval;
	    robj->post (this);
	    unlock ();
	    return this;
	  }
	  // check for a real
	  Real* dobj = dynamic_cast <Real*> (obj);
	  if (dobj != nilp) {
	    t_real rval = dobj->toreal ();
	    *this += rval;
	    robj->post (this);
	    unlock ();
	    return this;
	  }
	  // check for a vector
	  Rvi* vobj = dynamic_cast <Rvi*> (obj);
	  if (vobj != nilp) {
	    *this += (*vobj);
	    robj->post (this);
	    unlock ();
	    return this;
	  }
	  throw Exception ("type-error", "invalid object for vector aeq",
			   Object::repr (obj));
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_SEQ) {
	wrlock ();
	try {
	  t_real val = argv->getreal (0);
	  *this -= val;
	  robj->post (this);
	  unlock ();
	  return this;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_MEQ) {
	wrlock ();
	try {
	  t_real val = argv->getreal (0);
	  *this *= val;
	  robj->post (this);
	  unlock ();
	  return this;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_DEQ) {
	wrlock ();
	try {
	  t_real val = argv->getreal (0);
	  *this *= (1.0 / val);
	  robj->post (this);
	  unlock ();
	  return this;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_DUMP) {
        Object*      obj = argv->get (0);
        OutputStream* os = dynamic_cast <OutputStream*> (obj);
	if (os == nilp) {
	  throw Exception ("type-error", "invalid object with format",
			   Object::repr (obj));
	}
	dump (*os);
	return nilp;
      }
    }
    // dispatch 2 arguments
    if (argc == 2) {
      if (quark == QUARK_SET) {
        t_long pos = argv->getlong (0);
        t_real val = argv->getreal (1);
	set (pos, val);
        return nilp;
      }
    }
    // call the object
    return Object::apply (robj, nset, quark, argv);
  }
}

