<commit_before>/*
 *  Copyright (C) 2004 Steve Harris, Uwe Koloska
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as
 *  published by the Free Software Foundation; either version 2.1 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  $Id$
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>

#include "lo/lo.h"
using namespace std;

int done = 0;

void error(int num, const char *m, const char *path);

int generic_handler(const char *path, const char *types, lo_arg ** argv,
                    int argc, void *data, void *user_data);

int foo_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data);

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data);

int main()
{
    /* make address for multicast ip
     * pick a port number for you by passing NULL as the last argument */

    lo_address t = lo_address_new("239.255.0.1", "7770");
    // lo_server multi = lo_server_new_multicast("drone", "7771", error);
    /* start a new server on port 7770 */
    lo_server_thread st = lo_server_thread_new_multicast("239.255.0.1", "7770", error);

    /* add method that will match any path and args */
    lo_server_thread_add_method(st, NULL, NULL, generic_handler, NULL);

    /* add method that will match the path /foo/bar, with two numbers, coerced
     * to float and int */
    lo_server_thread_add_method(st, "/foo/bar", "fi", foo_handler, NULL);

    /* add method that will match the path /quit with no args */
    lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL);

    lo_server_thread_start(st);

    while (!done) {
#ifdef WIN32
        Sleep(1);
#else
        usleep(1000000);
#endif
        lo_timetag now;
        lo_timetag_now(&now);
        cerr << now.sec << endl;
        lo_send(t, "/foo/bar", "ff", 0.12345f, 0.987653f);
        // lo_send_from(t, st, now, "/foo/bar", "ff", 0.12345678f, 23.0f);
    }

    lo_server_thread_free(st);

    return 0;
}

void error(int num, const char *msg, const char *path)
{
    printf("liblo server error %d in path %s: %s\n", num, path, msg);
    fflush(stdout);
}

/* catch any incoming messages and display them. returning 1 means that the
 * message has not been fully handled and the server should try other methods */
int generic_handler(const char *path, const char *types, lo_arg ** argv,
                    int argc, void *data, void *user_data)
{
    int i;

    printf("path: <%s>\n", path);
    for (i = 0; i < argc; i++) {
        printf("arg %d '%c' ", i, types[i]);
        lo_arg_pp((lo_type)types[i], argv[i]);
        printf("\n");
    }
    printf("\n");
    fflush(stdout);

    return 1;
}

int foo_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data)
{
    /* example showing pulling the argument values out of the argv array */
    printf("%s <- f:%f, i:%d\n\n", path, argv[0]->f, argv[1]->i);
    fflush(stdout);

    return 0;
}

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data)
{
    done = 1;
    printf("quiting\n\n");
    fflush(stdout);

    return 0;
}

/* vi:set ts=8 sts=4 sw=4: */
<commit_msg>Pinging<commit_after>/*
 *  Copyright (C) 2004 Steve Harris, Uwe Koloska
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as
 *  published by the Free Software Foundation; either version 2.1 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  $Id$
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <vector>

#include "lo/lo.h"
using namespace std;

int done = 0;

struct member {
    int pid;
    char hostname[128];
};

vector<member> members;

void error(int num, const char *m, const char *path);

int ping_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data);

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data);

int main()
{
    /* make address for multicast ip
     * pick a port number for you by passing NULL as the last argument */

    lo_address t = lo_address_new("239.255.0.1", "7770");
    // lo_server multi = lo_server_new_multicast("drone", "7771", error);
    /* start a new server on port 7770 */
    lo_server_thread st = lo_server_thread_new_multicast("239.255.0.1", "7770", error);

    /* add method that will match the path /foo/bar, with two numbers, coerced
     * to float and int */
    lo_server_thread_add_method(st, "/ping", "fi", ping_handler, NULL);

    /* add method that will match the path /quit with no args */
    lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL);

    lo_server_thread_start(st);

    while (!done) {
#ifdef WIN32
        Sleep(1);
#else
        usleep(1000000);
#endif
        char hostname[128] = "";

        gethostname(hostname, sizeof(hostname));

        int pid = getpid();
        cerr << "pid: " << pid << " || hostname : " << hostname << endl;
        lo_send(t, "/ping", "is", pid, hostname);
        // lo_send_from(t, st, now, "/foo/bar", "ff", 0.12345678f, 23.0f);
    }

    lo_server_thread_free(st);

    return 0;
}

void error(int num, const char *msg, const char *path)
{
    printf("liblo server error %d in path %s: %s\n", num, path, msg);
    fflush(stdout);
}

/* catch any incoming messages and display them. returning 1 means that the
 * message has not been fully handled and the server should try other methods */
int ping_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data)
{
    cerr << "PID: " << argv[0]->i << " || path : " << argv[1]->s << endl;
    /* example showing pulling the argument values out of the argv array */
    printf("%s <- f:%f, i:%d\n\n", path, argv[0]->f, argv[1]->i);
    fflush(stdout);

    return 0;
}

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data)
{
    done = 1;
    printf("quiting\n\n");
    fflush(stdout);

    return 0;
}

/* vi:set ts=8 sts=4 sw=4: */
<|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     main.cpp
 * @author   Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
 * @version  dev
 * @date     February, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Ruben Dörfel. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief     Test for fitHpi function in inverse library.
 *
 */

///=============================================================================================================
// INCLUDES
//=============================================================================================================

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

#include <fiff/fiff.h>
#include <fiff/fiff_info.h>
#include <fiff/fiff_dig_point_set.h>
#include <fiff/fiff_cov.h>

#include <inverse/hpiFit/hpifit.h>
#include <inverse/hpiFit/hpifitdata.h>

#include <utils/ioutils.h>
#include <utils/generics/applicationlogger.h>

#include <fwd/fwd_coil_set.h>

#include <Eigen/Dense>
#include <Eigen/Geometry>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QDebug>
#include <QQuaternion>
#include <QtTest>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace INVERSELIB;
using namespace Eigen;
//=============================================================================================================
/**
 * DECLARE CLASS TestFiffRFR
 *
 * @brief The TestFitHPI class provides hpi fit verifivcation tests
 *
 */
class TestFitHPI: public QObject
{
    Q_OBJECT

public:
    TestFitHPI();

private slots:
    void initTestCase();
    void compareTranslation();
    void compareRotation();
    void compareTime();
    void cleanupTestCase();

private:
    double errorTrans = 0.0003;
    double errorQuat = 0.002;
    double errorTime = 0.00000001;
    MatrixXd ref_pos;
    MatrixXd hpi_pos;
};

//=============================================================================================================

TestFitHPI::TestFitHPI()
{
}

//=============================================================================================================

void storeHeadPosition(float time, const Eigen::Matrix<float, 4,4, Eigen::DontAlign>& devHeadT, MatrixXd& position, const VectorXd& vGoF, const QVector<double>& vError)
{
    // Write quaternions and time in position matrix. Format is the same like MaxFilter's .pos files.
    Matrix3f rot = devHeadT.block(0,0,3,3);

    double error = std::accumulate(vError.begin(), vError.end(), .0) / vError.size();     // HPI estimation Error
    Eigen::Quaternionf quatHPI(rot);

    //qDebug() << "quatHPI.x() " << "quatHPI.y() " << "quatHPI.y() " << "trans x " << "trans y " << "trans z " << std::endl;
    //qDebug() << quatHPI.x() << quatHPI.y() << quatHPI.z() << info->dev_head_t.trans(0,3) << info->dev_head_t.trans(1,3) << info->dev_head_t.trans(2,3) << std::endl;

    float x = quatHPI.x();
    float y = quatHPI.y();
    float z = quatHPI.z();
    position.conservativeResize(position.rows()+1, 10);
    position(position.rows()-1,0) = time;
    position(position.rows()-1,1) = x;
    position(position.rows()-1,2) = y;
    position(position.rows()-1,3) = z;
    position(position.rows()-1,4) = devHeadT(0,3);
    position(position.rows()-1,5) = devHeadT(1,3);
    position(position.rows()-1,6) = devHeadT(2,3);
    position(position.rows()-1,7) = vGoF.mean();
    position(position.rows()-1,8) = error;
    position(position.rows()-1,9) = 0;
}

