/*

	BigMatrix.h
	===========

	This file defines the two classes 'BigVector' and 'BigMatrix' that allow
	manipulations of large vectors and sparse quadratic matrices.
	For the matrix class the non-zero matrix elements will be stored in the
	form of linked lists (one list per column of the matrix).
	The dynamic storage of the matrix elements allows the user to
	modified the matrix at any point throughout the program.
	Both classes define the usual operations for vectors and matrices.
	The method of reference counting is used to prevent unnecessary copying.
	The member functions perform checks for illegal operations
	(e.g. index out of bound) and throw exceptions.
	Routines for calculating inverse matrices, determinants and eigenvalues
	are also provided.

*/


#ifndef BigMatrixH
#define BigMatrixH

#include <iostream.h>
#include <math.h>

typedef double BigFloat;            // type for matrix elements
typedef int    BigInt;              // type for matrix indices


// classes for exception handling in 'BigMatrix' and 'BigVector'
// these classes are thrown by the member functions in case of errors
class BigMatrixError {};            // error base class
class BigMatrixOutOfBounds
	: public BigMatrixError {};     // index outside allowed range
class BigMatrixIncompatible
	: public BigMatrixError {};     // objects have different size
class BigMatrixZeroSize
	: public BigMatrixError {};     // object has zero length
class BigMatrixOutOfMemory
	: public BigMatrixError {};     // 'new' failed to allocate memory
class BigMatrixReadError
	: public BigMatrixError {};     // error while reading matrix from stream


/*

	BigVector class:

	The vector elements of type 'BigFloat' are stored in a dynamically
	alloceted array of size 'length' and pointed to by 'data'.
	Vector elements can be accessed by the index operator '(i)' with
	indices ranging from 1 to 'length'.

	Reference counting:
	The copy constructor and assignment operator do not copy the entire vector.
	Instead they create a new reference to the same vector array 'data[]' and
	increase the reference count '*nref'.  Every member function that changes
	a vector calls the function 'clone()' which creates a real copy of the
	vector array in the case that another reference is pointing at the same
	data.

*/

class BigVector
{
	// data members
	BigFloat*     data;             // pointer to vector array
	BigInt        length;           // length of vector
	unsigned int* nref;             // pointer to reference count

	// private member functions
	void setall(BigFloat);          // set all array elements to one value
	void create(BigInt);            // allocate vector array and reference count
	void destroy();                 // decrease reference count and
	                                //   delete vector array if necessary
	void clone();                   // make complete copy of the array if its
	                                //   reference count is larger than one

public:
	BigVector(BigInt n=0, BigFloat x=0.0)     // construct vector of length n
		{ create(n); setall(x); }             //   and fill with value x
	BigVector(const BigVector & v)            // copies only a reference
		: data(v.data), length(v.length), nref(v.nref) { (*nref)++; }
	~BigVector()
		{ destroy(); }

	const BigVector& operator=(const BigVector &);  // copies only a reference
	const BigVector& operator=(BigFloat);
	      BigFloat&  operator()(BigInt);
	const BigFloat&  operator()(BigInt) const;

	// the usual arithmetic operations
	const BigVector  operator+ (const BigVector &) const;
	const BigVector  operator- (const BigVector &) const;
	      BigVector& operator+=(const BigVector &);
	      BigVector& operator-=(const BigVector &);
	const BigVector  operator+ () const  { return *this; }
	const BigVector  operator- () const;
	const BigVector  operator+ (BigFloat) const;
	const BigVector  operator- (BigFloat x) const  { return (*this)+(-x); }
	      BigVector& operator+=(BigFloat);
	      BigVector& operator-=(BigFloat x)  { return (*this)+=(-x); }
	      BigFloat   operator* (const BigVector &) const;
	const BigVector  operator* (BigFloat) const;
	const BigVector  operator/ (BigFloat x) const  { return (*this)*(1/x); }
	      BigVector& operator*=(BigFloat);
	      BigVector& operator/=(BigFloat x)  { return (*this)*=(1/x); }

	// compare two vectors
	int operator==(const BigVector &) const;
	int operator!=(const BigVector & v) const { return !(*this == v); }

	BigInt size() const { return length; }   // return length of vector
	void resize(BigInt);                     // resize and initialize vector

	void sort_ascending();                   // sort elements in ascending order
	void sort_descending();                  // sort elements in descending order
};


// some more arithmetic functions which cannot be defined as member functions

inline
const BigVector operator+(BigFloat x, const BigVector & v)
{
	return v+x;
}

inline
const BigVector operator-(BigFloat x, const BigVector & v)
{
	BigVector v2 = -v;
	v2 += x;
	return v2;
}

inline
const BigVector operator*(BigFloat x, const BigVector & v)
{
	return v*x;
}

inline
BigFloat abs(const BigVector & v)
{
	return sqrt(v*v);
}



