<commit_before>
#include <avr/interrupt.h>
#include "HalfDuplexHardwareSerial.h"

#define USART_PORT PORTD
#define USART_DDR DDRD
#define USART_PIN PIND
#define USART_RX_PIN PD0
#define USART_TX_PIN PD1

#define USART0_PORT PORTD
#define USART0_DDR DDRD
#define USART0_PIN PIND
#define USART0_RX_PIN PD0
#define USART0_TX_PIN PD1

#define USART1_PORT PORTD
#define USART1_DDR DDRD
#define USART1_PIN PIND
#define USART1_RX_PIN PD2
#define USART1_TX_PIN PD3

#define USART_N_PORT(usart) USART ## usart ## _PORT
#define USART_N_DDR(usart) USART ## usart ## _DDR
#define USART_N_PIN(usart) USART ## usart ## _PIN
#define USART_N_RX_PIN(usart) USART## usart ## _RX_PIN
#define USART_N_TX_PIN(usart) USART## usart ## _TX_PIN

#define USART_ENABLE_RX() \
    UCSRA &= ~(_BV(FE) | _BV(DOR) | _BV(UPE); \
    UCSRB |= _BV(RXEN);

#define USART_N_ENABLE_RX(usart) \
    UCSR ## usart ## A &= ~(_BV(FE ## usart) | _BV(DOR ## usart) | _BV(UPE ## usart)); \
    UCSR ## usart ## B |= _BV(RXEN ## usart);

#define USART_DISABLE_RX() \
    UCSRB &= ~_BV(RXEN); \
    USART_DDR &= ~_BV(USART_RX_PIN()); \
    USART_PORT &= ~_BV(USART_RX_PIN());

#define USART_N_DISABLE_RX(usart) \
    UCSR ## usart ## B &= ~_BV(RXEN ## usart); \
    USART ## usart ## _DDR &= ~_BV(USART ## usart ## _RX_PIN); \
    USART ## usart ## _PORT &= ~_BV(USART ## usart ## _RX_PIN);

#define USART_ENABLE_TX() \
    USART_DDR |= _BV(USART_TX_PIN); \
    USART_PORT |= _BV(USART_TX_PIN); \
    UCSRB |= _BV(TXEN);

#define USART_N_ENABLE_TX(usart) \
    USART ## usart ## _DDR |= _BV(USART ## usart ## _TX_PIN); \
    USART ## usart ## _PORT |= _BV(USART ## usart ## _TX_PIN); \
    UCSR ## usart ## B |= _BV(TXEN ## usart);

#define USART_N_DISABLE_TX(usart) \
    cli(); \
    while ((UCSRA & _BV(TXC)) == 0); \
    UCSRA &= ~(_BV(FE) | _BV(DOR) | _BV(UPE); \
    UCSRB &= ~_BV(TXEN); \
    USART_DDR &= ~_BV(USART_TX_PIN); \
    USART_PORT &= ~_BV(USART_TX_PIN); \
    sei();

#define USART_N_DISABLE_TX(usart) \
    cli(); \
    while ((UCSR ## usart ## A & _BV(TXC ## usart)) == 0); \
    UCSR ## usart ## A &= ~(_BV(FE ## usart) | _BV(DOR ## usart) | _BV(UPE ## usart)); \
    UCSR ## usart ## B &= ~_BV(TXEN ## usart); \
    USART_N_DDR(usart) &= ~_BV(USART_N_TX_PIN(usart)); \
    USART_N_PORT(usart) &= ~_BV(USART_N_TX_PIN(usart)); \
    sei();

void HalfDuplexHardwareSerial::begin(unsigned long baud) {
  mSerial.begin(baud);
  setDirection(kReceiveOnly);
}

void HalfDuplexHardwareSerial::begin(unsigned long baud, uint8_t config) {
  mSerial.begin(baud,config);
  setDirection(kReceiveOnly);
}

size_t HalfDuplexHardwareSerial::writeLast(uint8_t b) {
  size_t sent;
  cli();
  sent = mSerial.write(b);
  setDirection(kReceiveOnly);
  sei();
}

void HalfDuplexHardwareSerial::setDirection(Direction direction) {
  if (direction == mDirection) {
    return;
  }
  else if (direction == kTransmitOnly) {
    disableRx();
    enableTx();
  }
  else {
    disableTx();
    enableRx();
  }
  mDirection = direction;
}

void HalfDuplexHardwareSerial::enableRx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_ENABLE_RX()
#else
    USART_N_ENABLE_RX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_ENABLE_RX(1)

  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_ENABLE_RX(2)

  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_ENABLE_RX(3)
  }
#endif
}

void HalfDuplexHardwareSerial::disableRx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_DISABLE_RX()
#else
    USART_N_DISABLE_RX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_DISABLE_RX(1)
  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_DISABLE_RX(2)
  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_DISABLE_RX(3)
  }
#endif
}

void HalfDuplexHardwareSerial::enableTx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_ENABLE_TX()
#else
    USART_N_ENABLE_TX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_ENABLE_TX(1)

  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_ENABLE_TX(2)

  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_ENABLE_TX(3)
  }
#endif
}

void HalfDuplexHardwareSerial::disableTx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_DISABLE_TX()
#else
    USART_N_DISABLE_TX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_DISABLE_TX(1)
  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_DISABLE_TX(2)
  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_DISABLE_TX(3)
  }
#endif
}

<commit_msg>Change incorrectly named USART disable Tx macro.<commit_after>
#include <avr/interrupt.h>
#include "HalfDuplexHardwareSerial.h"

#define USART_PORT PORTD
#define USART_DDR DDRD
#define USART_PIN PIND
#define USART_RX_PIN PD0
#define USART_TX_PIN PD1

#define USART0_PORT PORTD
#define USART0_DDR DDRD
#define USART0_PIN PIND
#define USART0_RX_PIN PD0
#define USART0_TX_PIN PD1

#define USART1_PORT PORTD
#define USART1_DDR DDRD
#define USART1_PIN PIND
#define USART1_RX_PIN PD2
#define USART1_TX_PIN PD3

#define USART_N_PORT(usart) USART ## usart ## _PORT
#define USART_N_DDR(usart) USART ## usart ## _DDR
#define USART_N_PIN(usart) USART ## usart ## _PIN
#define USART_N_RX_PIN(usart) USART## usart ## _RX_PIN
#define USART_N_TX_PIN(usart) USART## usart ## _TX_PIN

#define USART_ENABLE_RX() \
    UCSRA &= ~(_BV(FE) | _BV(DOR) | _BV(UPE); \
    UCSRB |= _BV(RXEN);

#define USART_N_ENABLE_RX(usart) \
    UCSR ## usart ## A &= ~(_BV(FE ## usart) | _BV(DOR ## usart) | _BV(UPE ## usart)); \
    UCSR ## usart ## B |= _BV(RXEN ## usart);

#define USART_DISABLE_RX() \
    UCSRB &= ~_BV(RXEN); \
    USART_DDR &= ~_BV(USART_RX_PIN()); \
    USART_PORT &= ~_BV(USART_RX_PIN());

#define USART_N_DISABLE_RX(usart) \
    UCSR ## usart ## B &= ~_BV(RXEN ## usart); \
    USART ## usart ## _DDR &= ~_BV(USART ## usart ## _RX_PIN); \
    USART ## usart ## _PORT &= ~_BV(USART ## usart ## _RX_PIN);

#define USART_ENABLE_TX() \
    USART_DDR |= _BV(USART_TX_PIN); \
    USART_PORT |= _BV(USART_TX_PIN); \
    UCSRB |= _BV(TXEN);

#define USART_N_ENABLE_TX(usart) \
    USART ## usart ## _DDR |= _BV(USART ## usart ## _TX_PIN); \
    USART ## usart ## _PORT |= _BV(USART ## usart ## _TX_PIN); \
    UCSR ## usart ## B |= _BV(TXEN ## usart);

#define USART_DISABLE_TX(usart) \
    cli(); \
    while ((UCSRA & _BV(TXC)) == 0); \
    UCSRA &= ~(_BV(FE) | _BV(DOR) | _BV(UPE); \
    UCSRB &= ~_BV(TXEN); \
    USART_DDR &= ~_BV(USART_TX_PIN); \
    USART_PORT &= ~_BV(USART_TX_PIN); \
    sei();

#define USART_N_DISABLE_TX(usart) \
    cli(); \
    while ((UCSR ## usart ## A & _BV(TXC ## usart)) == 0); \
    UCSR ## usart ## A &= ~(_BV(FE ## usart) | _BV(DOR ## usart) | _BV(UPE ## usart)); \
    UCSR ## usart ## B &= ~_BV(TXEN ## usart); \
    USART_N_DDR(usart) &= ~_BV(USART_N_TX_PIN(usart)); \
    USART_N_PORT(usart) &= ~_BV(USART_N_TX_PIN(usart)); \
    sei();

void HalfDuplexHardwareSerial::begin(unsigned long baud) {
  mSerial.begin(baud);
  setDirection(kReceiveOnly);
}

void HalfDuplexHardwareSerial::begin(unsigned long baud, uint8_t config) {
  mSerial.begin(baud,config);
  setDirection(kReceiveOnly);
}

size_t HalfDuplexHardwareSerial::writeLast(uint8_t b) {
  size_t sent;
  cli();
  sent = mSerial.write(b);
  setDirection(kReceiveOnly);
  sei();
}

void HalfDuplexHardwareSerial::setDirection(Direction direction) {
  if (direction == mDirection) {
    return;
  }
  else if (direction == kTransmitOnly) {
    disableRx();
    enableTx();
  }
  else {
    disableTx();
    enableRx();
  }
  mDirection = direction;
}

void HalfDuplexHardwareSerial::enableRx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_ENABLE_RX()
#else
    USART_N_ENABLE_RX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_ENABLE_RX(1)

  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_ENABLE_RX(2)

  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_ENABLE_RX(3)
  }
#endif
}

void HalfDuplexHardwareSerial::disableRx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_DISABLE_RX()
#else
    USART_N_DISABLE_RX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_DISABLE_RX(1)
  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_DISABLE_RX(2)
  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_DISABLE_RX(3)
  }
#endif
}