void TestFitHPI::initTestCase()
{
    qInstallMessageHandler(UTILSLIB::ApplicationLogger::customLogWriter);
    qInfo() << "Error Translation" << errorTrans;
    qInfo() << "Error Quaternion" << errorQuat;
    QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");

    // Make sure test folder exists
    QFileInfo t_fileInInfo(t_fileIn);
    QDir().mkdir(t_fileInInfo.path());

    printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read Raw and HPI fit  >>>>>>>>>>>>>>>>>>>>>>>>>\n");

    // Setup for reading the raw data
    FiffRawData raw;
    raw = FiffRawData(t_fileIn);
    QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FIFFLIB::FiffInfo>(new FiffInfo(raw.info));

    // Only filter MEG channels
    RowVectorXi picks = raw.info.pick_types(true, false, false);
    RowVectorXd cals;

    // Set up the reading parameters
    fiff_int_t from;
    fiff_int_t to;
    fiff_int_t first = raw.first_samp;
    fiff_int_t last = raw.last_samp;
    MatrixXd matData, times;

    float quantum_sec = 0.2f;   //read and write in 200 ms junks
    fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);

    // Read Quaternion File from maxfilter
    UTILSLIB::IOUtils::read_eigen_matrix(ref_pos, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_hpiFit_pos.txt");

    // Setup informations for HPI fit
    QVector<int> vFreqs {166,154,161,158};
    QVector<double> vError;
    VectorXd vGoF;
    FiffDigPointSet fittedPointSet;
    Eigen::MatrixXd matProjectors = Eigen::MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());
    QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug";
    bool bDoDebug = true;

    for(int i = 0; i < ref_pos.rows(); i++) {
        from = first + ref_pos(i,0)*pFiffInfo->sfreq;
        to = from + quantum;
        if (to > last) {
            to = last;
        }
        qInfo()  << "Reading...";
        if(!raw.read_raw_segment(matData, times, from, to)) {
            qWarning("error during read_raw_segment\n");
        }

        qInfo()  << "HPI-Fit...";
        HPIFit::fitHPI(matData,
                       matProjectors,
                       pFiffInfo->dev_head_t,
                       vFreqs,
                       vError,
                       vGoF,
                       fittedPointSet,
                       pFiffInfo,
                       bDoDebug = 0,
                       sHPIResourceDir);
        qInfo() << "[done]\n";
        storeHeadPosition(ref_pos(i,0), pFiffInfo->dev_head_t.trans, hpi_pos, vGoF, vError);
    }
    // For debug: position file for HPIFit
    UTILSLIB::IOUtils::write_eigen_matrix(hpi_pos, QCoreApplication::applicationDirPath() + "/MNE-sample-data/hpi_pos.txt");
}

//=============================================================================================================

void TestFitHPI::compareTranslation()
{
    MatrixXd diff = MatrixXd::Zero(ref_pos.rows(),3);
    RowVector3d diff_trans;
    diff_trans(0) = (ref_pos.col(4)-hpi_pos.col(4)).mean();
    diff_trans(1) = (ref_pos.col(5)-hpi_pos.col(5)).mean();
    diff_trans(2) = (ref_pos.col(6)-hpi_pos.col(6)).mean();
    qDebug() << "errorTrans x: " << std::abs(diff_trans(0));
    qDebug() << "errorTrans y: " << std::abs(diff_trans(1));
    qDebug() << "errorTrans z: " << std::abs(diff_trans(2));
    QVERIFY(std::abs(diff_trans(0)) < errorTrans);
    QVERIFY(std::abs(diff_trans(1)) < errorTrans);
    QVERIFY(std::abs(diff_trans(2)) < errorTrans);
}

//=============================================================================================================

void TestFitHPI::compareRotation()
{
    MatrixXd diff = MatrixXd::Zero(ref_pos.rows(),3);
    RowVector3d diff_quat;
    diff_quat(0) = (ref_pos.col(1)-hpi_pos.col(1)).mean();
    diff_quat(1) = (ref_pos.col(2)-hpi_pos.col(2)).mean();
    diff_quat(2) = (ref_pos.col(3)-hpi_pos.col(3)).mean();
    qDebug() << "errorQuat q1: " <<std::abs(diff_quat(0));
    qDebug() << "errorQuat q2: " <<std::abs(diff_quat(1));
    qDebug() << "errorQuat q3: " <<std::abs(diff_quat(2));
    QVERIFY(std::abs(diff_quat(0)) < errorQuat);
    QVERIFY(std::abs(diff_quat(1)) < errorQuat);
    QVERIFY(std::abs(diff_quat(2)) < errorQuat);
}

//=============================================================================================================

void TestFitHPI::compareTime()
{
    MatrixXd diff = MatrixXd::Zero(ref_pos.rows(),1);
    diff.col(0) = ref_pos.col(0)-hpi_pos.col(0);
    float diff_t = diff.col(0).mean();
    qDebug() << "errorTime: " << diff_t;
    QVERIFY(std::abs(diff_t) < errorTime);
}

//=============================================================================================================

void TestFitHPI::cleanupTestCase()
{
}

//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_GUILESS_MAIN(TestFitHPI)
#include "test_hpiFit.moc"
<commit_msg>MAINT: implement changes to test<commit_after>//=============================================================================================================
/**
 * @file     main.cpp
 * @author   Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
 * @version  dev
 * @date     February, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Ruben Dörfel. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief     Test for fitHpi function in inverse library.
 *
 */

///=============================================================================================================
// INCLUDES
//=============================================================================================================

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

#include <fiff/fiff.h>
#include <fiff/fiff_info.h>
#include <fiff/fiff_dig_point_set.h>
#include <fiff/fiff_cov.h>

#include <inverse/hpiFit/hpifit.h>
#include <inverse/hpiFit/hpifitdata.h>

#include <utils/ioutils.h>
#include <utils/generics/applicationlogger.h>

#include <fwd/fwd_coil_set.h>

#include <Eigen/Dense>
#include <Eigen/Geometry>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QDebug>
#include <QQuaternion>
#include <QtTest>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace INVERSELIB;
using namespace Eigen;
//=============================================================================================================
/**
 * DECLARE CLASS TestFiffRFR
 *
 * @brief The TestFitHPI class provides hpi fit verifivcation tests
 *
 */
class TestFitHPI: public QObject
{
    Q_OBJECT

public:
    TestFitHPI();

private slots:
    void initTestCase();
    void compareTranslation();
    void compareRotation();
    void compareTime();
    void cleanupTestCase();

private:
    double errorTrans = 0.0003;
    double errorQuat = 0.002;
    double errorTime = 0.00000001;
    MatrixXd ref_pos;
    MatrixXd hpi_pos;
};

//=============================================================================================================

TestFitHPI::TestFitHPI()
{
}

//=============================================================================================================

void TestFitHPI::initTestCase()
{
    qInstallMessageHandler(UTILSLIB::ApplicationLogger::customLogWriter);
    qInfo() << "Error Translation" << errorTrans;
    qInfo() << "Error Quaternion" << errorQuat;
    QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");

    // Make sure test folder exists
    QFileInfo t_fileInInfo(t_fileIn);
    QDir().mkdir(t_fileInInfo.path());

    printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read Raw and HPI fit >>>>>>>>>>>>>>>>>>>>>>>>>\n");

    // Setup for reading the raw data
    FiffRawData raw;
    raw = FiffRawData(t_fileIn);
    QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FIFFLIB::FiffInfo>(new FiffInfo(raw.info));

    // Only filter MEG channels
    RowVectorXi picks = raw.info.pick_types(true, false, false);
    RowVectorXd cals;

    // Set up the reading parameters
    fiff_int_t from;
    fiff_int_t to;
    fiff_int_t first = raw.first_samp;
    fiff_int_t last = raw.last_samp;
    MatrixXd matData, times;

    float quantum_sec = 0.2f;   //read and write in 200 ms junks
    fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);

    // Read Quaternion File from maxfilter
    UTILSLIB::IOUtils::read_eigen_matrix(ref_pos, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_hpiFit_pos.txt");

    // Setup informations for HPI fit
    QVector<int> vFreqs {166,154,161,158};
    QVector<double> vError;
    VectorXd vGoF;
    FiffDigPointSet fittedPointSet;
    Eigen::MatrixXd matProjectors = Eigen::MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());
    QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug";
    bool bDoDebug = true;

    for(int i = 0; i < ref_pos.rows(); i++) {
        from = first + ref_pos(i,0)*pFiffInfo->sfreq;
        to = from + quantum;
        if (to > last) {
            to = last;
        }
        qInfo()  << "Reading...";
        if(!raw.read_raw_segment(matData, times, from, to)) {
            qWarning("error during read_raw_segment\n");
        }

        qInfo()  << "HPI-Fit...";
        HPIFit::fitHPI(matData,
                       matProjectors,
                       pFiffInfo->dev_head_t,
                       vFreqs,
                       vError,
                       vGoF,
                       fittedPointSet,
                       pFiffInfo,
                       bDoDebug = 0,
                       sHPIResourceDir);
        qInfo() << "[done]\n";
        HPIFit::storeHeadPosition(ref_pos(i,0), pFiffInfo->dev_head_t.trans, hpi_pos, vGoF, vError);
    }
    // For debug: position file for HPIFit
    UTILSLIB::IOUtils::write_eigen_matrix(hpi_pos, QCoreApplication::applicationDirPath() + "/MNE-sample-data/hpi_pos.txt");
}

//=============================================================================================================

void TestFitHPI::compareTranslation()
{
    MatrixXd diff = MatrixXd::Zero(ref_pos.rows(),3);
    RowVector3d diff_trans;
    diff_trans(0) = (ref_pos.col(4)-hpi_pos.col(4)).mean();
    diff_trans(1) = (ref_pos.col(5)-hpi_pos.col(5)).mean();
    diff_trans(2) = (ref_pos.col(6)-hpi_pos.col(6)).mean();
    qDebug() << "errorTrans x: " << std::abs(diff_trans(0));
    qDebug() << "errorTrans y: " << std::abs(diff_trans(1));
    qDebug() << "errorTrans z: " << std::abs(diff_trans(2));
    QVERIFY(std::abs(diff_trans(0)) < errorTrans);
    QVERIFY(std::abs(diff_trans(1)) < errorTrans);
    QVERIFY(std::abs(diff_trans(2)) < errorTrans);
}

//=============================================================================================================

