# AP Library adapted for C++

The document describes an AP library adapted for C++. The AP library for C++ contains a basic set of mathematical functions and collection classes needed to run the programs from the ALGLIB website.

# Compatibility

This library must be compatible with any C++ compiler.

# Structure and Use

The library includes the only module `ap.cpp` (with header file `ap.h`). Just add it to your project.

# AP Library Description

Introduction
Conditional compilation settings
Constants
Functions
Class ap_error
Array classes
Basic subroutines of linear algebra
Class of complex numbers

# Introduction

In the header file `ap.h` the namespace `ap` is defined. It must be taken into account that the names of functions, constants and classes listed further should be prefixed by ap::.

# Conditional Compilation Settings

AP_WIN32
This symbol (if defined by user) indicates that AP library is compiled under Win32. It allows library to use ABLAS (lightweight BLAS-like library with SSE2 support) if ABLAS is present on your system.

AP_ASSERT
This symbol enables checking of the array boundaries. If it is set by the "define" directive, then at each addressing to the dynamic array elements, the transferred index is verified for its correctness. In case of error the `ap_error` exception is thrown. Checking the array boundaries makes the program more reliable, but slows down the program operation.

NO_AP_ASSERT
This symbol disables checking of the array boundaries. If it is set by the "define" directive, then the index being outside the array boundaries is not checked when the dynamic array elements are addressed.

UNSAFE_MEM_COPY
The "define" directive that sets this symbol is disabled. Do not activate it. The library contains no documentation concerning this symbol.

# Constants

machineepsilon
The constant represents the accuracy of machine operations, that is the minimum number for `1+machineepsilon≠1` in the given bit grid. The constant may be taken "oversized", that is real accuracy can be even higher.

maxrealnumber
The constant represents the highest value of the positive real number, which could be represented on this machine. The constant may be taken "oversized", that is real boundary can be even higher.

minrealnumber
The constant represents the lowest value of positive real number, which could be represented on this machine. The constant may be taken "oversized", that is real boundary can be even lower.

# Functions

int sign(double x)
Returns:
+1, if X>0
-1, if X<0
0, if X=0

double randomreal()
Returns a random real number from half-interval [0,1).

int randominteger(int maxv)
Returns a random integer between 0 and maxv-1.

double round(double x)
Returns the nearest integer to x. If x is right in the middle between two integers, then the function result depends on the implementation.

double trunc(double x)
Truncates the fractional part of x.
trunc(1.3) = 1
trunc(-1.3)= -1

double pi()
Returns the constant π

double sqr(double x)
Returns x2.

double maxreal(double m1, double m2)
Returns the maximum of two real numbers.

double minreal(double m1, double m2)
Returns the minimum of two real numbers.

int maxint(int m1, int m2)
Returns the maximum of two integers.

int minint(int m1, int m2)
Returns the minimum of two integers.

# Class "ap_error"

This is a class of exception which is thrown when different errors occur in the AP library, for example - if the array index is found incorrect when the array boundaries check is enabled. The current version of the class contains no fields and doesn't allow to find the cause for the exception generated.

# Array classes

## Working with arrays

First we will discuss general principles of working with array classes, then describe the classes and their methods.

Classes of the standard library allow operations with matrixes and vectors (one-dimensional and two-dimensional arrays) of variable size and with variable numeration of elements, that is, the array numeration can start at any number, end at any number and change dynamically. Because the array classes are templates, the arrays of the same dimension have the same set of member functions. And as the member functions of arrays with different dimensions differ only by the number of arguments, there is little difference between two-dimensional and one-dimenstional arrays.

Working with an array starts with the array creation. You should distinguish the creation of array class instance and the memory allocation for the array. When creating the class instance, you can use constructor without any parameters, that creates an empty array without any elements, or you can use copy and assignment constructors that copy one array into another. In case the array is created by the default constructor, it contains no elements and an attempt to address them may cause the program failure. If, during the copy operation, the source array has no memory allocated for the array elements, destination array will contain no elements either. If the source array has memory allocated for its elements, destination array will allocate the same amount of memory and copy the elements there. That is, the copy operation yields into two independent arrays with indentical contents.

After an empty array has been created, you should allocate the memory for its elements, using the setbounds method The method parameters set upper and lower boundaries of the array indexes. The upper boundary should be not less than the lower one. When called, memory for corresponding number of elements is allocated. The content of the created array elements is not defined and no suppositions should be made about it. If the setbounds method is called for the array with already allocated memory, then, after changing its parameters, the newly allocated elements also become undefined and the old content is deleted.