/*
	BigMatrix class:

	The matrix elements of type 'BigFloat' are stored in dynamically
	alloceted objects of type 'element'.  For each column the non-zero
	matrix elements are connected as a sorted unidirectional linked list
	with ascending row indices.
	For each column an object of type 'column' is created which contains
	pointers to the first and last element of the linked list containing
	the matrix elements of that column.  The 'column' objects of the
	matrix are stored in an array of size 'length' and pointed to by 'col'.
	Matrix elements can be accessed by the index operator '(i,j)' with
	indices ranging from 1 to 'length'.

	Reference counting:
	See BigVector class for a description.
*/

class BigMatrix
{
protected:
	// An object of this class represents one non-zero matrix element.
	// The elements of one column of the matrix are stored in
	//   one linked list of 'element' objects.
	class element
	{
	public:
		BigInt   row;            // row index of matrix element (1..n)
		BigFloat value;          // value of matrix element
		element* next;           // pointer to next non-zero element in column
		element(BigInt n = 0, BigFloat x = 0, element* p = 0)
			: row(n), value(x), next(p) { }
	};

	// An object of this class represents one column of the matrix.
	// 'first' and 'last' are pointers to the first and last non-zero
	//   matrix elements while 'nfirst' and 'nlast' are their row indices.
	class column
	{
	public:
		BigInt   nfirst;         // row of first element (1..n)
		BigInt   nlast;          // row of last element (1..n)
		element* first;          // pointer to first non-zero element in column
		element* last;           // pointer to last non-zero element in column
		column() : nfirst(0), nlast(0), first(0), last(0) { }
	};

public:
	// An object of this class is returned by the index operator '(i,j)'.
	// Since matrix elements that are zero do not exist in memory,
	// the index operator cannot return a reference to them.
	// Instead it returns an 'element_ptr' which is simply converted
	// to a 'BigFloat' when used as r-value and which changes or
	// creates the matrix element when used as l-value.
	class element_ptr
	{
		column*  col;           // pointer to header of current column
		BigInt   row;           // row index of current matrix element
		element* current;       // pointer to current matrix element
		                        //   0 in case element does not exist
		element* previous;      // pointer to previous matrix element
		                        //   0 in case 'current' is the first one
	public:
		element_ptr(column* c=0, BigInt r=0, element* cu=0, element* p=0)
			: col(c),row(r),current(cu),previous(p) { }
		element_ptr(element_ptr& ep)
			: col(ep.col),row(ep.row),current(ep.current),
			previous(ep.previous) { }
		operator BigFloat() const { return current ? current->value : 0.0; }
		BigFloat    operator= (BigFloat x) { set(*this,x); return *this; }
		element_ptr operator+=(BigFloat x) { set(*this,*this+x); return *this; }
		element_ptr operator-=(BigFloat x) { set(*this,*this-x); return *this; }
		element_ptr operator*=(BigFloat x) { set(*this,*this*x); return *this; }
		element_ptr operator/=(BigFloat x) { set(*this,*this/x); return *this; }
		friend class BigMatrix;
	};
	friend class element_ptr;

	// 'find' searches for a certain matrix element and returns a reference
	// to it.  If the element does not exist, 'find' returns information
	// that it sufficient to create the element later, if required.
	// 'set' uses the information returned by 'find' to change, create or
	// delete the matrix element in question.
	static element_ptr find(column*, BigInt);
	static void set(element_ptr&, BigFloat);

	// This class is used to scan through the matrix column by column
	// considering only the non-zero elements.
	class scan_ptr
	{
		const BigMatrix* matrix;         // pointer to matrix header
		BigInt col;                      // column index of current element
		element* current;                // pointer to current object
	public:
		void set(BigFloat x)             // change value of current element
			{ if(current) current->value = x; }
		scan_ptr(const BigMatrix& m)     // create new scan_ptr pointing
			: matrix(&m), col(0)         //   at first non-zero element
			, current(0) { advance(); }  //   of the matrix
		BigInt advance();                // go to next non-zero element
		BigInt gotocol(BigInt col);      // go to first element of column 'col'
		BigFloat get() const             // return value of current element
			{ return current ? current->value : 0.0; }
		BigInt column() const            // return column index
			{ return col; }
		BigInt row() const               // return row index
			{return current ? current->row : 0; }
		bool valid() const               // false if end of matrix is reached
			{ return current ? true : false; }
		friend class BigMatrix;
	};
	friend class scan_ptr;

protected:

	column*       col;                   // pointer to 'column' array
	BigInt        length;                // size of matrix
	unsigned int* nref;                  // number of references to matrix

protected:

	virtual BigInt create(BigInt);       // allocate matrix and 'cref' object
	virtual void destroy();              // delete matrix and 'cref' object
	virtual void clone();                // create real copy of matrix if it
	                                     //   has more than one reference

public:
	BigMatrix(BigInt n=0) { create(n); } // create matrix of zeros
	BigMatrix(BigInt, BigFloat);         // create diagonal matrix from number
	BigMatrix(const BigVector &);        // create diagonal matrix from vector
	BigMatrix(const BigMatrix & m)       // copy constructor only copies
		: col(m.col), length(m.length)   //   a reference
		, nref(m.nref) { (*nref)++; }
	virtual ~BigMatrix() { destroy(); }