void TestFitHPI::compareRotation()
{
    MatrixXd diff = MatrixXd::Zero(ref_pos.rows(),3);
    RowVector3d diff_quat;
    diff_quat(0) = (ref_pos.col(1)-hpi_pos.col(1)).mean();
    diff_quat(1) = (ref_pos.col(2)-hpi_pos.col(2)).mean();
    diff_quat(2) = (ref_pos.col(3)-hpi_pos.col(3)).mean();
    qDebug() << "errorQuat q1: " <<std::abs(diff_quat(0));
    qDebug() << "errorQuat q2: " <<std::abs(diff_quat(1));
    qDebug() << "errorQuat q3: " <<std::abs(diff_quat(2));
    QVERIFY(std::abs(diff_quat(0)) < errorQuat);
    QVERIFY(std::abs(diff_quat(1)) < errorQuat);
    QVERIFY(std::abs(diff_quat(2)) < errorQuat);
}

//=============================================================================================================

void TestFitHPI::compareTime()
{
    MatrixXd diff = MatrixXd::Zero(ref_pos.rows(),1);
    diff.col(0) = ref_pos.col(0)-hpi_pos.col(0);
    float diff_t = diff.col(0).mean();
    qDebug() << "errorTime: " << diff_t;
    QVERIFY(std::abs(diff_t) < errorTime);
}

//=============================================================================================================

void TestFitHPI::cleanupTestCase()
{
}

//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_GUILESS_MAIN(TestFitHPI)
#include "test_hpiFit.moc"
<|endoftext|>


<commit_before>#include <unittest/testframework.h>
#include <thrust/system/cuda/memory.h>
#include <cuda_runtime.h>
#include "testframework.h"

void list_devices(void)
{
  int deviceCount;
  cudaGetDeviceCount(&deviceCount);
  if(deviceCount == 0)
  {
    std::cout << "There is no device supporting CUDA" << std::endl;
  }

  int selected_device;
  cudaGetDevice(&selected_device);

  for (int dev = 0; dev < deviceCount; ++dev)
  {
    cudaDeviceProp deviceProp;
    cudaGetDeviceProperties(&deviceProp, dev);

    if(dev == 0)
    {
      if(deviceProp.major == 9999 && deviceProp.minor == 9999)
        std::cout << "There is no device supporting CUDA." << std::endl;
      else if(deviceCount == 1)
        std::cout << "There is 1 device supporting CUDA" << std:: endl;
      else
        std::cout << "There are " << deviceCount <<  " devices supporting CUDA" << std:: endl;
    }

    std::cout << "\nDevice " << dev << ": \"" << deviceProp.name << "\"";
    if(dev == selected_device)
      std::cout << "  [SELECTED]";
    std::cout << std::endl;

    std::cout << "  Major revision number:                         " << deviceProp.major << std::endl;
    std::cout << "  Minor revision number:                         " << deviceProp.minor << std::endl;
    std::cout << "  Total amount of global memory:                 " << deviceProp.totalGlobalMem << " bytes" << std::endl;
  }
  std::cout << std::endl;
}

// provide next, which c++03 doesn't have
template<typename Iterator> Iterator my_next(Iterator iter)
{
  return ++iter;
}

std::vector<int> CUDATestDriver::target_devices(const ArgumentMap &kwargs)
{
  std::vector<int> result;

  // by default, test all devices in the system (device id -1)
  int device_id = kwargs.count("device") ? atoi(kwargs.find("device")->second.c_str()) : -1;

  if(device_id < 0)
  {
    // target all devices in the system
    int count = 0;
    cudaGetDeviceCount(&count);

    result.resize(count);
    // XXX iota is not available in c++03
    for(int i = 0; i < count; ++i)
      result[i] = i;
  }
  else
  {
    // target the specified device
    result = std::vector<int>(1,device_id);
  }

  return result;
}

bool CUDATestDriver::check_cuda_error(bool concise)
{
  cudaError_t error = cudaGetLastError();
  if(error)
  {
    if(!concise)
    {
      std::cout << "[ERROR] CUDA Error detected before running tests: [";
      std::cout << std::string(cudaGetErrorString(error));
      std::cout << "]" << std::endl;
    }
  }

  return error;
}

bool CUDATestDriver::post_test_sanity_check(const UnitTest &test, bool concise)
{
  cudaError_t error = cudaGetLastError();
  if(error && error != cudaErrorMemoryAllocation)
  {
    if(!concise)
    {
      std::cout << "\t[ERROR] CUDA Error detected after running " << test.name << ": [";
      std::cout << std::string(cudaGetErrorString(error));
      std::cout << "]" << std::endl;
    }
  }

  return error == cudaSuccess;
}

bool CUDATestDriver::run_tests(const ArgumentSet &args, const ArgumentMap &kwargs)
{
  bool verbose = kwargs.count("verbose");
  bool concise = kwargs.count("concise");

  if(verbose && concise)
  {
    std::cout << "--verbose and --concise cannot be used together" << std::endl;
    exit(EXIT_FAILURE);
  }

  bool result = true;

  if(kwargs.count("verbose"))
  {
    list_devices();
  }

  // figure out which devices to target
  std::vector<int> devices = target_devices(kwargs);

  // target each device
  for(std::vector<int>::iterator device = devices.begin();
      device != devices.end();
      ++device)
  {
    if(!concise)
    {
      // note which device we're testing
      cudaDeviceProp deviceProp;
      cudaGetDeviceProperties(&deviceProp, *device);

      std::cout << "Testing Device " << *device << ": \"" << deviceProp.name << "\"" << std::endl;
    }

    // set the device
    cudaSetDevice(*device);

    // check error status before running any tests
    if(check_cuda_error(concise)) return false;

    // run tests
    result &= UnitTestDriver::run_tests(args, kwargs);

    if(!concise && my_next(device) != devices.end())
    {
      // provide some separation between the output of separate tests
      std::cout << std::endl;
    }
  }

  return result;
}

UnitTestDriver &driver_instance(thrust::system::cuda::tag)
{
  static CUDATestDriver s_instance;
  return s_instance;
}

<commit_msg>Check for CUDA error before doing anything with CUDART in the unit tester.<commit_after>#include <unittest/testframework.h>
#include <thrust/system/cuda/memory.h>
#include <cuda_runtime.h>
#include "testframework.h"

void list_devices(void)
{
  int deviceCount;
  cudaGetDeviceCount(&deviceCount);
  if(deviceCount == 0)
  {
    std::cout << "There is no device supporting CUDA" << std::endl;
  }

  int selected_device;
  cudaGetDevice(&selected_device);

  for (int dev = 0; dev < deviceCount; ++dev)
  {
    cudaDeviceProp deviceProp;
    cudaGetDeviceProperties(&deviceProp, dev);

    if(dev == 0)
    {
      if(deviceProp.major == 9999 && deviceProp.minor == 9999)
        std::cout << "There is no device supporting CUDA." << std::endl;
      else if(deviceCount == 1)
        std::cout << "There is 1 device supporting CUDA" << std:: endl;
      else
        std::cout << "There are " << deviceCount <<  " devices supporting CUDA" << std:: endl;
    }

    std::cout << "\nDevice " << dev << ": \"" << deviceProp.name << "\"";
    if(dev == selected_device)
      std::cout << "  [SELECTED]";
    std::cout << std::endl;

    std::cout << "  Major revision number:                         " << deviceProp.major << std::endl;
    std::cout << "  Minor revision number:                         " << deviceProp.minor << std::endl;
    std::cout << "  Total amount of global memory:                 " << deviceProp.totalGlobalMem << " bytes" << std::endl;
  }
  std::cout << std::endl;
}

// provide next, which c++03 doesn't have
template<typename Iterator> Iterator my_next(Iterator iter)
{
  return ++iter;
}

std::vector<int> CUDATestDriver::target_devices(const ArgumentMap &kwargs)
{
  std::vector<int> result;

  // by default, test all devices in the system (device id -1)
  int device_id = kwargs.count("device") ? atoi(kwargs.find("device")->second.c_str()) : -1;

  if(device_id < 0)
  {
    // target all devices in the system
    int count = 0;
    cudaGetDeviceCount(&count);

    result.resize(count);
    // XXX iota is not available in c++03
    for(int i = 0; i < count; ++i)
      result[i] = i;
  }
  else
  {
    // target the specified device
    result = std::vector<int>(1,device_id);
  }

  return result;
}

bool CUDATestDriver::check_cuda_error(bool concise)
{
  cudaError_t error = cudaGetLastError();
  if(error)
  {
    if(!concise)
    {
      std::cout << "[ERROR] CUDA Error detected before running tests: [";
      std::cout << std::string(cudaGetErrorString(error));
      std::cout << "]" << std::endl;
    }
  }

  return error;
}

bool CUDATestDriver::post_test_sanity_check(const UnitTest &test, bool concise)
{
  cudaError_t error = cudaGetLastError();
  if(error && error != cudaErrorMemoryAllocation)
  {
    if(!concise)
    {
      std::cout << "\t[ERROR] CUDA Error detected after running " << test.name << ": [";
      std::cout << std::string(cudaGetErrorString(error));
      std::cout << "]" << std::endl;
    }
  }

  return error == cudaSuccess;
}