void HalfDuplexHardwareSerial::enableTx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_ENABLE_TX()
#else
    USART_N_ENABLE_TX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_ENABLE_TX(1)

  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_ENABLE_TX(2)

  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_ENABLE_TX(3)
  }
#endif
}

void HalfDuplexHardwareSerial::disableTx() {
  if (false) {}
#ifdef HAVE_HWSERIAL0
  else if (&mSerial == &Serial) {
#if defined(UBRRH) && defined(UBRRL)
    USART_DISABLE_TX()
#else
    USART_N_DISABLE_TX(0)
#endif
  }
#endif
#ifdef HAVE_HWSERIAL1
  else if (&mSerial == &Serial1) {
    USART_N_DISABLE_TX(1)
  }
#endif
#ifdef HAVE_HWSERIAL2
  else if (&mSerial == &Serial2) {
    USART_N_DISABLE_TX(2)
  }
#endif
#ifdef HAVE_HWSERIAL3
  else if (&mSerial == &Serial3) {
    USART_N_DISABLE_TX(3)
  }
#endif
}

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mscenelayereffectdimview.h"

#include "mscenewindowview_p.h"
#include "mviewcreator.h"
#include "mscenelayereffect.h"
#include "mscenelayereffectmodel.h"
#include <mdeviceprofile.h>
#include "mscenemanager.h"

//! \internal
class MSceneLayerEffectDimViewPrivate : public MSceneWindowViewPrivate
{
public:
    MSceneLayerEffect *controller;
};
//! \internal_end

MSceneLayerEffectDimView::MSceneLayerEffectDimView(MSceneLayerEffect *controller) :
    MSceneWindowView(*new MSceneLayerEffectDimViewPrivate, controller)
{
    Q_D(MSceneLayerEffectDimView);
    d->controller = controller;

    d->controller->setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true);
}

MSceneLayerEffectDimView::~MSceneLayerEffectDimView()
{
}

void MSceneLayerEffectDimView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_D(MSceneLayerEffectDimView);
    Q_UNUSED(widget);
    Q_UNUSED(option);

    qreal oldOpacity = painter->opacity();
    qreal opacity = d_ptr->controller->effectiveOpacity() * style()->opacity();

    QTransform oldTransform = painter->transform();
    QTransform transform;
    M::Orientation layerEffectOrientation = M::Landscape;

    QRectF geometry = d->controller->geometry();
    if (geometry.height() > geometry.width()) {
        layerEffectOrientation = M::Portrait;
    }

    if (layerEffectOrientation != MDeviceProfile::instance()->orientationFromAngle(M::Angle0)) {
        // layer effect's orientation is different than display's native orientation.
        // Therefore we have to place our layer effect sideways.
        transform.translate(0, geometry.width());
        transform.rotate(-90);
    }

    painter->setTransform(transform);
    painter->setOpacity(opacity);
    painter->fillRect(boundingRect(), QColor(0, 0, 0));
    painter->setOpacity(oldOpacity);

    painter->setTransform(oldTransform);
}

QRectF MSceneLayerEffectDimView::boundingRect() const
{
    Q_D(const MSceneLayerEffectDimView);
    return QRectF(QPointF(0, 0), d->controller->size());
}

void MSceneLayerEffectDimView::applyStyle()
{
    MSceneWindowView::applyStyle();
}

M_REGISTER_VIEW_NEW(MSceneLayerEffectDimView, MSceneLayerEffect)
<commit_msg>Changes: MSceneLayerEffectDimView - use backgroundImage if available<commit_after>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mscenelayereffectdimview.h"

#include "mscenewindowview_p.h"
#include "mviewcreator.h"
#include "mscenelayereffect.h"
#include "mscenelayereffectmodel.h"
#include <mdeviceprofile.h>
#include "mscenemanager.h"
#include <mscalableimage.h>

//! \internal
class MSceneLayerEffectDimViewPrivate : public MSceneWindowViewPrivate
{
public:
    MSceneLayerEffect *controller;
};
//! \internal_end

MSceneLayerEffectDimView::MSceneLayerEffectDimView(MSceneLayerEffect *controller) :
    MSceneWindowView(*new MSceneLayerEffectDimViewPrivate, controller)
{
    Q_D(MSceneLayerEffectDimView);
    d->controller = controller;

    d->controller->setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true);
}

MSceneLayerEffectDimView::~MSceneLayerEffectDimView()
{
}

void MSceneLayerEffectDimView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_D(MSceneLayerEffectDimView);
    Q_UNUSED(widget);
    Q_UNUSED(option);

    qreal oldOpacity = painter->opacity();
    qreal opacity = d_ptr->controller->effectiveOpacity() * style()->opacity();

    QTransform oldTransform = painter->transform();
    QTransform transform;
    M::Orientation layerEffectOrientation = M::Landscape;

    QRectF geometry = d->controller->geometry();
    if (geometry.height() > geometry.width()) {
        layerEffectOrientation = M::Portrait;
    }

    if (layerEffectOrientation != MDeviceProfile::instance()->orientationFromAngle(M::Angle0)) {
        // layer effect's orientation is different than display's native orientation.
        // Therefore we have to place our layer effect sideways.
        transform.translate(0, geometry.width());
        transform.rotate(-90);
    }

    painter->setTransform(transform);
    painter->setOpacity(opacity);

    if(style()->backgroundImage()) {
        style()->backgroundImage()->draw(boundingRect(), painter);
    } else {
        painter->fillRect(boundingRect(), QColor(0, 0, 0));
    }

    painter->setOpacity(oldOpacity);

    painter->setTransform(oldTransform);
}

QRectF MSceneLayerEffectDimView::boundingRect() const
{
    Q_D(const MSceneLayerEffectDimView);
    return QRectF(QPointF(0, 0), d->controller->size());
}

void MSceneLayerEffectDimView::applyStyle()
{
    MSceneWindowView::applyStyle();
}

M_REGISTER_VIEW_NEW(MSceneLayerEffectDimView, MSceneLayerEffect)
<|endoftext|>


<commit_before>#include <iostream> //cout
#include <cstdlib>	//rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> 	//LaGenMatComplex
#include <laslv.h>  //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>

using namespace std;

/* Total [13/20] */

/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
    cout << scalar << endl;
}                                                 //working
void print_scalar(const COMPLEX scalar, const string name){
    cout << name << ":" << scalar << endl;
}                              //working
void print_array(const COMPLEX array[], int len){
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                                        //working
void print_array(const COMPLEX array[], int len, const string name){
	cout << name << ":" << endl;
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                     //working
void print_matrix(const LaGenMatComplex& matrix){
	cout << matrix << endl;
}                                        //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
	cout << name << ":" << endl << matrix << endl;
}			          //working

/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
    A.r = rand() % x;	//1 to x
    A.i = rand() % x;
}                                           //working
void generate_scalar(int A, const int x){
    A = rand() % x;	//1 to x
}                                                //working
void generate_array(COMPLEX array[], const int len, const int x){
	srand(time(NULL));				//seed
    for(int i = 0; i < len; i++){
        array[i].r = rand() % x;	//1 to x
        array[i].i = rand() % x;
	}
}                        //working

/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
    for(int i = 0; i < len; i++){
        array[i] = vector(i);
    }
}       //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
    diag = 0;
    for(int i = 0; i < len; i++){
        diag(i, i) = array[i];
    }
}               //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
    COMPLEX array[len];
    vec_to_array(vector, len, array);
    array_to_diag(array, len, diag);
}   //working