	virtual const BigMatrix&  operator= (const BigMatrix &);
	virtual const BigMatrix&  operator= (const BigVector &);
	virtual const BigMatrix&  operator= (BigFloat);
	virtual       element_ptr operator()(BigInt,BigInt);
	virtual       element_ptr operator()(BigInt i) { return (*this)(i,i); }
	virtual const BigFloat    operator()(BigInt,BigInt) const;
	virtual const BigFloat    operator()(BigInt i) const { return (*this)(i,i); }

	// the usual arithmetic operations
	virtual const BigMatrix  operator+ (const BigMatrix &) const;
	virtual const BigMatrix  operator- (const BigMatrix &) const;
	virtual       BigMatrix& operator+=(const BigMatrix &);
	virtual       BigMatrix& operator-=(const BigMatrix &);
	virtual const BigMatrix  operator+ () const  { return *this; }
	virtual const BigMatrix  operator- () const;
	virtual const BigMatrix  operator+ (const BigVector &) const;
	virtual const BigMatrix  operator- (const BigVector &) const;
	virtual       BigMatrix& operator+=(const BigVector &);
	virtual       BigMatrix& operator-=(const BigVector &);
	virtual const BigMatrix  operator+ (BigFloat) const;
	virtual const BigMatrix  operator- (BigFloat x) const  { return (*this)+(-x); }
	virtual       BigMatrix& operator+=(BigFloat);
	virtual       BigMatrix& operator-=(BigFloat x)  { return (*this)+=(-x); }
	virtual       BigMatrix  operator* (const BigMatrix &) const;
	virtual       BigVector  operator* (const BigVector &) const;
	virtual       BigMatrix  operator* (BigFloat) const;
	virtual const BigMatrix  operator/ (BigFloat x) const { return (*this)*(1/x); }
	virtual       BigMatrix& operator*=(const BigMatrix &);
	virtual       BigMatrix& operator*=(BigFloat);
	virtual       BigMatrix& operator/=(BigFloat x)  { return (*this)*=(1/x); }

	// compare two matrices
	virtual int operator==(const BigMatrix &) const;
	virtual int operator!=(const BigMatrix & m) const { return !(*this == m); }

	virtual BigInt size() const           // return size of matrix
		{ return length; }
	virtual void resize(BigInt);          // resize and initialize matrix
	virtual void delete_column(BigInt);   // sets all elements of one column to zero
	virtual void delete_lower_triangle(); // deletes all elements in lower triangle

	// 'write_matrix' writes all non-zero matrix elements to ostream
	// 'read_matrix' reads matrix elements from istream; only the elements
	//    read from istream are changed, the others are not set to zero
	// the format is: "row-index  column-index  value" e.g. "1  2  3.45"
	virtual void     write_matrix(ostream &);
	virtual long int read_matrix (istream &, long int);
	virtual long int read_matrix (istream & in) { return read_matrix(in, -1); }

	virtual char* type() { return "General Matrix"; }
};


// some more arithmetic functions which cannot be defined as member functions

inline
const BigMatrix operator+(BigVector & v, const BigMatrix & m)
{
	return m+v;
}


inline
const BigMatrix operator-(BigVector & v, const BigMatrix & m)
{
	BigMatrix m2(v);
	m2 -= m;
	return m2;
}


inline
const BigMatrix operator+(BigFloat x, const BigMatrix & m)
{
	return m+x;
}


inline
const BigMatrix operator-(BigFloat x, const BigMatrix & m)
{
	BigMatrix m2 = -m;
	m2 += x;
	return m2;
}


inline
const BigMatrix operator*(BigFloat x, const BigMatrix & m)
{
	return m*x;
}


BigMatrix transpose(BigMatrix &);



// ==================
// SymmetricBigMatrix
// ==================

class SymmetricBigMatrix : public BigMatrix
{
protected:
	virtual void clone();
public:
	SymmetricBigMatrix(BigInt n=0) : BigMatrix(n) { }
	SymmetricBigMatrix(BigInt n, BigFloat x) : BigMatrix(n,x) { }
	SymmetricBigMatrix(const BigVector & v) : BigMatrix(v) { }
	SymmetricBigMatrix(const SymmetricBigMatrix & m)
		{ col = m.col; length = m.length; nref = m.nref; (*nref)++; }
	SymmetricBigMatrix(const BigMatrix & m)
		{ *((BigMatrix*)this) = m; delete_lower_triangle(); }

	virtual const SymmetricBigMatrix&  operator= (const SymmetricBigMatrix &);

	virtual       element_ptr operator()(BigInt i, BigInt j);
	virtual const BigFloat    operator()(BigInt i, BigInt j) const;
	virtual       element_ptr operator()(BigInt i) { return (*this)(i,i); }
	virtual const BigFloat    operator()(BigInt i) const { return (*this)(i,i); }

	virtual char* type() { return "Symmetric Matrix"; }
};



#endif