bool CUDATestDriver::run_tests(const ArgumentSet &args, const ArgumentMap &kwargs)
{
  bool verbose = kwargs.count("verbose");
  bool concise = kwargs.count("concise");

  if(verbose && concise)
  {
    std::cout << "--verbose and --concise cannot be used together" << std::endl;
    exit(EXIT_FAILURE);
  }

  // check error status before doing anything
  if(check_cuda_error(concise)) return false;

  bool result = true;

  if(kwargs.count("verbose"))
  {
    list_devices();
  }

  // figure out which devices to target
  std::vector<int> devices = target_devices(kwargs);

  // target each device
  for(std::vector<int>::iterator device = devices.begin();
      device != devices.end();
      ++device)
  {
    if(!concise)
    {
      // note which device we're testing
      cudaDeviceProp deviceProp;
      cudaGetDeviceProperties(&deviceProp, *device);

      std::cout << "Testing Device " << *device << ": \"" << deviceProp.name << "\"" << std::endl;
    }

    // set the device
    cudaSetDevice(*device);

    // check error status before running any tests
    if(check_cuda_error(concise)) return false;

    // run tests
    result &= UnitTestDriver::run_tests(args, kwargs);

    if(!concise && my_next(device) != devices.end())
    {
      // provide some separation between the output of separate tests
      std::cout << std::endl;
    }
  }

  return result;
}

UnitTestDriver &driver_instance(thrust::system::cuda::tag)
{
  static CUDATestDriver s_instance;
  return s_instance;
}

<|endoftext|>


<commit_before>#import <v8.h>
#import <node.h>
#import <AudioToolbox/AudioToolbox.h>
#import <UIKit/UIKit.h>
#import "graphicServices.h"
#import "notifications.h"
#import "telephony.h"
#import "compatibility.h" // ...meh

using namespace node;
using namespace v8;

class Binding {
  public:

  static void Init(v8::Handle<Object> target) {
    HandleScope scope;

    UIDevice *aDevice = [UIDevice currentDevice];
    [aDevice beginGeneratingDeviceOrientationNotifications];
    [aDevice setBatteryMonitoringEnabled:YES];

    NODE_SET_METHOD(target, "vibrate", Vibrate);
    NODE_SET_METHOD(target, "device", Device);
    NODE_SET_METHOD(target, "sendSMS", Telephony::SendSMS);
  }

  static v8::Handle<Value> Vibrate(const Arguments& args) {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    return Undefined();
  }

  static v8::Handle<Value> Device(const Arguments& args) {
    HandleScope scope;
    Local<Object> result = Object::New();

    UIDevice *aDevice = [UIDevice currentDevice];

    result->Set(String::NewSymbol("batteryLevel"), Number::New([aDevice batteryLevel]));
    result->Set(String::NewSymbol("batteryState"), Integer::New([aDevice batteryState]));
    result->Set(String::NewSymbol("model"), String::NewSymbol([[aDevice model] UTF8String]));
    result->Set(String::NewSymbol("localizedModel"), String::NewSymbol([[aDevice localizedModel] UTF8String]));
    result->Set(String::NewSymbol("orientation"), Integer::New([aDevice orientation]));
    result->Set(String::NewSymbol("name"), String::NewSymbol([[aDevice name] UTF8String]));
    result->Set(String::NewSymbol("systemName"), String::NewSymbol([[aDevice systemName] UTF8String]));
    result->Set(String::NewSymbol("systemVersion"), String::NewSymbol([[aDevice systemVersion] UTF8String]));
    result->Set(String::NewSymbol("uniqueIdentifier"), String::NewSymbol([[aDevice uniqueIdentifier] UTF8String]));

    return scope.Close(result);
  }

};

extern "C" void init (v8::Handle<Object> target) {
  Binding::Init(target);
  GraphicServices::Init(target);
  Notifications::Init(target);
}
<commit_msg>Revert "Remove call to NODE_MODULES macro. WTF did that do anyways?"<commit_after>#import <v8.h>
#import <node.h>
#import <AudioToolbox/AudioToolbox.h>
#import <UIKit/UIKit.h>
#import "graphicServices.h"
#import "notifications.h"
#import "telephony.h"
#import "compatibility.h" // ...meh

using namespace node;
using namespace v8;

class Binding {
  public:

  static void Init(v8::Handle<Object> target) {
    HandleScope scope;

    UIDevice *aDevice = [UIDevice currentDevice];
    [aDevice beginGeneratingDeviceOrientationNotifications];
    [aDevice setBatteryMonitoringEnabled:YES];

    NODE_SET_METHOD(target, "vibrate", Vibrate);
    NODE_SET_METHOD(target, "device", Device);
    NODE_SET_METHOD(target, "sendSMS", Telephony::SendSMS);
  }

  static v8::Handle<Value> Vibrate(const Arguments& args) {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    return Undefined();
  }

  static v8::Handle<Value> Device(const Arguments& args) {
    HandleScope scope;
    Local<Object> result = Object::New();

    UIDevice *aDevice = [UIDevice currentDevice];

    result->Set(String::NewSymbol("batteryLevel"), Number::New([aDevice batteryLevel]));
    result->Set(String::NewSymbol("batteryState"), Integer::New([aDevice batteryState]));
    result->Set(String::NewSymbol("model"), String::NewSymbol([[aDevice model] UTF8String]));
    result->Set(String::NewSymbol("localizedModel"), String::NewSymbol([[aDevice localizedModel] UTF8String]));
    result->Set(String::NewSymbol("orientation"), Integer::New([aDevice orientation]));
    result->Set(String::NewSymbol("name"), String::NewSymbol([[aDevice name] UTF8String]));
    result->Set(String::NewSymbol("systemName"), String::NewSymbol([[aDevice systemName] UTF8String]));
    result->Set(String::NewSymbol("systemVersion"), String::NewSymbol([[aDevice systemVersion] UTF8String]));
    result->Set(String::NewSymbol("uniqueIdentifier"), String::NewSymbol([[aDevice uniqueIdentifier] UTF8String]));

    return scope.Close(result);
  }

};

extern "C" {
  static void init (v8::Handle<Object> target) {
    Binding::Init(target);
    GraphicServices::Init(target);
    Notifications::Init(target);
  }

  NODE_MODULE(binding, init);
}
<|endoftext|>


<commit_before>/**
 * \file dcs/testbed/system_identification.hpp
 *
 * \brief Class to perform a system identification experiment.
 *
 * \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/>.
 */

#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP

#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/base_signal_generator.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <fstream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unistd.h>
#include <vector>

#ifdef DCS_DEBUG
# include <boost/numeric/ublas/io.hpp>
#endif // DCS_DEBUG

namespace dcs { namespace testbed {

template <typename RealT>
class system_identification
{
	public: typedef RealT real_type;
	public: typedef base_virtual_machine<real_type> vm_type;
	public: typedef ::boost::shared_ptr<vm_type> vm_pointer;
	public: typedef base_signal_generator<real_type> signal_generator_type;
	public: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;
	public: typedef base_workload_driver workload_driver_type;
	public: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;
	private: typedef ::std::vector<vm_pointer> vm_container;

	private: static const unsigned int default_sampling_time = 10;
	private: static const ::std::string default_output_data_file_path;

	public: system_identification()
	: ts_(default_sampling_time),
	  out_dat_file_(default_output_data_file_path)
	{
	}

	public: template <typename FwdIterT>
			system_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)
	: vms_(vm_first, vm_last),
	  p_wkl_driver_(p_wkl_driver),
	  p_sig_gen_(p_sig_gen),
	  ts_(default_sampling_time),
	  out_dat_file_(default_output_data_file_path)
	{
	}

	/// Set the path of the output data file.
	public: void output_data_file(::std::string const& s)
	{
		out_dat_file_ = s;
	}

	/**
	 * \brief Perform system identification by using as initial shares the
	 *  100% of resource.
	 */
	public: void run()
	{
		::std::vector<real_type> init_shares(vms_.size(), 1);

		this->run(init_shares.begin(), init_shares.end());
	}

	/**
	 * \brief Perform system identification with the given initial shares.
	 */
	public: template <typename FwdIterT>
			void run(FwdIterT share_first, FwdIterT share_end)
	{
		// distance(share_first,share_end) == size(vms_)
		DCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Share container size does not match"));

		typedef typename vm_container::const_iterator vm_iterator;
		typedef typename signal_generator_type::vector_type share_container;

		//const ::std::size_t nt(10);//FIXME: parameterize

		// Open output data file
		::std::ofstream ofs(out_dat_file_.c_str());
		if (!ofs.good())
		{
			::std::ostringstream oss;
			oss << "Cannot open output data file '" << out_dat_file_ << "'";

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		// Set initial shares
		vm_iterator vm_end_it(vms_.end());
		vm_iterator vm_beg_it(vms_.begin());
		for (vm_iterator vm_it = vm_beg_it;
			 vm_it != vm_end_it;
			 ++vm_it)
		{
			vm_pointer p_vm(*vm_it);

			p_vm->cpu_share(*share_first);
			++share_first;
		}

		// Start the workload driver
		p_wkl_driver_->start();

		// Set shares according to the given signal
		::std::size_t t(0);
		while (p_wkl_driver_->alive())
		{
			if (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())
			{
				share_container share((*p_sig_gen_)());

				// check: consistency
				DCS_DEBUG_ASSERT( share.size() == vms_.size() );

				double rt = p_wkl_driver_->observation();

				DCS_DEBUG_TRACE( "-- Time " << (t*ts_) );
				DCS_DEBUG_TRACE( "   Generated shares: " << dcs::debug::to_string(share.begin(), share.end()) );
				DCS_DEBUG_TRACE( "   Current Response Time: " << rt );

				ofs << t*ts_ << " " << rt;

				::std::size_t ix(0);
				for (vm_iterator vm_it = vm_beg_it;
					 vm_it != vm_end_it;
					 ++vm_it)
				{
					vm_pointer p_vm(*vm_it);

					// check: not null
					DCS_DEBUG_ASSERT( p_vm );

					DCS_DEBUG_TRACE( "   VM '" << p_vm->name() << "' :: Old CPU share: " << p_vm->cpu_share() << " :: New CPU share: " << share[ix] );

					ofs << " " << p_vm->cpu_share();

					p_vm->cpu_share(share[ix]);

					++ix;
				}

				ofs << ::std::endl;

				// Wait until the next sampling time
				::sleep(ts_);
			}

			++t;
		}

		// Stop the workload driver
		p_wkl_driver_->stop();

		// Close output data file
		ofs.close();
	}

	private: vm_container vms_; ///< VMs container
	private: workload_driver_pointer p_wkl_driver_; ///< Ptr to workload driver
	private: signal_generator_pointer p_sig_gen_; ///< Ptr to signal generator used to excite VMs
	private: unsigned int ts_; ///< The sampling time
	private: ::std::string out_dat_file_; ///< The path to the output data file
}; // system_identification

template <typename RealT>
const ::std::string system_identification<RealT>::default_output_data_file_path("./sysid_out.dat");

}} // Namespace dcs::testbed