/* Scalar manipulation [5/8] */
int factorial(int x){
	if(x <= 1){
        return 1;
	}else{
        return x * factorial(x - 1);
	}
}                                                                    //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
    result.r = A.r + B.r;
    result.i = A.i + B.i;
}              //working
void scalar_addition(COMPLEX& result, const COMPLEX addition){
    result.r += addition.r;
    result.i += addition.i;
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r * B;
    result.i = A.i * B;
}              //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA * laB;
    result = laResult.toCOMPLEX();
}         //to test
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r / B;
    result.i = A.i / B;
}                    //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA / laB;
    result = laResult.toCOMPLEX();
}               //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
    la::complex<double> laResult = la::complex<double>(number);
    la::complex<double> laNumber = la::complex<double>(number);
    for(int i = 1; i < power; i++){
        laResult *= laNumber;
    }
    result = laResult.toCOMPLEX();
}             //to test
void scalar_exponential_1(const COMPLEX& number, const int iterations, COMPLEX& result){
    COMPLEX division, total_division, A;
    result.r = 1;
    result.i = 1;
    for(int step = 1; step <= iterations; step++){   //sum (from 1 to n)
        division.r = 0;
        division.i = 0;
        total_division.r = 1;
        total_division.i = 0;
        for(int i = 1; i <= step; i++){        //    ( num^n / n!)
            cout << "division = " << division << endl;
            cout << "total_division = " << total_division << endl;
            A = total_division;
            scalar_division(number, i, division);
            scalar_multiplication(A, division, total_division);
        }
        scalar_addition(result, total_division);
        cout << "sum = " << result << endl;
    }
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
}         //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
//    COMPLEX result, division, multiplication;
//	if(step <= 1){
//        result.r = 1;
//        return result;
//	}else{
//        scalar_division(number,step,division);
//        scalar_multiplication(division, rec_scalar_exp_step(step-1),  multiplication);
//        return multiplication;
//	}
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
} //empty

/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
    /*
    for(int i = 0; i < len; i++){
        array[i] = complex_power(array[i], power, result);
    }
    */
}                       //empty

/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){      //empty
  //...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
    //LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
    LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){                                                               //working
    // LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
    LaVectorLongInt PIV = LaVectorLongInt(len);
    LUFactorizeIP(matrix, PIV);
    LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){                                 //empty
    //
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
    //LaGenMatComplex step = LaGenMatComplex

} //empty

/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
    COMPLEX compA;                                                              //initialisation
    generate_scalar(compA, max_rand);
    COMPLEX compB;
    generate_scalar(compB, max_rand);
    int realB;
    generate_scalar(realB, max_rand);
    COMPLEX result;

    for(int i = 1; i < 5; i++){                                                 //factorials
        cout << "factorial(" << i << "): " << factorial(i) << endl;
    }

    scalar_addition(compA, compB, result);                                      //addition/subtraction
    cout << "scalar addition: " << result << endl << endl;

    scalar_multiplication(compA, realB, result);                                //multiplication
    cout << "scalar multiplication by scalar: " << result << endl << endl;
    scalar_multiplication(compA, compB, result);
    cout << "scalar multiplication by complex: " << result << endl << endl;

    scalar_division(compA, realB, result);                                      //division
    cout << "scalar division by scalar: " << result << endl << endl;
    scalar_division(compA, compB, result);
    cout << "scalar division by complex: " << result << endl << endl;

    for(int i = 1; i < 5; i++){
        scalar_powers(compA, i, result);
        cout << "scalar powers - A^" << i << " = " << result << endl;
    }

}                                       //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
    LaVectorComplex eigenvalueVec = LaVectorComplex(size);             //initialise eigenstuff
    LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
    LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
    matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
    print_matrix(eigenvalueVec, "eigenvalue vector");               //print eigenstuff
    vec_to_diag(eigenvalueVec, size, eigenvalues);
    print_matrix(eigenvalues, "eigenvalue matrix");
    print_matrix(eigenvectors, "eigenvector matrix");
}             //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
    LaGenMatComplex inverseMatrix;
    inverseMatrix = initialMatrix.copy();
    matrix_inverse(inverseMatrix, size);
    print_matrix(inverseMatrix, "inverse matrix");
}                 //to test
void test_scalar_exponential(const int iterations, const int max_rand){
    COMPLEX number, result;
    generate_scalar(number, max_rand);
    cout << endl << "scalar exponential test no.: " << number << endl << endl;
    scalar_exponential_1(number, iterations, result);
    cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
    //...
}

/* Main Program */
int main(){
//	int matrix_size = 3, max_rand = 9;
//    int matrix_volume = matrix_size * matrix_size;

	/* generate the matrix */
//    COMPLEX elements[matrix_volume];
//    generate_array(elements, matrix_volume, max_rand);
//	LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );

//    print_matrix(initialMatrix, "initial matrix");

    /* test eigenvalues */
//    test_eigenvalues(initialMatrix, matrix_size);

    /* test scalar manipulation */
//    test_scalar_manipulation(4);

    /* test scalar sum */

    /* test scalar product */

    /* test scalar exponentials */
//    test_scalar_exponential(3,4);

    /* test inversion */
//    test_inverse(initialMatrix, matrix_size);
}
<commit_msg>testing<commit_after>#include <iostream> //cout
#include <cstdlib>	//rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> 	//LaGenMatComplex
#include <laslv.h>  //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>

using namespace std;

/* Total [13/20] */

/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
    cout << scalar << endl;
}                                                 //working
void print_scalar(const COMPLEX scalar, const string name){
    cout << name << ":" << scalar << endl;
}                              //working
void print_array(const COMPLEX array[], int len){
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                                        //working
void print_array(const COMPLEX array[], int len, const string name){
	cout << name << ":" << endl;
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                     //working
void print_matrix(const LaGenMatComplex& matrix){
	cout << matrix << endl;
}                                        //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
	cout << name << ":" << endl << matrix << endl;
}			          //working

/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
    A.r = rand() % x;	//1 to x
    A.i = rand() % x;
}                                           //working
void generate_scalar(int A, const int x){
    A = rand() % x;	//1 to x
}                                                //working
void generate_array(COMPLEX array[], const int len, const int x){
	srand(time(NULL));				//seed
    for(int i = 0; i < len; i++){
        array[i].r = rand() % x;	//1 to x
        array[i].i = rand() % x;
	}
}                        //working

/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
    for(int i = 0; i < len; i++){
        array[i] = vector(i);
    }
}       //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
    diag = 0;
    for(int i = 0; i < len; i++){
        diag(i, i) = array[i];
    }
}               //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
    COMPLEX array[len];
    vec_to_array(vector, len, array);
    array_to_diag(array, len, diag);
}   //working

/* Scalar manipulation [5/8] */
int factorial(int x){
	if(x <= 1){
        return 1;
	}else{
        return x * factorial(x - 1);
	}
}                                                                    //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
    result.r = A.r + B.r;
    result.i = A.i + B.i;
}              //working
void scalar_addition(COMPLEX& result, const COMPLEX addition){
    result.r += addition.r;
    result.i += addition.i;
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r * B;
    result.i = A.i * B;
}              //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA * laB;
    result = laResult.toCOMPLEX();
}         //to test
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r / B;
    result.i = A.i / B;
}                    //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA / laB;
    result = laResult.toCOMPLEX();
}               //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
    la::complex<double> laResult = la::complex<double>(number);
    la::complex<double> laNumber = la::complex<double>(number);
    for(int i = 1; i < power; i++){
        laResult *= laNumber;
    }
    result = laResult.toCOMPLEX();
}             //to test
void scalar_exponential_1(const COMPLEX& number, const int iterations, COMPLEX& result){
    COMPLEX division, total_division, A;
    result.r = 1;
    result.i = 1;
    for(int step = 1; step <= iterations; step++){   //sum (from 1 to n)
        division.r = 0;
        division.i = 0;
        total_division.r = 1;
        total_division.i = 0;
        for(int i = 1; i <= step; i++){        //    ( num^n / n!)
            cout << "division = " << division << endl;
            cout << "total_division = " << total_division << endl;
            A = total_division;
            scalar_division(number, i, division);
            scalar_multiplication(A, division, total_division);
        }
        scalar_addition(result, total_division);
        cout << "sum = " << result << endl;
    }
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
}         //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
//    COMPLEX result, division, multiplication;
//	if(step <= 1){
//        result.r = 1;
//        return result;
//	}else{
//        scalar_division(number,step,division);
//        scalar_multiplication(division, rec_scalar_exp_step(step-1),  multiplication);
//        return multiplication;
//	}
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
} //empty

/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
    /*
    for(int i = 0; i < len; i++){
        array[i] = complex_power(array[i], power, result);
    }
    */
}                       //empty

/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){      //empty
  //...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
    //LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
    LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){                                                               //working
    // LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
    LaVectorLongInt PIV = LaVectorLongInt(len);
    LUFactorizeIP(matrix, PIV);
    LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){                                 //empty
    //
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
    //LaGenMatComplex step = LaGenMatComplex

} //empty