To address the array elements, an overloaded operator() is used. That is, the code addressing the element of array a with indexes a(i,j,k) will look like a(i,j,k). Below is given an example of factorial array calculation, illustrating the work with arrays.

    integer_1d_array factarr(int n)
    {
        integer_1d_array result;
        result.setbounds(1,n);
        result(1) = 1;
        for(int i=2; i<=n; i++)
            result(i) = result(i-1)*i;
        return result;
    }

## Class "template_1d_array"

This class is a template of dynamical one-dimensional array with variable upper and lower boundaries. Based on this class, the following classes are constructed:

    typedef template_1d_array<int>     integer_1d_array;
    typedef template_1d_array<double>  real_1d_array;
    typedef template_1d_array<bool>    boolean_1d_array;
    typedef template_1d_array<complex> complex_1d_array;

## Class member functions

template_1d_array()
Constructor. Creates an empty array.

~template_1d_array()
Destructor. Frees memory, which had been allocated for the array.

template_1d_array(const template_1d_array &rhs)
Copy constructor. Allocates the separate storage and copies source array content there.

const template_1d_array& operator=(const template_1d_array &rhs)
Assignment constructor. Deletes destination array content, frees allocated memory, then allocates a separate storage and copies source array content there.

T& operator()(int i)
Addressing the array element number i

void setbounds(int iLow, int iHigh)
Memory allocation for the array . Deletes the array content, frees allocated memory, then allocates a separate storage for iHigh-iLow+1 elements.
The elements numeration in the new array starts with iLow and ends with iHigh The content of the new array is not defined.

void setcontent(int iLow, int iHigh, const T *pContent)
The method is similar to the setbounds() method, but after allocating a memory for a destination array it copies the content of pContent[] there.

T* getcontent()
Gets pointer to the array. The data pointed by the returned pointer can be changed, and the array content will be changed as well.

int getlowbound()
int gethighbound()
Get lower and upper boundaries.

raw_vector<T> getvector(int iStart, int iEnd)
The method is used by the basic subroutines of linear algebra to get access to the internal memory of the array. The method returns an object, holding the pointer to a vector part (starting from the element with iStart index value and finishing with iEnd index value). If iEnd<iStart, then an empty vector is considered to be set.

const_raw_vector<T> getvector(int iStart, int iEnd) const
The method is used by the basic subroutines of linear algebra to get access to the internal memory of the array. The method returns an object, holding the pointer to a vector part (starting from the element with iStart index value and finishing with iEnd index value). If iEnd<iStart, then an empty vector is considered to be set. The returned object is for read only.

## Class "template_2d_array"

This class is a template of dynamical two-dimensional array with variable upper and lower boundaries. Based on this class, the following classes are constructed:

    typedef template_2d_array<int>     integer_2d_array;
    typedef template_2d_array<double>  real_2d_array;
    typedef template_2d_array<bool>    boolean_2d_array;
    typedef template_2d_array<complex> complex_2d_array;

## Class member functions

template_2d_array()
Constructor. Creates an empty array.

~template_2d_array()
Destructor. Frees memory, which had been allocated for the array.

template_2d_array(const template_2d_array &rhs)
Copy constructor. Allocates the separate storage and copies source array content there.

const template_2d_array& operator=(const template_2d_array &rhs)
Assignment constructor. Deletes destination array content, frees allocated memory, then allocates a separate storage and copies source array content there.

T& operator()(int i1, int i2)
Addressing the array element with [i1,i2] index value.

void setbounds(int iLow1, int iHigh1, int iLow2, int iHigh2)
Memory allocation for the array . Deletes the array content, frees allocated memory, then allocates a separate storage for (iHigh1-iLow1+1)*(iHigh2-iLow2+1) elements.
The elements numeration in the new array starts with iLow1 and finishes with iHigh1 for the first dimension, and similarly for the second dimension.
The content of the new array is not defined.

void setcontent(int iLow1, int iHigh1, int iLow2, int iHigh2, const T *pContent)
The method is similar to the setbounds() method, but after allocating a memory for a destination array it copies the content of pContent[] there.
The pContent array contains two-dimensional array, written in line, that is, the first element is [iLow1, iLow2], then goes [iLow1, iLow2+1], and so on.

int getlowbound(int iBoundNum)
int gethighbound(int iBoundNum)
Get lower and upper boundaries of one-dimensional array with number iBoundNum.

raw_vector getcolumn(int iColumn, int iRowStart, int iRowEnd)
const_raw_vector getcolumn(int iColumn, int iRowStart, int iRowEnd) const
The methods are used by the basic subroutines of linear algebra to get access to the internal memory of the array. The methods return the object holding the pointer to the part of column iColumn (starting from the line iRowStart and finishing with the line iRowEnd).
The iColumn parameter must be the valid column number (that is be within the boundaries of the array). If iRowEnd<iRowStart, then an empty column is considered to be set.