#endif // DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
<commit_msg>(bug-fix:minor) Use C timing functions to keep track of time passing.<commit_after>/**
 * \file dcs/testbed/system_identification.hpp
 *
 * \brief Class to perform a system identification experiment.
 *
 * \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/>.
 */

#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP

#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <ctime>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/base_signal_generator.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <fstream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unistd.h>
#include <vector>

#ifdef DCS_DEBUG
# include <boost/numeric/ublas/io.hpp>
#endif // DCS_DEBUG

namespace dcs { namespace testbed {

template <typename RealT>
class system_identification
{
	public: typedef RealT real_type;
	public: typedef base_virtual_machine<real_type> vm_type;
	public: typedef ::boost::shared_ptr<vm_type> vm_pointer;
	public: typedef base_signal_generator<real_type> signal_generator_type;
	public: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;
	public: typedef base_workload_driver workload_driver_type;
	public: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;
	private: typedef ::std::vector<vm_pointer> vm_container;

	private: static const unsigned int default_sampling_time = 10;
	private: static const ::std::string default_output_data_file_path;

	public: system_identification()
	: ts_(default_sampling_time),
	  out_dat_file_(default_output_data_file_path)
	{
	}

	public: template <typename FwdIterT>
			system_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)
	: vms_(vm_first, vm_last),
	  p_wkl_driver_(p_wkl_driver),
	  p_sig_gen_(p_sig_gen),
	  ts_(default_sampling_time),
	  out_dat_file_(default_output_data_file_path)
	{
	}

	/// Set the path of the output data file.
	public: void output_data_file(::std::string const& s)
	{
		out_dat_file_ = s;
	}

	/**
	 * \brief Perform system identification by using as initial shares the
	 *  100% of resource.
	 */
	public: void run()
	{
		::std::vector<real_type> init_shares(vms_.size(), 1);

		this->run(init_shares.begin(), init_shares.end());
	}

	/**
	 * \brief Perform system identification with the given initial shares.
	 */
	public: template <typename FwdIterT>
			void run(FwdIterT share_first, FwdIterT share_end)
	{
		// distance(share_first,share_end) == size(vms_)
		DCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Share container size does not match"));

		typedef typename vm_container::const_iterator vm_iterator;
		typedef typename signal_generator_type::vector_type share_container;

		//const ::std::size_t nt(10);//FIXME: parameterize

		// Open output data file
		::std::ofstream ofs(out_dat_file_.c_str());
		if (!ofs.good())
		{
			::std::ostringstream oss;
			oss << "Cannot open output data file '" << out_dat_file_ << "'";

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		// Set initial shares
		vm_iterator vm_end_it(vms_.end());
		vm_iterator vm_beg_it(vms_.begin());
		for (vm_iterator vm_it = vm_beg_it;
			 vm_it != vm_end_it;
			 ++vm_it)
		{
			vm_pointer p_vm(*vm_it);

			p_vm->cpu_share(*share_first);
			++share_first;
		}

		// Start the workload driver
		p_wkl_driver_->start();

		// Set shares according to the given signal
		::std::time_t t0;
		::std::time_t t1;
		t0 = ::std::time(&t1);
		while (p_wkl_driver_->alive())
		{
			if (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())
			{
				share_container share((*p_sig_gen_)());

				// check: consistency
				DCS_DEBUG_ASSERT( share.size() == vms_.size() );

				double rt = p_wkl_driver_->observation();

				t0 = t1;
				::std::time(&t1);
				double dt = ::std::difftime(t1, t0);
				DCS_DEBUG_TRACE( "-- Time " << dt );
				DCS_DEBUG_TRACE( "   Generated shares: " << dcs::debug::to_string(share.begin(), share.end()) );
				DCS_DEBUG_TRACE( "   Current Response Time: " << rt );

				ofs << dt << " " << rt;

				::std::size_t ix(0);
				for (vm_iterator vm_it = vm_beg_it;
					 vm_it != vm_end_it;
					 ++vm_it)
				{
					vm_pointer p_vm(*vm_it);

					// check: not null
					DCS_DEBUG_ASSERT( p_vm );

					DCS_DEBUG_TRACE( "   VM '" << p_vm->name() << "' :: Old CPU share: " << p_vm->cpu_share() << " :: New CPU share: " << share[ix] );

					ofs << " " << p_vm->cpu_share();

					p_vm->cpu_share(share[ix]);

					++ix;
				}

				ofs << ::std::endl;

				// Wait until the next sampling time
				::sleep(ts_);
			}
		}

		// Stop the workload driver
		p_wkl_driver_->stop();

		// Close output data file
		ofs.close();
	}

	private: vm_container vms_; ///< VMs container
	private: workload_driver_pointer p_wkl_driver_; ///< Ptr to workload driver
	private: signal_generator_pointer p_sig_gen_; ///< Ptr to signal generator used to excite VMs
	private: unsigned int ts_; ///< The sampling time
	private: ::std::string out_dat_file_; ///< The path to the output data file
}; // system_identification

template <typename RealT>
const ::std::string system_identification<RealT>::default_output_data_file_path("./sysid_out.dat");

}} // Namespace dcs::testbed

#endif // DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
<|endoftext|>


<commit_before>/*
  This is an example file shipped by 'Aleph - A Library for Exploring
  Persistent Homology'.

  This example demonstrates how to obtain a Vietoris--Rips complex
  from an unstructured point cloud (using Euclidean distances) and
  calculate its persistent homology.

  Demonstrated classes:

    - aleph::PersistenceDiagram
    - aleph::containers::PointCloud
    - aleph::geometry::FLANN
    - aleph::geometry::BruteForce

  Demonstrated functions:

    - aleph::geometry::buildVietorisRipsComplex
    - aleph::calculatePersistenceDiagrams
    - aleph::utilities::convert

  Original author: Bastian Rieck
*/

#include <aleph/config/FLANN.hh>

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/BruteForce.hh>
#include <aleph/geometry/FLANN.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/utilities/String.hh>

#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <iostream>
#include <string>
#include <vector>

void usage()
{
  std::cerr << "Usage: vietoris_rips FILE EPSILON [DIMENSION]\n"
            << "\n"
            << "Calculates the Vietoris--Rips complex of an unstructured point\n"
            << "cloud, stored in FILE. Euclidean distances are used during the\n"
            << "expansion process. The maximum distance threshold is specified\n"
            << "by EPSILON. If present, an optional parameter DIMENSION may be\n"
            << "used to truncate the simplicial complex.\n"
            << "\n";
}