/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
    COMPLEX compA;                                                              //initialisation
    generate_scalar(compA, max_rand);
    COMPLEX compB;
    generate_scalar(compB, max_rand);
    int realB;
    generate_scalar(realB, max_rand);
    COMPLEX result;

    for(int i = 1; i < 5; i++){                                                 //factorials
        cout << "factorial(" << i << "): " << factorial(i) << endl;
    }

    scalar_addition(compA, compB, result);                                      //addition/subtraction
    cout << "scalar addition: " << result << endl << endl;

    scalar_multiplication(compA, realB, result);                                //multiplication
    cout << "scalar multiplication by scalar: " << result << endl << endl;
    scalar_multiplication(compA, compB, result);
    cout << "scalar multiplication by complex: " << result << endl << endl;

    scalar_division(compA, realB, result);                                      //division
    cout << "scalar division by scalar: " << result << endl << endl;
    scalar_division(compA, compB, result);
    cout << "scalar division by complex: " << result << endl << endl;

    for(int i = 1; i < 5; i++){
        scalar_powers(compA, i, result);
        cout << "scalar powers - A^" << i << " = " << result << endl;
    }

}                                       //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
    LaVectorComplex eigenvalueVec = LaVectorComplex(size);             //initialise eigenstuff
    LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
    LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
    matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
    print_matrix(eigenvalueVec, "eigenvalue vector");               //print eigenstuff
    vec_to_diag(eigenvalueVec, size, eigenvalues);
    print_matrix(eigenvalues, "eigenvalue matrix");
    print_matrix(eigenvectors, "eigenvector matrix");
}             //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
    LaGenMatComplex inverseMatrix;
    inverseMatrix = initialMatrix.copy();
    matrix_inverse(inverseMatrix, size);
    print_matrix(inverseMatrix, "inverse matrix");
}                 //to test
void test_scalar_sum(const int rand_max, const int iterations){
    COMPLEX number;
    generate_scalar(number, max_rand);
    for(int i = 0; i < iterations; i++){
        cout << number << endl;
        scalar_addition(number, number);
    }
    cout << number << endl;
}
void test_scalar_exponential(const int iterations, const int max_rand){
    COMPLEX number, result;
    generate_scalar(number, max_rand);
    cout << endl << "scalar exponential test no.: " << number << endl << endl;
    scalar_exponential_1(number, iterations, result);
    cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
    //...
}

/* Main Program */
int main(){
//	int matrix_size = 3, max_rand = 9;
//    int matrix_volume = matrix_size * matrix_size;

	/* generate the matrix */
//    COMPLEX elements[matrix_volume];
//    generate_array(elements, matrix_volume, max_rand);
//	LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );

//    print_matrix(initialMatrix, "initial matrix");

    /* test eigenvalues */
//    test_eigenvalues(initialMatrix, matrix_size);

    /* test scalar manipulation */
//    test_scalar_manipulation(4);

    /* test scalar sum */
    test_scalar_sum(4,3)

    /* test scalar product */

    /* test scalar exponentials */
//    test_scalar_exponential(3,4);

    /* test inversion */
//    test_inverse(initialMatrix, matrix_size);
}
<|endoftext|>


<commit_before>#include <iostream> //cout
#include <cstdlib>	//rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> 	//LaGenMatComplex
#include <laslv.h>  //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
//#include <random>   //random_device, mt19937

using namespace std;

/* Total [13/20] */

int ran(int a, int b){
//    random_device rd;
//    mt19937 gen(rd());
//    uniform_int_distribution<> dist(a, b);
//    return dist(gen);
    return rand() % b;
}

/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
    cout << scalar << endl;
}                                                 //working
void print_scalar(const COMPLEX scalar, const string name){
    cout << name << ":" << scalar << endl;
}                              //working
void print_array(const COMPLEX array[], int len){
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                                        //working
void print_array(const COMPLEX array[], int len, const string name){
	cout << name << ":" << endl;
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                     //working
void print_matrix(const LaGenMatComplex& matrix){
	cout << matrix << endl;
}                                        //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
	cout << name << ":" << endl << matrix << endl;
}			          //working

/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
    A.r = ran(1, x);	//1 to x
    A.i = ran(1, x);
}               //working
void generate_scalar(int number, const int x){
    number = ran(1, x);	//1 to x
}                                                //working
void generate_array(COMPLEX array[], const int len, const int x){
    for(int i = 0; i < len; i++){
        array[i].r = ran(1, x);	//1 to x
        array[i].i = ran(1, x);
	}
}                        //working

/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
    for(int i = 0; i < len; i++){
        array[i] = vector(i);
    }
}       //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
    diag = 0;
    for(int i = 0; i < len; i++){
        diag(i, i) = array[i];
    }
}               //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
    COMPLEX array[len];
    vec_to_array(vector, len, array);
    array_to_diag(array, len, diag);
}   //working

/* Scalar manipulation [5/8] */
int factorial(int x){
	if(x <= 1){
        return 1;
	}else{
        return x * factorial(x - 1);
	}
}                                                                    //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
    result.r = A.r + B.r;
    result.i = A.i + B.i;
}              //working
void scalar_addition(COMPLEX& result, const COMPLEX addition){
    result.r += addition.r;
    result.i += addition.i;
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r * B;
    result.i = A.i * B;
}              //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA * laB;
    result = laResult.toCOMPLEX();
}         //to test
void scalar_product(COMPLEX& total, const COMPLEX& number){
    COMPLEX part;
    part.r = (total.r * number.r) - (total.i * number.i);
    part.i = (total.r * number.i) + (total.i * number.r);
    total = part;
}
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r / B;
    result.i = A.i / B;
}                    //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA / laB;
    result = laResult.toCOMPLEX();
}               //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
    la::complex<double> laResult = la::complex<double>(number);
    la::complex<double> laNumber = la::complex<double>(number);
    for(int i = 1; i < power; i++){
        laResult *= laNumber;
    }
    result = laResult.toCOMPLEX();
}             //to test
void scalar_exponential_main(const COMPLEX& number, const int iterations, COMPLEX& result){
    COMPLEX division, total_division;
    result.r = 1;
    result.i = 0 ;
    for(int step = 1; step <= iterations; step++){   //sum (from 1 to n)
        total_division.r = 1;
        total_division.i = 0;
        for(int i = 1; i <= step; i++){        //    ( num^n / n!)
            scalar_division(number, i, division);
            scalar_product(total_division, division);
        }
        scalar_addition(result, total_division);
    }
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
}         //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
//    COMPLEX result, division, multiplication;
//	if(step <= 1){
//        result.r = 1;
//        return result;
//	}else{
//        scalar_division(number,step,division);
//        scalar_multiplication(division, rec_scalar_exp_step(step-1),  multiplication);
//        return multiplication;
//	}
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
} //empty

/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
    /*
    for(int i = 0; i < len; i++){
        array[i] = complex_power(array[i], power, result);
    }
    */
}                       //empty

/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){      //empty
  //...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
    //LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
    LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){                                                               //working
    // LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
    LaVectorLongInt PIV = LaVectorLongInt(len);
    LUFactorizeIP(matrix, PIV);
    LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){                                 //empty
    //
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
    //LaGenMatComplex step = LaGenMatComplex

} //empty

/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
    COMPLEX compA;
    generate_scalar(compA, max_rand);
    COMPLEX compB;
    generate_scalar(compB, max_rand);
    int realB;
    generate_scalar(realB, max_rand);
    COMPLEX result;

    cout << "compA = " << compA << endl;
    cout << "compB = " << compB << endl;
    cout << "realB = " << realB << endl;
    cout << endl;

    for(int i = 1; i < 5; i++){                                                 //factorials
        cout << "factorial(" << i << "): " << factorial(i) << endl;
    }

    scalar_addition(compA, compB, result);                                      //addition/subtraction
    cout << "scalar addition: " << result << endl << endl;

    scalar_multiplication(compA, realB, result);                                //multiplication
    cout << "scalar multiplication by scalar: " << result << endl << endl;

    scalar_multiplication(compA, compB, result);
    cout << "scalar multiplication by complex: " << result << endl << endl;

    scalar_division(compA, realB, result);         //division
    cout << "scalar division by scalar: " << result << endl << endl;

    scalar_division(compA, compB, result);
    cout << "scalar division by complex: " << result << endl << endl;

    for(int i = 1; i < 5; i++){
        scalar_powers(compA, i, result);
        cout << "scalar powers - A^" << i << " = " << result << endl;
    }
    cout << endl;

    COMPLEX sum;
    sum.r = 0;
    sum.i = 0;
    for(int i = 0; i < 5; i++){
        cout << "sum(" << i << ") = " << sum << endl;
        scalar_addition(sum, compA);
    }
    cout << "sum = " << sum << endl;

}                                       //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
    LaVectorComplex eigenvalueVec = LaVectorComplex(size);             //initialise eigenstuff
    LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
    LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
    matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
    print_matrix(eigenvalueVec, "eigenvalue vector");               //print eigenstuff
    vec_to_diag(eigenvalueVec, size, eigenvalues);
    print_matrix(eigenvalues, "eigenvalue matrix");
    print_matrix(eigenvectors, "eigenvector matrix");
}             //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
    LaGenMatComplex inverseMatrix;
    inverseMatrix = initialMatrix.copy();
    matrix_inverse(inverseMatrix, size);
    print_matrix(inverseMatrix, "inverse matrix");
}                 //to test
void test_scalar_sum(const int max_rand, const int iterations){
    COMPLEX number, step;
    generate_scalar(number, max_rand);
    step = number;
    for(int i = 0; i < iterations; i++){
        cout << step << endl;
        scalar_addition(number, step);
    }
    cout << number << endl;
}
void test_scalar_product(const int max_rand, const int iterations){
    //...
}
void test_scalar_exponential(const int iterations, const int max_rand){
    COMPLEX number, result;
    generate_scalar(number, max_rand);
    cout << endl << "scalar exponential test no.: " << number << endl << endl;
    scalar_exponential_main(number, iterations, result);
    cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
    //cout << "intial matrix = " << endl << initialMatrix << endl;
}
void test_idenpotent_exponential(){

    // Generate the matrix
    int elements [] = {2, -2, -4, -1, 3, 4, 1, -2, -3};
    COMPLEX comp[9];
    for(int i = 0; i < 9; i++){
        comp[i].r = elements[i];
        comp[i].i = 0;
    }
    LaGenMatComplex initialMatrix = LaGenMatComplex(comp, 3, 3, false );
    cout << "initialMatrix = " << endl << initialMatrix << endl;

    //calculate the exponential
}