raw_vector getrow(int iRow, int iColumnStart, int iColumnEnd)
const_raw_vector getrow(int iRow, int iColumnStart, int iColumnEnd) const
The methods are used by the basic subroutines of linear algebra to get access to the internal memory of the array. The methods return the object holding the pointer to the part of line iRow (starting from the column iColumnStart and finishing with the column iColumnEnd).
The iRow parameter must be the valid line number (that is be within the boundaries of the array). If iColumnEnd<iColumnStart, then an empty line is considered to be set.

# Basic subroutines of linear algebra

Basic subroutines of linear algebra included into the AP library are close by their functions to the Level 1 BLAS, allowing to perform the simplest operations with vectors and with the matrix lines and columns.

Subroutines should be used in the following way. First you need to get an object of the `raw_vector` type or `const_raw_vector` type, pointing to the part of the matrix or array being processed using the methods `getcolumn`/`getrow` (for the matrix), or `getvector` (for the array). The object holds the pointer for the line (or column) start, the number of elements in the processed line (column), and the interval between the two adjacent elements. When using a standard scheme for matrixes storage in the memory (that is, by lines), the interval between the elements of one line equals 1, and the interval between the adjacent elements of one column equals the number of columns. The received object is transferred as argument to the corresponding subroutine, which performs operations on the matrix part pointed by the internal object pointer.

Below is given the list of basic subroutines of linear algebra, available in the AP library.

template<class T> T vdotproduct(const_raw_vector<T> v1, const_raw_vector<T> v2)
The subroutine calculates the scalar product of transferred vectors.

template<class T> void vmove(raw_vector<T> vdst, const_raw_vector<T> vsrc)
template<class T> void vmoveneg(raw_vector<T> vdst, const_raw_vector<T> vsrc)
template<class T, class T2> void vmove(raw_vector<T> vdst, const_raw_vector<T> vsrc, T2 alpha)
This subroutine set is used to copy one vector content to another vector using different methods: simple copy, copy multiplied by -1, copy multiplied by a number.

template<class T> void vadd(raw_vector<T> vdst, const_raw_vector<T> vsrc)
template<class T, class T2> void vadd(raw_vector<T> vdst, const_raw_vector<T> vsrc, T2 alpha)
This subroutine set is used to add one vector to another using different methods: simple addition or addition multiplied by a number.

template<class T> void vsub(raw_vector<T> vdst, const_raw_vector<T> vsrc)
template<class T, class T2> void vsub(raw_vector<T> vdst, const_raw_vector<T> vsrc, T2 alpha)
This subroutine set is used to subtract one vector from another using different methods: simple subtraction or subtraction multiplied by a number.

template<class T, class T2> void vmul(raw_vector<T> vdst, T2 alpha)
Multiplies vector by a number and stores the result in the same place.

## Alternative syntax

If both operands are vectors/rows with interval between the elements equals 1 and length equals N, alternative syntax can be used.

template<class T> T vdotproduct(const T *v1, const T *v2, int N)
template<class T> void vmove(T *vdst, const T *vsrc, int N)
template<class T> void vmoveneg(T *vdst, const T *vsrc, int N)
template<class T, class T2> void vmove(T *vdst, const T *vsrc, int N, T2 alpha)
template<class T> void vadd(T *vdst, const T *vsrc, int N)
template<class T, class T2> void vadd(T *vdst, const T *vsrc, int N, T2 alpha)
template<class T> void vsub(T *vdst, const T *vsrc, int N)
template<class T, class T2> void vsub(T *vdst, const T *vsrc, int N, T2 alpha)
template<class T, class T2> void vmul(T *vdst, int N, T2 alpha)

# Class of complex numbers

AP library includes the `ap::complex` class that allows operations with compex numbers. Access to real and imaginary parts of complex number is implemented through the public fields `x` and `y`. Arithmetical operations are supported, the same as with embedded data types, by overloading of operations: addition, subtraction, multiplication and division. Addition, subtraction and multiplication are performed by a usual way (i.e., according to their definition which can be found in any textdook in algebra), division is performed using so called "safe" algorithm that could never cause overflow when calculating intermediate results. The library also includes several functions performing elementary operations with complex numbers.

const double abscomplex(const complex &z)
Returns the modulus of complex number z. It should be noted that the modulus calculation is performed using so called "safe" algorithm, that could never cause overflow when calculating intermediate results.

const complex conj(const complex &z)
Returns complex conjugate to z.

const complex csqr(const complex &z)
Returns the square of z.