int main( int argc, char** argv )
{
  if( argc <= 2 )
  {
    usage();
    return -1;
  }

  // We first have to specify the data type to use for the subsequent
  // expansion of the Vietoris--Rips complex. This also results in
  // a different choice of point clouds.
  //
  // Moreover, we specify a distance functor to use for the subsequent
  // expansion process.
  //
  // For educational purposes, we use the full namespace here.
  using DataType   = double;
  using PointCloud = aleph::containers::PointCloud<DataType>;
  using Distance   = aleph::geometry::distances::Euclidean<DataType>;

  std::string input = argv[1];

  // This loads the point cloud from an unstructured file. The point
  // cloud loader is smart enough to handle things such as different
  // separators in a file.
  auto pointCloud   = aleph::containers::load<DataType>( input );
  auto dimension    = pointCloud.dimension() + 1;

  // This converts the string supplied by the user to the corresponding
  // data type. Note that the `convert()` function only makes sense for
  // builtin types such as 'double' or 'float'. If you want to use this
  // for your own data types, you need to overload `operator>>` because
  // the converter internally uses `std::stringstream` for tokens.
  auto epsilon = aleph::utilities::convert<DataType>( argv[2] );

  if( argc >= 4 )
    dimension = std::stoul( argv[3] );

  std::cerr << "* Calculating Vietoris--Rips complex with eps=" << epsilon << " and d=" << dimension << "...";

  // Aleph gives you some options for detecting optional features such
  // as the wrapper for neighbourhood calculations. I would recommend
  // using the FLANN wrapper. It uses kd-trees, is reasonably fast in
  // higher dimensions and well tested.
  //
  // If this wrapper is not available, we fall back to the brute force
  // wrapper, which---you guessed it---enumerates all neighbours by,
  // well, brute force.
  //
  // If you want to write a wrapper for another library, take a look at
  // the interface of the FLANN wrapper.
  #ifdef ALEPH_WITH_FLANN
    aleph::geometry::FLANN<PointCloud, Distance> flannWrapper( pointCloud );

    // That's really all there is to is: the convenience function below
    // uses a neighbourhood wrapper and additional parameters and
    // creates an appropriate Vietoris--Rips complex.
    //
    // Since we did not specify anything else, the complex will contain
    // the high-dimensional distances as weights. The vertices of K are
    // assigned a value of 0, while the edges are assigned a value
    // according to the distance between their corresponding vertices.
    //
    // The simplicial complex is ordered according to this weight, from
    // low values to high values, resulting in a filtration of the
    // sublevel sets of the distance function.
    //
    // Other filtrations are possible but need to be applied manually
    // afterwards.
    auto K
      = aleph::geometry::buildVietorisRipsComplex( flannWrapper,
                                                   epsilon,
                                                   unsigned( dimension ) );
  #else
    aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );

    auto K
      = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper,
                                                   epsilon,
                                                   unsigned( dimension ) );
  #endif

  std::cerr << "finished\n"
            << "* Obtained simplicial complex with " << K.size() << " simplices\n";

  std::cerr << "* Calculating persistence diagrams...";

  // Finally, this function will calculate all persistence diagrams of
  // the simplicial complex. Again, this is a convenience function which
  // assumes that the complex is already in filtration order.
  auto diagrams
    = aleph::calculatePersistenceDiagrams( K );

  std::cerr << "finished\n"
            << "* Obtained " << diagrams.size() << " persistence diagrams\n";

  for( auto&& D : diagrams )
  {
    // Removes all features of zero persistence. They only clutter up
    // the diagonal.
    D.removeDiagonal();

    // This output contains a sort of header (in gnuplot style) so that
    // it is possible to store multiple persistence diagrams in the same
    // file.
    //
    // Note that for the output, it would also be possible just to loop
    // over the individual points of the persistence diagram.
    std::cout << "# Persistence diagram <" << input << ">\n"
              << "#\n"
              << "# Dimension: " << D.dimension() << "\n"
              << "# Entries  : " << D.size() << "\n"
              << D << "\n\n";
  }
}
<commit_msg>Trying to support reading from `STDIN` directly<commit_after>/*
  This is an example file shipped by 'Aleph - A Library for Exploring
  Persistent Homology'.

  This example demonstrates how to obtain a Vietoris--Rips complex
  from an unstructured point cloud (using Euclidean distances) and
  calculate its persistent homology.

  Demonstrated classes:

    - aleph::PersistenceDiagram
    - aleph::containers::PointCloud
    - aleph::geometry::FLANN
    - aleph::geometry::BruteForce

  Demonstrated functions:

    - aleph::geometry::buildVietorisRipsComplex
    - aleph::calculatePersistenceDiagrams
    - aleph::utilities::convert

  Original author: Bastian Rieck
*/

#include <aleph/config/FLANN.hh>

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/BruteForce.hh>
#include <aleph/geometry/FLANN.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/utilities/String.hh>

#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <iostream>
#include <string>
#include <vector>

void usage()
{
  std::cerr << "Usage: vietoris_rips FILE EPSILON [DIMENSION]\n"
            << "\n"
            << "Calculates the Vietoris--Rips complex of an unstructured point\n"
            << "cloud, stored in FILE. Euclidean distances are used during the\n"
            << "expansion process. The maximum distance threshold is specified\n"
            << "by EPSILON. If present, an optional parameter DIMENSION may be\n"
            << "used to truncate the simplicial complex.\n"
            << "\n";
}

int main( int argc, char** argv )
{
  if( argc <= 2 )
  {
    usage();
    return -1;
  }

  // We first have to specify the data type to use for the subsequent
  // expansion of the Vietoris--Rips complex. This also results in
  // a different choice of point clouds.
  //
  // Moreover, we specify a distance functor to use for the subsequent
  // expansion process.
  //
  // For educational purposes, we use the full namespace here.
  using DataType   = double;
  using PointCloud = aleph::containers::PointCloud<DataType>;
  using Distance   = aleph::geometry::distances::Euclidean<DataType>;

  std::string input = argv[1];

  PointCloud pointCloud;

  if( input == "-" )
    pointCloud = aleph::containers::load<DataType>( std::cin );
  else
  {
    // This loads the point cloud from an unstructured file. The point
    // cloud loader is smart enough to handle things such as different
    // separators in a file.
    pointCloud = aleph::containers::load<DataType>( input );
  }

  auto dimension = pointCloud.dimension() + 1;

  // This converts the string supplied by the user to the corresponding
  // data type. Note that the `convert()` function only makes sense for
  // builtin types such as 'double' or 'float'. If you want to use this
  // for your own data types, you need to overload `operator>>` because
  // the converter internally uses `std::stringstream` for tokens.
  auto epsilon = aleph::utilities::convert<DataType>( argv[2] );

  if( argc >= 4 )
    dimension = std::stoul( argv[3] );

  std::cerr << "* Calculating Vietoris--Rips complex with eps=" << epsilon << " and d=" << dimension << "...";

  // Aleph gives you some options for detecting optional features such
  // as the wrapper for neighbourhood calculations. I would recommend
  // using the FLANN wrapper. It uses kd-trees, is reasonably fast in
  // higher dimensions and well tested.
  //
  // If this wrapper is not available, we fall back to the brute force
  // wrapper, which---you guessed it---enumerates all neighbours by,
  // well, brute force.
  //
  // If you want to write a wrapper for another library, take a look at
  // the interface of the FLANN wrapper.
  #ifdef ALEPH_WITH_FLANN
    aleph::geometry::FLANN<PointCloud, Distance> flannWrapper( pointCloud );

    // That's really all there is to is: the convenience function below
    // uses a neighbourhood wrapper and additional parameters and
    // creates an appropriate Vietoris--Rips complex.
    //
    // Since we did not specify anything else, the complex will contain
    // the high-dimensional distances as weights. The vertices of K are
    // assigned a value of 0, while the edges are assigned a value
    // according to the distance between their corresponding vertices.
    //
    // The simplicial complex is ordered according to this weight, from
    // low values to high values, resulting in a filtration of the
    // sublevel sets of the distance function.
    //
    // Other filtrations are possible but need to be applied manually
    // afterwards.
    auto K
      = aleph::geometry::buildVietorisRipsComplex( flannWrapper,
                                                   epsilon,
                                                   unsigned( dimension ) );
  #else
    aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );

    auto K
      = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper,
                                                   epsilon,
                                                   unsigned( dimension ) );
  #endif

  std::cerr << "finished\n"
            << "* Obtained simplicial complex with " << K.size() << " simplices\n";

  std::cerr << "* Calculating persistence diagrams...";

  // Finally, this function will calculate all persistence diagrams of
  // the simplicial complex. Again, this is a convenience function which
  // assumes that the complex is already in filtration order.
  auto diagrams
    = aleph::calculatePersistenceDiagrams( K );

  std::cerr << "finished\n"
            << "* Obtained " << diagrams.size() << " persistence diagrams\n";

  for( auto&& D : diagrams )
  {
    // Removes all features of zero persistence. They only clutter up
    // the diagonal.
    D.removeDiagonal();

    // This output contains a sort of header (in gnuplot style) so that
    // it is possible to store multiple persistence diagrams in the same
    // file.
    //
    // Note that for the output, it would also be possible just to loop
    // over the individual points of the persistence diagram.
    std::cout << "# Persistence diagram <" << input << ">\n"
              << "#\n"
              << "# Dimension: " << D.dimension() << "\n"
              << "# Entries  : " << D.size() << "\n"
              << D << "\n\n";
  }
}
<|endoftext|>


<commit_before>#ifndef BULL_MATH_MATRIX_SQUAREMATRIX_HPP
#define BULL_MATH_MATRIX_SQUAREMATRIX_HPP

#include <Bull/Math/Matrix/Matrix.hpp>

namespace Bull
{
    template <typename T, std::size_t S>
    struct SquareMatrix : public Matrix<T, S, S>
    {
        static SquareMatrix<T, S> Zero;

        /*! \brief Create an identity SquareMatrix
         *
         * \return The identity SquareMatrix
         *
         */
        static SquareMatrix<T, S> makeIdentity()
        {
            SquareMatrix<T, S> identity;

            for(std::size_t i = 0; i < S; i++)
            {
                identity.at(i, i) = 1;
            }

            return identity;
        }

        /*! \brief Default constructor
         *
         */
        SquareMatrix() = default;

        /*! \brief Constructor
         *
         * \param value The value to use to fill the Matrix
         *
         */
        explicit SquareMatrix(T value) :
            Matrix<T, S, S>(value)
        {
            /// Nothing
        }

        /*! \brief Copy constructor
         *
         * \param copy The Matrix to copy
         *
         */
        template <typename U, std::size_t WU, std::size_t HU>
        SquareMatrix(const Matrix<U, WU, HU>& copy) :
            Matrix<T, S, S>(copy)
        {
            /// Nothing
        }
    };

    template <typename T, std::size_t S>
    SquareMatrix<T, S> SquareMatrix<T, S>::Zero = SquareMatrix<T, S>();

    /*! \brief Multiply two Matrix
     *
     * \param left  The left Matrix
     * \param right The right Matrix
     *
     * \return The product of left and right
     *
     */
    template <typename T, std::size_t S>
    SquareMatrix<T, S> operator*(const SquareMatrix<T, S>& left, const SquareMatrix<T, S>& right)
    {
        SquareMatrix<T, S> product;

        for(std::size_t y = 0; y < S; y++)
        {
            for(std::size_t x = 0; x < S; x++)
            {
                T sum = 0;

                Vector<T, S> row = right.getRow(x);
                Vector<T, S> column = left.getColumn(y);

                for(std::size_t i = 0; i < S; i++)
                {
                    sum += row.at(i) * column.at(i);
                }

                product.at(x, y) = sum;
            }
        }

        return product;
    }
}