/* Main Program */
int main(){
	int matrix_size = 3, max_rand = 9;
    int matrix_volume = matrix_size * matrix_size;

	/* generate the matrix */
    COMPLEX elements[matrix_volume];
    generate_array(elements, matrix_volume, max_rand);
	LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );

    print_matrix(initialMatrix, "initial matrix");

    /* test eigenvalues */
//    test_eigenvalues(initialMatrix, matrix_size);

    /* test scalar manipulation */
//    test_scalar_manipulation(4);

    /* test scalar product */

    /* test scalar exponentials */
//    test_scalar_exponential(5000,40);
//    test_idenpotent_exponential();

    /* test matrix exponentials */
    test_matrix_exponential(initialMatrix, matrix_size);
    /* test inversion */
//    test_inverse(initialMatrix, matrix_size);
}
<commit_msg>testing<commit_after>#include <iostream> //cout
#include <cstdlib>	//rand, sran
#include <string>
#include "complex_matrices.h"
#include <gmc.h> 	//LaGenMatComplex
#include <laslv.h>  //LUFactorizeIP, LaLUInverseIP, etc.
#include <blas3pp.h>
//#include <random>   //random_device, mt19937

using namespace std;

/* Total [13/20] */

int ran(int a, int b){
//    random_device rd;
//    mt19937 gen(rd());
//    uniform_int_distribution<> dist(a, b);
//    return dist(gen);
    return rand() % b;
}

/* Printing [6/9] */
void print_scalar(const COMPLEX scalar){
    cout << scalar << endl;
}                                                 //working
void print_scalar(const COMPLEX scalar, const string name){
    cout << name << ":" << scalar << endl;
}                              //working
void print_array(const COMPLEX array[], int len){
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                                        //working
void print_array(const COMPLEX array[], int len, const string name){
	cout << name << ":" << endl;
    for(int i = 0; i < len; i++){
        cout << array[i] << endl;
    }
}                     //working
void print_matrix(const LaGenMatComplex& matrix){
	cout << matrix << endl;
}                                        //working
void print_matrix(const LaGenMatComplex& matrix, const string name){
	cout << name << ":" << endl << matrix << endl;
}			          //working

/* Number generation [2/2] */
void generate_scalar(COMPLEX& A, const int x){
    A.r = ran(1, x);	//1 to x
    A.i = ran(1, x);
}               //working
void generate_scalar(int number, const int x){
    number = ran(1, x);	//1 to x
}                                                //working
void generate_array(COMPLEX array[], const int len, const int x){
    for(int i = 0; i < len; i++){
        array[i].r = ran(1, x);	//1 to x
        array[i].i = ran(1, x);
	}
}                        //working

/* Matrix conversion [3/3] */
void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){
    for(int i = 0; i < len; i++){
        array[i] = vector(i);
    }
}       //working
void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){
    diag = 0;
    for(int i = 0; i < len; i++){
        diag(i, i) = array[i];
    }
}               //working
void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){
    COMPLEX array[len];
    vec_to_array(vector, len, array);
    array_to_diag(array, len, diag);
}   //working

/* Scalar manipulation [5/8] */
int factorial(int x){
	if(x <= 1){
        return 1;
	}else{
        return x * factorial(x - 1);
	}
}                                                                    //working
void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){
    result.r = A.r + B.r;
    result.i = A.i + B.i;
}              //working
void scalar_addition(COMPLEX& result, const COMPLEX addition){
    result.r += addition.r;
    result.i += addition.i;
}
void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r * B;
    result.i = A.i * B;
}              //to test
void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA * laB;
    result = laResult.toCOMPLEX();
}         //to test
void scalar_product(COMPLEX& total, const COMPLEX& number){
    COMPLEX part;
    part.r = (total.r * number.r) - (total.i * number.i);
    part.i = (total.r * number.i) + (total.i * number.r);
    total = part;
}
void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){
    result.r = A.r / B;
    result.i = A.i / B;
}                    //to test
void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){
    la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double>
    la::complex<double> laB = la::complex<double>(B);
    la::complex<double> laResult = la::complex<double>(result);
    laResult = laA / laB;
    result = laResult.toCOMPLEX();
}               //to test
void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){
    la::complex<double> laResult = la::complex<double>(number);
    la::complex<double> laNumber = la::complex<double>(number);
    for(int i = 1; i < power; i++){
        laResult *= laNumber;
    }
    result = laResult.toCOMPLEX();
}             //to test
void scalar_exponential_main(const COMPLEX& number, const int iterations, COMPLEX& result){
    COMPLEX division, total_division;
    result.r = 1;
    result.i = 0 ;
    for(int step = 1; step <= iterations; step++){   //sum (from 1 to n)
        total_division.r = 1;
        total_division.i = 0;
        for(int i = 1; i <= step; i++){        //    ( num^n / n!)
            scalar_division(number, i, division);
            scalar_product(total_division, division);
        }
        scalar_addition(result, total_division);
    }
}
void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
}         //empty
//COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){
//    COMPLEX result, division, multiplication;
//	if(step <= 1){
//        result.r = 1;
//        return result;
//	}else{
//        scalar_division(number,step,division);
//        scalar_multiplication(division, rec_scalar_exp_step(step-1),  multiplication);
//        return multiplication;
//	}
//}
void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){
    //COMPLEX power;
    //COMPLEX division;
    //result.r = 0;
    //result.i = 0;
    //for(int i = 0; i < iter; i++){
    //    scalar_powers(number, i, power);
    //    scalar_division(power, factorial(i), division);
    //    scalar_addition(result, division, result);
    //}
} //empty

/* array manipulation [0/1] */
void array_powers(COMPLEX array[], const int len, const int power){/**/
    /*
    for(int i = 0; i < len; i++){
        array[i] = complex_power(array[i], power, result);
    }
    */
}                       //empty

/* Matrix manipulation [2/4] */
void diagonal_matrix_powers(){      //empty
  //...
}
void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working
    //LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769
    LaEigSolve(matrix, eigenvalues, eigenvectors);
}
void matrix_inverse(LaGenMatComplex& matrix, int len){                                                               //working
    // LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189
    LaVectorLongInt PIV = LaVectorLongInt(len);
    LUFactorizeIP(matrix, PIV);
    LaLUInverseIP(matrix, PIV);
}
void matrix_exp_step(){                                 //empty
    //
}
void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){
    //LaGenMatComplex step = LaGenMatComplex

} //empty