#endif // BULL_MATH_MATRIX_SQUAREMATRIX_HPP
<commit_msg>[Math/SquareMatrix] Implement Matrix * Vector operator<commit_after>#ifndef BULL_MATH_MATRIX_SQUAREMATRIX_HPP
#define BULL_MATH_MATRIX_SQUAREMATRIX_HPP

#include <Bull/Math/Matrix/Matrix.hpp>

namespace Bull
{
    template <typename T, std::size_t S>
    struct SquareMatrix : public Matrix<T, S, S>
    {
        static SquareMatrix<T, S> Zero;

        /*! \brief Create an identity SquareMatrix
         *
         * \return The identity SquareMatrix
         *
         */
        static SquareMatrix<T, S> makeIdentity()
        {
            SquareMatrix<T, S> identity;

            for(std::size_t i = 0; i < S; i++)
            {
                identity.at(i, i) = 1;
            }

            return identity;
        }

        /*! \brief Default constructor
         *
         */
        SquareMatrix() = default;

        /*! \brief Constructor
         *
         * \param value The value to use to fill the Matrix
         *
         */
        explicit SquareMatrix(T value) :
            Matrix<T, S, S>(value)
        {
            /// Nothing
        }

        /*! \brief Copy constructor
         *
         * \param copy The Matrix to copy
         *
         */
        template <typename U, std::size_t WU, std::size_t HU>
        SquareMatrix(const Matrix<U, WU, HU>& copy) :
            Matrix<T, S, S>(copy)
        {
            /// Nothing
        }
    };

    template <typename T, std::size_t S>
    SquareMatrix<T, S> SquareMatrix<T, S>::Zero = SquareMatrix<T, S>();

    /*! \brief Multiply two Matrix
     *
     * \param left  The left Matrix
     * \param right The right Matrix
     *
     * \return The product of left and right
     *
     */
    template <typename T, std::size_t S>
    SquareMatrix<T, S> operator*(const SquareMatrix<T, S>& left, const SquareMatrix<T, S>& right)
    {
        SquareMatrix<T, S> product;

        for(std::size_t y = 0; y < S; y++)
        {
            for(std::size_t x = 0; x < S; x++)
            {
                T sum = 0;

                Vector<T, S> row = right.getRow(x);
                Vector<T, S> column = left.getColumn(y);

                for(std::size_t i = 0; i < S; i++)
                {
                    sum += row.at(i) * column.at(i);
                }

                product.at(x, y) = sum;
            }
        }

        return product;
    }

    template <typename T, std::size_t S>
    Vector<T, S> operator*(const SquareMatrix<T, S>& left, const Vector<T, S>& right)
    {
        Vector<T, S> product;

        for(std::size_t i = 0; i < S; i++)
        {
            product.at(i) = Vector<T, S>::dotProduct(right, left.getColumn(i));
        }

        return product;
    }
}

#endif // BULL_MATH_MATRIX_SQUAREMATRIX_HPP
<|endoftext|>


<commit_before>#ifndef GNR_SCOPEEXIT_HPP
# define GNR_SCOPEEXIT_HPP
# pragma once

#include <utility>

/* This counts the number of args */
#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

/* This will let macros expand before concating them */
#ifndef PRIMITIVE_CAT
# define PRIMITIVE_CAT(x, y) x ## y
#endif // PRIMITIVE_CAT

#ifndef CAT
# define CAT(x, y) PRIMITIVE_CAT(x, y)
#endif // CAT

/* This will pop the last argument off */
#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define POP_LAST_1(x1)
#define POP_LAST_2(x1, x2) x1
#define POP_LAST_3(x1, x2, x3) x1, x2
#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3
#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4
#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5
#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6
#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7
#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8
#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9

/* This will return the last argument */
#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define LAST_1(x1) x1
#define LAST_2(x1, x2) x2
#define LAST_3(x1, x2, x3) x3
#define LAST_4(x1, x2, x3, x4) x4
#define LAST_5(x1, x2, x3, x4, x5) x5
#define LAST_6(x1, x2, x3, x4, x5, x6) x6
#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7
#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8
#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9
#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10

namespace gnr
{

template <typename F>
class scope_exit
{
  F f_;

public:
  explicit scope_exit(F&& f)
    noexcept(noexcept(F(std::move(f)))):
    f_(std::move(f))
  {
  }

  ~scope_exit() noexcept(noexcept(std::declval<F>()())) { f_(); }

  scope_exit(scope_exit const&) = delete;
  scope_exit(scope_exit&&) = delete;
};

}

#define SCOPE_EXIT(...) auto const CAT(gnr_scope_exit_, __LINE__)\
  (gnr::scope_exit([POP_LAST(__VA_ARGS__)]()\
    noexcept(noexcept(LAST(__VA_ARGS__)))\
    { LAST(__VA_ARGS__); }))

#endif // GNR_SCOPEEXIT_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_SCOPEEXIT_HPP
# define GNR_SCOPEEXIT_HPP
# pragma once

#include <utility>

/* This counts the number of args */
#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

/* This will let macros expand before concating them */
#ifndef PRIMITIVE_CAT
# define PRIMITIVE_CAT(x, y) x ## y
#endif // PRIMITIVE_CAT

#ifndef CAT
# define CAT(x, y) PRIMITIVE_CAT(x, y)
#endif // CAT

/* This will pop the last argument off */
#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define POP_LAST_1(x1)
#define POP_LAST_2(x1, x2) x1
#define POP_LAST_3(x1, x2, x3) x1, x2
#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3
#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4
#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5
#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6
#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7
#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8
#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9

/* This will return the last argument */
#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define LAST_1(x1) x1
#define LAST_2(x1, x2) x2
#define LAST_3(x1, x2, x3) x3
#define LAST_4(x1, x2, x3, x4) x4
#define LAST_5(x1, x2, x3, x4, x5) x5
#define LAST_6(x1, x2, x3, x4, x5, x6) x6
#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7
#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8
#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9
#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10

namespace gnr
{

template <typename F>
class scope_exit
{
  F f_;

public:
  explicit scope_exit(F&& f)
    noexcept(noexcept(F(std::move(f)))):
    f_(std::move(f))
  {
  }

  ~scope_exit() noexcept(noexcept(std::declval<F&>()())) { f_(); }

  scope_exit(scope_exit const&) = delete;
  scope_exit(scope_exit&&) = delete;
};

}

#define SCOPE_EXIT(...) auto const CAT(gnr_scope_exit_, __LINE__)\
  (gnr::scope_exit([POP_LAST(__VA_ARGS__)]()\
    noexcept(noexcept(LAST(__VA_ARGS__)))\
    { LAST(__VA_ARGS__); }))

#endif // GNR_SCOPEEXIT_HPP
<|endoftext|>


<commit_before>/*
 * StatefulFeatureFunction.cpp
 *
 *  Created on: 24 Oct 2015
 *      Author: hieu
 */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#include <boost/foreach.hpp>
#include "StatefulFeatureFunction.h"
#include "../Search/Hypothesis.h"

StatefulFeatureFunction::StatefulFeatureFunction(size_t startInd, const std::string &line)
:FeatureFunction(startInd, line)
{
}

StatefulFeatureFunction::~StatefulFeatureFunction() {
	// TODO Auto-generated destructor stub
}

void StatefulFeatureFunction::EvaluateWhenApplied(const ObjectPoolContiguous<Hypothesis*> &hypos) const
{
#ifdef __linux
	pthread_t thread;
	handle = pthread_self();

    int s;
    cpu_set_t cpusetOrig, cpuset;
    s = pthread_getaffinity_np(handle, sizeof(cpu_set_t), &cpusetOrig);

    CPU_ZERO(&cpuset);

    int core = handle % 8;
    core += 24;
    CPU_SET(core, &cpuset);

    s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpuset);

#endif

	for (size_t i = 0; i < hypos.size(); ++i) {
		Hypothesis *hypo = hypos.get(i);
		 hypo->EvaluateWhenApplied(*this);
	 }

#ifdef __linux

    s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpusetOrig);
#endif
}
<commit_msg>don't run LM on different CPU<commit_after>/*
 * StatefulFeatureFunction.cpp
 *
 *  Created on: 24 Oct 2015
 *      Author: hieu
 */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#include <boost/foreach.hpp>
#include "StatefulFeatureFunction.h"
#include "../Search/Hypothesis.h"

StatefulFeatureFunction::StatefulFeatureFunction(size_t startInd, const std::string &line)
:FeatureFunction(startInd, line)
{
}

StatefulFeatureFunction::~StatefulFeatureFunction() {
	// TODO Auto-generated destructor stub
}

void StatefulFeatureFunction::EvaluateWhenApplied(const ObjectPoolContiguous<Hypothesis*> &hypos) const
{
#ifdef __linux
  /*
	pthread_t handle;
	handle = pthread_self();

    int s;
    cpu_set_t cpusetOrig, cpuset;
    s = pthread_getaffinity_np(handle, sizeof(cpu_set_t), &cpusetOrig);

    CPU_ZERO(&cpuset);

    int core = handle % 8;
    core += 24;
    CPU_SET(core, &cpuset);

    s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
*/
#endif

	for (size_t i = 0; i < hypos.size(); ++i) {
		Hypothesis *hypo = hypos.get(i);
		 hypo->EvaluateWhenApplied(*this);
	 }

#ifdef __linux
	//    s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpusetOrig);
#endif
}
<|endoftext|>