/* Testing [3/3] */
void test_scalar_manipulation(const int max_rand){
    COMPLEX compA;
    generate_scalar(compA, max_rand);
    COMPLEX compB;
    generate_scalar(compB, max_rand);
    int realB;
    generate_scalar(realB, max_rand);
    COMPLEX result;

    cout << "compA = " << compA << endl;
    cout << "compB = " << compB << endl;
    cout << "realB = " << realB << endl;
    cout << endl;

    for(int i = 1; i < 5; i++){                                                 //factorials
        cout << "factorial(" << i << "): " << factorial(i) << endl;
    }

    scalar_addition(compA, compB, result);                                      //addition/subtraction
    cout << "scalar addition: " << result << endl << endl;

    scalar_multiplication(compA, realB, result);                                //multiplication
    cout << "scalar multiplication by scalar: " << result << endl << endl;

    scalar_multiplication(compA, compB, result);
    cout << "scalar multiplication by complex: " << result << endl << endl;

    scalar_division(compA, realB, result);         //division
    cout << "scalar division by scalar: " << result << endl << endl;

    scalar_division(compA, compB, result);
    cout << "scalar division by complex: " << result << endl << endl;

    for(int i = 1; i < 5; i++){
        scalar_powers(compA, i, result);
        cout << "scalar powers - A^" << i << " = " << result << endl;
    }
    cout << endl;

    COMPLEX sum;
    sum.r = 0;
    sum.i = 0;
    for(int i = 0; i < 5; i++){
        cout << "sum(" << i << ") = " << sum << endl;
        scalar_addition(sum, compA);
    }
    cout << "sum = " << sum << endl;

}                                       //to test
void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){
    LaVectorComplex eigenvalueVec = LaVectorComplex(size);             //initialise eigenstuff
    LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size);
    LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size);
    matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff
    print_matrix(eigenvalueVec, "eigenvalue vector");               //print eigenstuff
    vec_to_diag(eigenvalueVec, size, eigenvalues);
    print_matrix(eigenvalues, "eigenvalue matrix");
    print_matrix(eigenvectors, "eigenvector matrix");
}             //to test
void test_inverse(const LaGenMatComplex& initialMatrix, const int size){
    LaGenMatComplex inverseMatrix;
    inverseMatrix = initialMatrix.copy();
    matrix_inverse(inverseMatrix, size);
    print_matrix(inverseMatrix, "inverse matrix");
}                 //to test
void test_scalar_sum(const int max_rand, const int iterations){
    COMPLEX number, step;
    generate_scalar(number, max_rand);
    step = number;
    for(int i = 0; i < iterations; i++){
        cout << step << endl;
        scalar_addition(number, step);
    }
    cout << number << endl;
}
void test_scalar_product(const int max_rand, const int iterations){
    //...
}
void test_scalar_exponential(const int iterations, const int max_rand){
    COMPLEX number, result;
    generate_scalar(number, max_rand);
    cout << endl << "scalar exponential test no.: " << number << endl << endl;
    scalar_exponential_main(number, iterations, result);
    cout << "e^" << number << " = " << result << endl;
}
void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){
    test_eigenvalues(initialMatrix, size);
}
void test_idenpotent_exponential(){

    // Generate the matrix
    int elements [] = {2, -2, -4, -1, 3, 4, 1, -2, -3};
    COMPLEX comp[9];
    for(int i = 0; i < 9; i++){
        comp[i].r = elements[i];
        comp[i].i = 0;
    }
    LaGenMatComplex initialMatrix = LaGenMatComplex(comp, 3, 3, false );
    cout << "initialMatrix = " << endl << initialMatrix << endl;

    //calculate the exponential
}

/* Main Program */
int main(){
	int matrix_size = 3, max_rand = 9;
    int matrix_volume = matrix_size * matrix_size;

	/* generate the matrix */
    COMPLEX elements[matrix_volume];
    generate_array(elements, matrix_volume, max_rand);
	LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false );

    print_matrix(initialMatrix, "initial matrix");

    /* test eigenvalues */
//    test_eigenvalues(initialMatrix, matrix_size);

    /* test scalar manipulation */
//    test_scalar_manipulation(4);

    /* test scalar product */

    /* test scalar exponentials */
//    test_scalar_exponential(5000,40);
//    test_idenpotent_exponential();

    /* test matrix exponentials */
    test_matrix_exponential(initialMatrix, matrix_size);

    /* test inversion */
//    test_inverse(initialMatrix, matrix_size);
}
<|endoftext|>


<commit_before>/**
 * \file sysexp.hpp
 *
 * \brief Driver for performing system experiments
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright (C) 2012       Marco Guazzone
 *                          [Distributed Computing System (DCS) Group,
 *                           Computer Science Institute,
 *                           Department of Science and Technological Innovation,
 *                           University of Piemonte Orientale,
 *                           Alessandria (Italy)]
 *
 * This file is part of dcsxx-testbed.
 *
 * dcsxx-testbed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dcsxx-testbed 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with dcsxx-testbed.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <dcs/cli.hpp>
#include <dcs/logging.hpp>
#include <dcs/math/traits/float.hpp>
#include <dcs/testbed/application.hpp>
#include <dcs/testbed/application_managers.hpp>
#include <dcs/testbed/base_application.hpp>
#include <dcs/testbed/system_experiment.hpp>
#include <dcs/testbed/system_identification_strategies.hpp>
//#include <dcs/testbed/system_managers.hpp>
#include <dcs/testbed/traits.hpp>
#include <dcs/testbed/virtual_machine_managers.hpp>
#include <dcs/testbed/virtual_machines.hpp>
#include <dcs/testbed/workload_category.hpp>
#include <dcs/testbed/workload_drivers.hpp>
#include <dcs/testbed/workload_generator_category.hpp>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <stdexcept>
#include <vector>

namespace detail { namespace /*<unnamed>*/ {

//enum aggregation_category
//{
//	mean_aggregation
//};

const dcs::testbed::workload_category default_workload(dcs::testbed::olio_workload);
const dcs::testbed::workload_generator_category default_workload_driver(dcs::testbed::rain_workload_generator);
const ::std::string default_workload_driver_rain_path("/usr/local/opt/rain-workload-toolkit");
const ::std::string default_out_dat_file("./sysmgt-out.dat");
const double default_sampling_time(10);
const double default_ewma_smooth_factor(0.9);

void usage(char const* progname)
{
	::std::cerr << "Usage: " << progname << " [options]" << ::std::endl
				<< " --help" << ::std::endl
				<< "   Show this message." << ::std::endl
				<< " --out-dat-file <file path>" << ::std::endl
				<< "   The path to the output data file." << ::std::endl
				<< "   [default: '" << default_out_dat_file << "']." << ::std::endl
				<< " --ts <time in secs>" << ::std::endl
				<< "   Sampling time (in seconds)." << ::std::endl
				<< "   [default: " << default_sampling_time << "]." << ::std::endl
				<< " --verbose" << ::std::endl
				<< "   Show verbose messages." << ::std::endl
				<< "   [default: disabled]." << ::std::endl
				<< " --vm-uri <URI>" << ::std::endl
				<< "   The VM URI to connect." << ::std::endl
				<< "   Repeat this option as many times as is the number of your VMs."
				<< " --wkl <name>" << ::std::endl
				<< "   The workload to generate. Possible values are: 'olio', 'rubis'." << ::std::endl
				<< "   [default: '" << default_workload << "']." << ::std::endl
				<< " --wkl-driver <name>" << ::std::endl
				<< "   The workload driver to use. Possible values are: 'rain'." << ::std::endl
				<< "   [default: '" << default_workload_driver << "']." << ::std::endl
				<< " --wkl-driver-rain-path <name>" << ::std::endl
				<< "   The full path to the RAIN workload driver." << ::std::endl
				<< "   [default: '" << default_workload_driver_rain_path << "']." << ::std::endl
				<< ::std::endl;
}

template <typename RealT>
struct rt_slo_checker
{
	rt_slo_checker(RealT max_val, RealT rel_tol=0.05)
	: max_val_(max_val),
	  check_val_(max_val_*(1+rel_tol))
	{
	}

	bool operator()(RealT val)
	{
		return ::dcs::math::float_traits<RealT>::approximately_less_equal(val, check_val_);
	}

	private: RealT max_val_;
	private: RealT check_val_;
};

}} // Namespace detail::<unnamed>

int main(int argc, char *argv[])
{
	namespace testbed = ::dcs::testbed;

	typedef double real_type;
	typedef unsigned int uint_type;
	typedef testbed::traits<real_type,uint_type> traits_type;

	bool help(false);
	std::string out_dat_file;
	real_type ts;
	bool verbose(false);
	testbed::workload_category wkl;
	testbed::workload_generator_category wkl_driver;
	std::string wkl_driver_rain_path;
	std::vector<std::string> vm_uris;

	// Parse command line options
	try
	{
		help = dcs::cli::simple::get_option(argv, argv+argc, "--help");
		out_dat_file = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--out-dat-file", detail::default_out_dat_file);
		ts = dcs::cli::simple::get_option<real_type>(argv, argv+argc, "--ts", detail::default_sampling_time);
		verbose = dcs::cli::simple::get_option(argv, argv+argc, "--verbose");
		vm_uris = dcs::cli::simple::get_options<std::string>(argv, argv+argc, "--vm-uri");
		wkl = dcs::cli::simple::get_option<testbed::workload_category>(argv, argv+argc, "--wkl", detail::default_workload);
		wkl_driver = dcs::cli::simple::get_option<testbed::workload_generator_category>(argv, argv+argc, "--wkl-driver", detail::default_workload_driver);
		wkl_driver_rain_path = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--wkl-driver-rain-path", detail::default_workload_driver_rain_path);
	}
	catch (std::exception const& e)
	{
		std::ostringstream oss;
		oss << "Error while parsing command-line options: " << e.what();
		dcs::log_error(DCS_LOGGING_AT, oss.str());

		detail::usage(argv[0]);
		std::abort();
		return EXIT_FAILURE;
	}

	if (help)
	{
		detail::usage(argv[0]);
		return EXIT_SUCCESS;
	}

	int ret(0);

	if (verbose)
	{
		std::ostringstream oss;

		for (std::size_t i = 0; i < vm_uris.size(); ++i)
		{
			if (i > 0)
			{
				oss << ", ";
			}
			oss << "VM URI: " << vm_uris[i];
		}
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Output data file: " << out_dat_file;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Sampling time: " << ts;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Workload: " << wkl;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Workload driver: " << wkl_driver;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Workload driver RAIN path: " << wkl_driver_rain_path;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");
	}

	typedef testbed::base_virtual_machine<traits_type> vm_type;
	typedef boost::shared_ptr<vm_type> vm_pointer;
	typedef vm_type::identifier_type vm_identifier_type;
	typedef testbed::base_virtual_machine_manager<traits_type> vmm_type;
	typedef boost::shared_ptr<vmm_type> vmm_pointer;
	typedef vmm_type::identifier_type vmm_identifier_type;
	typedef testbed::base_application<traits_type> app_type;
	typedef boost::shared_ptr<app_type> app_pointer;
	typedef testbed::base_application_manager<traits_type> app_manager_type;
	typedef boost::shared_ptr<app_manager_type> app_manager_pointer;
	typedef testbed::base_workload_driver<traits_type> app_driver_type;
	typedef boost::shared_ptr<app_driver_type> app_driver_pointer;
	typedef testbed::base_arx_system_identification_strategy<traits_type> sysid_strategy_type;
	typedef boost::shared_ptr<sysid_strategy_type> sysid_strategy_pointer;

	try
	{
		const std::size_t nt(vm_uris.size()); // Number of tiers

		testbed::system_experiment<traits_type> sys_exp;

		// Setup application experiment
		// - Setup application (and VMs)
		std::map<vmm_identifier_type,vmm_pointer> vmm_map;
		std::vector<vm_pointer> vms(nt);
		std::vector<std::string>::const_iterator uri_end_it(vm_uris.end());
		for (std::vector<std::string>::const_iterator it = vm_uris.begin();
			 it != uri_end_it;
			 ++it)
		{
			std::string const& uri(*it);

			vmm_pointer p_vmm;
			if (!vmm_map.count(uri) > 0)
			{
				p_vmm = boost::make_shared< testbed::libvirt::virtual_machine_manager<traits_type> >(uri);
				vmm_map[uri] = p_vmm;
			}
			else
			{
				p_vmm = vmm_map.at(uri);
			}

			vm_pointer p_vm(p_vmm->vm(uri));
			vms.push_back(p_vm);
		}
		app_pointer p_app = boost::make_shared< testbed::application<traits_type> >(vms.begin(), vms.end());
		p_app->slo(testbed::response_time_application_performance, detail::rt_slo_checker<real_type>(0.2870));

		// - Setup workload driver
		app_driver_pointer p_drv;
		switch (wkl_driver)
		{
			case testbed::rain_workload_generator:
				p_drv = boost::make_shared< testbed::rain::workload_driver<traits_type> >(wkl, wkl_driver_rain_path);
				break;
		}

		// - Setup application manager
		app_manager_pointer p_mgr;
		//p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >();
		{
			sysid_strategy_pointer p_sysid_alg = boost::make_shared< testbed::rls_ff_arx_miso_proxy<traits_type> >(2, 2, 1, 1, nt, 0.98);
			testbed::lqry_application_manager<traits_type> lqry_mgr;
			lqry_mgr.sysid_strategy(p_sysid_alg);
			lqry_mgr.target_value(testbed::response_time_application_performance, 0.1034);

			p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >(lqry_mgr);
			p_mgr->sampling_time(static_cast<uint_type>(ts));
			p_mgr->control_time(3*p_mgr->sampling_time());
		}

		// Add to main experiment
		sys_exp.add_app(p_app, p_drv, p_mgr);

		//sys_exp.logger(...);
		//sys_exp.output_data_file(out_dat_file);

		sys_exp.run();
	}
	catch (std::exception const& e)
	{
		ret = 1;
		dcs::log_error(DCS_LOGGING_AT, e.what());
	}
	catch (...)
	{
		ret = 1;
		dcs::log_error(DCS_LOGGING_AT, "Unknown error");
	}

	return ret;
}
<commit_msg>(bug-fix:minor) Forgot to set the response time sensor.<commit_after>/**
 * \file sysexp.hpp
 *
 * \brief Driver for performing system experiments
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright (C) 2012       Marco Guazzone
 *                          [Distributed Computing System (DCS) Group,
 *                           Computer Science Institute,
 *                           Department of Science and Technological Innovation,
 *                           University of Piemonte Orientale,
 *                           Alessandria (Italy)]
 *
 * This file is part of dcsxx-testbed.
 *
 * dcsxx-testbed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dcsxx-testbed 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with dcsxx-testbed.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <dcs/cli.hpp>
#include <dcs/logging.hpp>
#include <dcs/math/traits/float.hpp>
#include <dcs/testbed/application.hpp>
#include <dcs/testbed/application_managers.hpp>
#include <dcs/testbed/base_application.hpp>
#include <dcs/testbed/system_experiment.hpp>
#include <dcs/testbed/system_identification_strategies.hpp>
//#include <dcs/testbed/system_managers.hpp>
#include <dcs/testbed/traits.hpp>
#include <dcs/testbed/virtual_machine_managers.hpp>
#include <dcs/testbed/virtual_machines.hpp>
#include <dcs/testbed/workload_category.hpp>
#include <dcs/testbed/workload_drivers.hpp>
#include <dcs/testbed/workload_generator_category.hpp>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <stdexcept>
#include <vector>

namespace detail { namespace /*<unnamed>*/ {

//enum aggregation_category
//{
//	mean_aggregation
//};

const dcs::testbed::workload_category default_workload(dcs::testbed::olio_workload);
const dcs::testbed::workload_generator_category default_workload_driver(dcs::testbed::rain_workload_generator);
const ::std::string default_workload_driver_rain_path("/usr/local/opt/rain-workload-toolkit");
const ::std::string default_out_dat_file("./sysmgt-out.dat");
const double default_sampling_time(10);
const double default_ewma_smooth_factor(0.9);

void usage(char const* progname)
{
	::std::cerr << "Usage: " << progname << " [options]" << ::std::endl
				<< " --help" << ::std::endl
				<< "   Show this message." << ::std::endl
				<< " --out-dat-file <file path>" << ::std::endl
				<< "   The path to the output data file." << ::std::endl
				<< "   [default: '" << default_out_dat_file << "']." << ::std::endl
				<< " --ts <time in secs>" << ::std::endl
				<< "   Sampling time (in seconds)." << ::std::endl
				<< "   [default: " << default_sampling_time << "]." << ::std::endl
				<< " --verbose" << ::std::endl
				<< "   Show verbose messages." << ::std::endl
				<< "   [default: disabled]." << ::std::endl
				<< " --vm-uri <URI>" << ::std::endl
				<< "   The VM URI to connect." << ::std::endl
				<< "   Repeat this option as many times as is the number of your VMs."
				<< " --wkl <name>" << ::std::endl
				<< "   The workload to generate. Possible values are: 'olio', 'rubis'." << ::std::endl
				<< "   [default: '" << default_workload << "']." << ::std::endl
				<< " --wkl-driver <name>" << ::std::endl
				<< "   The workload driver to use. Possible values are: 'rain'." << ::std::endl
				<< "   [default: '" << default_workload_driver << "']." << ::std::endl
				<< " --wkl-driver-rain-path <name>" << ::std::endl
				<< "   The full path to the RAIN workload driver." << ::std::endl
				<< "   [default: '" << default_workload_driver_rain_path << "']." << ::std::endl
				<< ::std::endl;
}

template <typename RealT>
struct rt_slo_checker
{
	rt_slo_checker(RealT max_val, RealT rel_tol=0.05)
	: max_val_(max_val),
	  check_val_(max_val_*(1+rel_tol))
	{
	}

	bool operator()(RealT val)
	{
		return ::dcs::math::float_traits<RealT>::approximately_less_equal(val, check_val_);
	}

	private: RealT max_val_;
	private: RealT check_val_;
};

}} // Namespace detail::<unnamed>