<commit_before>#ifndef COMPASS_RT_X86_GNU_CPUID_H_

#include "detail/ct/detect_compiler.hpp"

#ifdef COMPASS_CT_COMP_GCC

#define COMPASS_RT_X86_GNU_CPUID_H_

#include "detail/tags.hpp"
#include "detail/definitions.hpp"
#include "detail/rt/x86/cpuid_common.hpp"

#include <array>
#include <cstdint>

namespace compass {

  namespace runtime {

    static std::array<std::uint32_t,4> cpuid(std::uint32_t in_eax = 0,
                                             std::uint32_t in_ebx = 0,
                                             std::uint32_t in_ecx = 0,
                                             std::uint32_t in_edx = 0){

      std::array<std::uint32_t,4> regs = {0,0,0,0};
      int cpuid_rvalue = __get_cpuid_count(in_eax,
                                     in_ecx,
                                     &regs[ct::eax],
                                     &regs[ct::ebx],
                                     &regs[ct::ecx],
                                     &regs[ct::edx]
        );

      if(cpuid_rvalue < 1){
        return {0,0,0,0};
      }

      return regs;

    }

  };

};
#endif /* COMPASS_CT_COMP_GCC */
#endif /* COMPASS_CT_GNU_IMPL_H_ */
<commit_msg>using correct initial values<commit_after>#ifndef COMPASS_RT_X86_GNU_CPUID_H_

#include "detail/ct/detect_compiler.hpp"

#ifdef COMPASS_CT_COMP_GCC

#define COMPASS_RT_X86_GNU_CPUID_H_

#include "detail/tags.hpp"
#include "detail/definitions.hpp"
#include "detail/rt/x86/cpuid_common.hpp"

#include <array>
#include <cstdint>

namespace compass {

  namespace runtime {

    static std::array<std::uint32_t,4> cpuid(std::uint32_t in_eax = 0,
                                             std::uint32_t in_ebx = 0,
                                             std::uint32_t in_ecx = 0,
                                             std::uint32_t in_edx = 0){

      std::array<std::uint32_t,4> regs = {in_eax,0,in_ecx,0};
      int cpuid_rvalue = __get_cpuid_count(in_eax,
                                     in_ecx,
                                     &regs[ct::eax],
                                     &regs[ct::ebx],
                                     &regs[ct::ecx],
                                     &regs[ct::edx]
        );

      if(cpuid_rvalue < 1){
        return {0,0,0,0};
      }

      return regs;

    }

  };

};
#endif /* COMPASS_CT_COMP_GCC */
#endif /* COMPASS_CT_GNU_IMPL_H_ */
<|endoftext|>


<commit_before>#include "memstat.h"
#include "utils.h"

CMemStat::CMemStat()
{
    initialized = FALSE;
    locator = NULL;
    service = NULL;
}

CMemStat::~CMemStat()
{
    service = NULL;
    locator = NULL;

    if (initialized == TRUE) {
        CoUninitialize();
    }
}

BOOL CMemStat::Init()
{
    HRESULT status  = S_OK;
    status = CoInitializeEx(NULL,
                            COINIT_MULTITHREADED);
    if (FAILED(status)) {
        PrintMessage("Cannot initialize COM");
        return status;
    }
    initialized = TRUE;

    status = CoInitializeSecurity(
                             NULL,
                             -1,
                             NULL,
                             NULL,
                             RPC_C_AUTHN_LEVEL_PKT,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE,
                             0
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot initialize security");
        return FALSE;
    }

    status = CoCreateInstance(
                             CLSID_WbemLocator,
                             NULL,
                             CLSCTX_INPROC_SERVER,
                             IID_IWbemLocator,
                             reinterpret_cast< void** >( &locator )
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot create instance");
        return FALSE;
    }

    status = locator->ConnectServer(
                             L"root\\cimv2",
                             NULL,
                             NULL,
                             0L,
                             0L,
                             NULL,
                             NULL,
                             &service
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot connect to wmi server");
        return FALSE;
    }

    status = CoSetProxyBlanket(service,
                             RPC_C_AUTHN_WINNT,
                             RPC_C_AUTHZ_NONE,
                             NULL,
                             RPC_C_AUTHN_LEVEL_CALL,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot set proxy blanket");
        return FALSE;
    }
    return TRUE;
}

BOOL  CMemStat::GetStatus(PBALLOON_STAT pStat)
{
    MEMORYSTATUS stat = {sizeof(stat)};
    CComPtr< IEnumWbemClassObject > enumerator;
    CComPtr< IWbemClassObject > memory;
    ULONG retcnt;
    _variant_t var_val;
    HRESULT status  = S_OK;
    UINT idx = 0;
    if(!pStat) {
        PrintMessage("Invalid pointer");
        return FALSE;
    }

    status = service->ExecQuery(
                             L"WQL",
                             L"SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory",
                             WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
                             NULL,
                             &enumerator
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot execute query");
        return FALSE;
    }

    while(enumerator)
    {
        status = enumerator->Next(
                             WBEM_INFINITE,
                             1L,
                             &memory,
                             &retcnt
                             );
        if (retcnt == 0) {
            break;
        }

        status = memory->Get(
                             L"PagesInputPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PagesInputPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_SWAP_IN;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get(
                             L"PagesOutputPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PagesOutputPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_SWAP_OUT;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get(
                             L"PageReadsPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PageReadsPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_MAJFLT;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get(
                             L"PageFaultsPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PageFaultsPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_MINFLT;
        pStat[idx].val = (long)var_val;
        idx++;

        GlobalMemoryStatus(&stat);

        pStat[idx].tag = VIRTIO_BALLOON_S_MEMFREE;
        pStat[idx].val = stat.dwAvailPhys;
        idx++;

        pStat[idx].tag = VIRTIO_BALLOON_S_MEMTOT;
        pStat[idx].val = stat.dwTotalPhys;
    }
    return TRUE;
}
<commit_msg>[balloon] Bug 1080319 - win8.1-32 could use 3G memory in one guest but stat-total-memory only shows 2G<commit_after>#include "memstat.h"
#include "utils.h"

CMemStat::CMemStat()
{
    initialized = FALSE;
    locator = NULL;
    service = NULL;
}

CMemStat::~CMemStat()
{
    service = NULL;
    locator = NULL;

    if (initialized == TRUE) {
        CoUninitialize();
    }
}

BOOL CMemStat::Init()
{
    HRESULT status  = S_OK;
    status = CoInitializeEx(NULL,
                            COINIT_MULTITHREADED);
    if (FAILED(status)) {
        PrintMessage("Cannot initialize COM");
        return status;
    }
    initialized = TRUE;

    status = CoInitializeSecurity(
                             NULL,
                             -1,
                             NULL,
                             NULL,
                             RPC_C_AUTHN_LEVEL_PKT,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE,
                             0
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot initialize security");
        return FALSE;
    }

    status = CoCreateInstance(
                             CLSID_WbemLocator,
                             NULL,
                             CLSCTX_INPROC_SERVER,
                             IID_IWbemLocator,
                             reinterpret_cast< void** >( &locator )
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot create instance");
        return FALSE;
    }

    status = locator->ConnectServer(
                             L"root\\cimv2",
                             NULL,
                             NULL,
                             0L,
                             0L,
                             NULL,
                             NULL,
                             &service
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot connect to wmi server");
        return FALSE;
    }

    status = CoSetProxyBlanket(service,
                             RPC_C_AUTHN_WINNT,
                             RPC_C_AUTHZ_NONE,
                             NULL,
                             RPC_C_AUTHN_LEVEL_CALL,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot set proxy blanket");
        return FALSE;
    }
    return TRUE;
}

BOOL  CMemStat::GetStatus(PBALLOON_STAT pStat)
{
    MEMORYSTATUSEX statex = {sizeof(statex)};
    CComPtr< IEnumWbemClassObject > enumerator;
    CComPtr< IWbemClassObject > memory;
    ULONG retcnt;
    _variant_t var_val;
    HRESULT status  = S_OK;
    UINT idx = 0;
    if(!pStat) {
        PrintMessage("Invalid pointer");
        return FALSE;
    }

    status = service->ExecQuery(
                             L"WQL",
                             L"SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory",
                             WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
                             NULL,
                             &enumerator
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot execute query");
        return FALSE;
    }

    while(enumerator)
    {
        status = enumerator->Next(
                             WBEM_INFINITE,
                             1L,
                             &memory,
                             &retcnt
                             );
        if (retcnt == 0) {
            break;
        }

        status = memory->Get(
                             L"PagesInputPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PagesInputPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_SWAP_IN;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get(
                             L"PagesOutputPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PagesOutputPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_SWAP_OUT;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get(
                             L"PageReadsPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PageReadsPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_MAJFLT;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get(
                             L"PageFaultsPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PageFaultsPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_MINFLT;
        pStat[idx].val = (long)var_val;
        idx++;

        GlobalMemoryStatusEx(&statex);

        pStat[idx].tag = VIRTIO_BALLOON_S_MEMFREE;
        pStat[idx].val = statex.ullAvailPhys;
        idx++;

        pStat[idx].tag = VIRTIO_BALLOON_S_MEMTOT;
        pStat[idx].val = statex.ullTotalPhys;
    }
    return TRUE;
}
<|endoftext|>