int main(int argc, char *argv[])
{
	namespace testbed = ::dcs::testbed;

	typedef double real_type;
	typedef unsigned int uint_type;
	typedef testbed::traits<real_type,uint_type> traits_type;

	bool help(false);
	std::string out_dat_file;
	real_type ts;
	bool verbose(false);
	testbed::workload_category wkl;
	testbed::workload_generator_category wkl_driver;
	std::string wkl_driver_rain_path;
	std::vector<std::string> vm_uris;

	// Parse command line options
	try
	{
		help = dcs::cli::simple::get_option(argv, argv+argc, "--help");
		out_dat_file = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--out-dat-file", detail::default_out_dat_file);
		ts = dcs::cli::simple::get_option<real_type>(argv, argv+argc, "--ts", detail::default_sampling_time);
		verbose = dcs::cli::simple::get_option(argv, argv+argc, "--verbose");
		vm_uris = dcs::cli::simple::get_options<std::string>(argv, argv+argc, "--vm-uri");
		wkl = dcs::cli::simple::get_option<testbed::workload_category>(argv, argv+argc, "--wkl", detail::default_workload);
		wkl_driver = dcs::cli::simple::get_option<testbed::workload_generator_category>(argv, argv+argc, "--wkl-driver", detail::default_workload_driver);
		wkl_driver_rain_path = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--wkl-driver-rain-path", detail::default_workload_driver_rain_path);
	}
	catch (std::exception const& e)
	{
		std::ostringstream oss;
		oss << "Error while parsing command-line options: " << e.what();
		dcs::log_error(DCS_LOGGING_AT, oss.str());

		detail::usage(argv[0]);
		std::abort();
		return EXIT_FAILURE;
	}

	if (help)
	{
		detail::usage(argv[0]);
		return EXIT_SUCCESS;
	}

	int ret(0);

	if (verbose)
	{
		std::ostringstream oss;

		for (std::size_t i = 0; i < vm_uris.size(); ++i)
		{
			if (i > 0)
			{
				oss << ", ";
			}
			oss << "VM URI: " << vm_uris[i];
		}
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Output data file: " << out_dat_file;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Sampling time: " << ts;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Workload: " << wkl;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Workload driver: " << wkl_driver;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");

		oss << "Workload driver RAIN path: " << wkl_driver_rain_path;
		dcs::log_info(DCS_LOGGING_AT, oss.str());
		oss.str("");
	}

	typedef testbed::base_virtual_machine<traits_type> vm_type;
	typedef boost::shared_ptr<vm_type> vm_pointer;
	typedef vm_type::identifier_type vm_identifier_type;
	typedef testbed::base_virtual_machine_manager<traits_type> vmm_type;
	typedef boost::shared_ptr<vmm_type> vmm_pointer;
	typedef vmm_type::identifier_type vmm_identifier_type;
	typedef testbed::base_application<traits_type> app_type;
	typedef boost::shared_ptr<app_type> app_pointer;
	typedef testbed::base_application_manager<traits_type> app_manager_type;
	typedef boost::shared_ptr<app_manager_type> app_manager_pointer;
	typedef testbed::base_workload_driver<traits_type> app_driver_type;
	typedef boost::shared_ptr<app_driver_type> app_driver_pointer;
	typedef testbed::base_arx_system_identification_strategy<traits_type> sysid_strategy_type;
	typedef boost::shared_ptr<sysid_strategy_type> sysid_strategy_pointer;

	try
	{
		const std::size_t nt(vm_uris.size()); // Number of tiers

		testbed::system_experiment<traits_type> sys_exp;

		// Setup application experiment
		// - Setup application (and VMs)
		std::map<vmm_identifier_type,vmm_pointer> vmm_map;
		std::vector<vm_pointer> vms(nt);
		std::vector<std::string>::const_iterator uri_end_it(vm_uris.end());
		for (std::vector<std::string>::const_iterator it = vm_uris.begin();
			 it != uri_end_it;
			 ++it)
		{
			std::string const& uri(*it);

			vmm_pointer p_vmm;
			if (!vmm_map.count(uri) > 0)
			{
				p_vmm = boost::make_shared< testbed::libvirt::virtual_machine_manager<traits_type> >(uri);
				vmm_map[uri] = p_vmm;
			}
			else
			{
				p_vmm = vmm_map.at(uri);
			}

			vm_pointer p_vm(p_vmm->vm(uri));
			vms.push_back(p_vm);
		}
		app_pointer p_app = boost::make_shared< testbed::application<traits_type> >(vms.begin(), vms.end());
		p_app->slo(testbed::response_time_application_performance, detail::rt_slo_checker<real_type>(0.2870));

		// - Setup workload driver
		app_driver_pointer p_drv;
		switch (wkl_driver)
		{
			case testbed::rain_workload_generator:
				{
					boost::shared_ptr< testbed::rain::workload_driver<traits_type> > p_drv_impl = boost::make_shared< testbed::rain::workload_driver<traits_type> >(wkl, wkl_driver_rain_path);
					p_app->register_sensor(testbed::response_time_application_performance, p_drv_impl->sensor(testbed::response_time_application_performance));
					//p_drv = boost::make_shared< testbed::rain::workload_driver<traits_type> >(drv_impl);
					p_drv = p_drv_impl;
				}
				break;
		}

		// - Setup application manager
		app_manager_pointer p_mgr;
		//p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >();
		{
			sysid_strategy_pointer p_sysid_alg = boost::make_shared< testbed::rls_ff_arx_miso_proxy<traits_type> >(2, 2, 1, 1, nt, 0.98);
			testbed::lqry_application_manager<traits_type> lqry_mgr;
			lqry_mgr.sysid_strategy(p_sysid_alg);
			lqry_mgr.target_value(testbed::response_time_application_performance, 0.1034);

			p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >(lqry_mgr);
			p_mgr->sampling_time(static_cast<uint_type>(ts));
			p_mgr->control_time(3*p_mgr->sampling_time());
		}

		// Add to main experiment
		sys_exp.add_app(p_app, p_drv, p_mgr);

		//sys_exp.logger(...);
		//sys_exp.output_data_file(out_dat_file);

		sys_exp.run();
	}
	catch (std::exception const& e)
	{
		ret = 1;
		dcs::log_error(DCS_LOGGING_AT, e.what());
	}
	catch (...)
	{
		ret = 1;
		dcs::log_error(DCS_LOGGING_AT, "Unknown error");
	}

	return ret;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * c7a/core/stage_builder.hpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_CORE_STAGE_BUILDER_HEADER
#define C7A_CORE_STAGE_BUILDER_HEADER

#include <c7a/api/dia_base.hpp>
#include <c7a/common/logger.hpp>

#include <stack>
#include <string>
#include <utility>
#include <algorithm>
#include <set>
#include <vector>

namespace c7a {
namespace core {

class Stage
{
public:
    explicit Stage(DIABase* node) : node_(node) {
        LOG << "CREATING stage" << node_->ToString() << "node" << node_;
    }
    void Run() {
        LOG << "RUNNING stage " << node_->ToString() << "node" << node_;
        node_->execute();
    }

private:

    static const bool debug = false;
    DIABase* node_;
};

class StageBuilder
{
public:
    void FindStages(DIABase* action, std::vector<Stage>& stages_result) {
        LOG1 << "FINDING stages:";
        std::set<const DIABase*> stages_found;
        // Do a reverse DFS and find all stages
        std::stack<DIABase*> dia_stack;
        dia_stack.push(action);
        stages_found.insert(action);
        while (!dia_stack.empty()) {
            DIABase* curr = dia_stack.top();
            dia_stack.pop();
            stages_result.emplace_back(Stage(curr));
            const std::vector<DIABase*> parents = curr->get_parents();
            for (DIABase* p : parents) {
                // if p is not a nullpointer and p is not cached mark it and save stage
                if (p && (stages_found.find(p) == stages_found.end()) && p->state() != CACHED) {
                    dia_stack.push(p);
                    stages_found.insert(p);
                }
                else LOG1 << "OMG NULLPTR";

    }

    void RunScope(DIABase* action) {
        std::vector<Stage> result;
        FindStages(action, result);
        for (auto s : result)
        {
            s.Run();
        }
    }
};
} // namespace core
} // namespace c7a

#endif // !C7A_CORE_STAGE_BUILDER_HEADER

/******************************************************************************/
<commit_msg>Actually commit fix for merge failure.<commit_after>/*******************************************************************************
 * c7a/core/stage_builder.hpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_CORE_STAGE_BUILDER_HEADER
#define C7A_CORE_STAGE_BUILDER_HEADER

#include <c7a/api/dia_base.hpp>
#include <c7a/common/logger.hpp>

#include <stack>
#include <string>
#include <utility>
#include <algorithm>
#include <set>
#include <vector>

namespace c7a {
namespace core {

class Stage
{
public:
    explicit Stage(DIABase* node) : node_(node) {
        LOG << "CREATING stage" << node_->ToString() << "node" << node_;
    }
    void Run() {
        LOG << "RUNNING stage " << node_->ToString() << "node" << node_;
        node_->execute();
    }

private:

    static const bool debug = false;
    DIABase* node_;
};

class StageBuilder
{
public:
    void FindStages(DIABase* action, std::vector<Stage>& stages_result) {
        LOG1 << "FINDING stages:";
        std::set<const DIABase*> stages_found;
        // Do a reverse DFS and find all stages
        std::stack<DIABase*> dia_stack;
        dia_stack.push(action);
        stages_found.insert(action);
        while (!dia_stack.empty()) {
            DIABase* curr = dia_stack.top();
            dia_stack.pop();
            stages_result.emplace_back(Stage(curr));
            const std::vector<DIABase*> parents = curr->get_parents();
            for (DIABase* p : parents) {
                // if p is not a nullpointer and p is not cached mark it and save stage
                if (p && (stages_found.find(p) == stages_found.end()) && p->state() != CACHED) {
                    dia_stack.push(p);
                    stages_found.insert(p);
                }
                else LOG1 << "OMG NULLPTR";
	    }
	}
    }

    void RunScope(DIABase* action) {
        std::vector<Stage> result;
        FindStages(action, result);
        for (auto s : result)
        {
            s.Run();
        }
    }
};
} // namespace core
} // namespace c7a

#endif // !C7A_CORE_STAGE_BUILDER_HEADER

/******************************************************************************/
<|endoftext|>