<commit_before>#include <QtCore>
#include <iostream>

#include <pHash.h>

static const QString TMPNAME = "xraytmp";   // name of temporary dir (usually below /tmp)
static const int THRESHOLD = 3;             // find at least x dupe snapshots to consider video duped
static const int KEYFRAMES = 5;             // how many snapshots (keyframes) to compare

// create snapshots from video file
void
createSnaps( const QString& file, const QString& tmpPath )
{
    QStringList args;
    args << "-sstep" << "1"                             // only output keyframes
         << "-nosound" << "-vo" << "jpeg"               // output as jpegs
         << "-ss" << "00:01:00"                         // start one minute into the video
         << "-frames" << QString::number( KEYFRAMES )   // output 10 frames
         << file;

    QProcess p;
    p.setWorkingDirectory( tmpPath );
    p.start( "mplayer", args );
    p.waitForFinished( 60000 );             // wait one minute at most
}

// create perceptual hash for snapshots
QHash<ulong64, int>
hashSnaps( const QString& path )
{
    QHash<ulong64, int> hashes;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( !fileInfo.fileName().endsWith( ".jpg" ) )
            continue;

        ulong64 hash;
        int err = ph_dct_imagehash(fileInfo.absoluteFilePath().toLocal8Bit(), hash);
        if ( err )
            continue;

        hashes.insertMulti( hash, i );

        // delete snapshot
        QFile::remove( fileInfo.absoluteFilePath() );
    }

    return hashes;
}

// finds similar hashes by hamming distance
QList <QPair <int, QString> >
closestHashes( QHash<ulong64, QPair<int, QString> >& hashes, const ulong64& searchKey )
{
    QList <QPair <int, QString> > res;

    for ( int i = 0; i < hashes.keys().count(); i++ )
    {
        ulong64 key = hashes.keys().at( i );
        if ( ph_hamming_distance( searchKey, key ) < 10 )
        {
            QPair<int, QString> pair = hashes.values().at( i );
            res << pair;
        }
    }

    return res;
}

void
scanDir( QHash<ulong64, QPair<int, QString> >& hashes, const QString& path )
{
//    qDebug() << "Scanning dir:" << path;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( fileInfo.isSymLink() )
            continue;
        if ( fileInfo.fileName().startsWith( "." ) )
            continue;

        if ( fileInfo.isDir() )
        {
            // scan recursively
            scanDir( hashes, fileInfo.absolutePath() + "/" + fileInfo.fileName() );
            continue;
        }

        if ( !fileInfo.fileName().endsWith(".wmv") && !fileInfo.fileName().endsWith(".avi") &&
             !fileInfo.fileName().endsWith(".mp4") && !fileInfo.fileName().endsWith(".mkv") &&
             !fileInfo.fileName().endsWith(".flv") && !fileInfo.fileName().endsWith(".mpg") &&
             !fileInfo.fileName().endsWith(".m4v") && !fileInfo.fileName().endsWith(".mov") &&
             !fileInfo.fileName().endsWith(".divx") && !fileInfo.fileName().endsWith(".mpeg") )
        {
            // only index videos
            continue;
        }

        std::cout << "Indexing \"" << qPrintable( fileInfo.absoluteFilePath() ) << "\" - size: " << fileInfo.size() << std::endl;

        // create snapshots
        const QString tmpPath = QDir::tempPath() + "/" + TMPNAME;
        createSnaps( fileInfo.absoluteFilePath(), tmpPath );
        // analyze and hash snapshots
        QHash<ulong64, int> hash = hashSnaps( tmpPath );

        QPair<int, QString> pair;       // snapshot #, filename
        QHash<QString, int> matches;    // filename, matches

        // go through all extracted snapshots and find dupes
        for ( int j = 0; j < hash.keys().count(); j++ )
        {
            ulong64 key = hash.keys().at( j );  // hash
            int value = hash.values().at( j );  // snapshot #

            {
                QList<QPair<int, QString> > res;    // snapshot #, filename

                // find closest snapshots by hamming distance
                res = closestHashes( hashes, key );
                for ( int x = 0; x < res.count(); x++ )
                {
                    pair = res.at( x );
                    if ( pair.second == fileInfo.absoluteFilePath() )
                    {
                        // ignore matches to self
                        continue;
                    }

                    // add/increment match count
                    if ( !matches.contains( pair.second ) )
                        matches[pair.second] = 1;
                    else
                        matches[pair.second] = matches[pair.second] + 1;
                }
            }

            // store hashes for future comparisons
            pair.first = value;
            pair.second = fileInfo.absoluteFilePath();
            hashes.insertMulti( key, pair );
        }

        for ( int y = 0; y < matches.keys().count(); y++ )
        {
            // threshold of matched snapshots to consider duped
            if ( matches.values().at( y ) >= THRESHOLD )
            {
                std::cout << "   --> Dupe of \"" << qPrintable( matches.keys().at( y ) ) << "\" - size: " << QFileInfo( matches.keys().at( y ) ).size()
                          << " (scores " << qMin( 10, matches.values().at( y ) ) << " out of " << KEYFRAMES << ")" << std::endl;
            }
        }
    }
}

int
main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    if ( app.arguments().count() < 2 )
    {
        std::cout << "Usage: xray /some/dir/full/of/videos" << std::endl;
        std::cout << "xray indexes video files by their perceptual hash and finds duplicates." << std::endl
                  << "This means files are not compared byte for byte, but by their visual content." << std::endl
                  << "It will/should find dupes of videos, even when they are encoded in different formats and resolutions." << std::endl;
        return 1;
    }

    QHash<ulong64, QPair<int, QString> > hashes;    // perceptual hash, pair<snapshot #, filename>

    QDir::temp().mkdir( TMPNAME );
    scanDir( hashes, app.arguments().at( 1 ) );
    QDir::temp().rmdir( TMPNAME );

    return 0;
}
<commit_msg>* Fixed output.<commit_after>#include <QtCore>
#include <iostream>

#include <pHash.h>

static const QString TMPNAME = "xraytmp";   // name of temporary dir (usually below /tmp)
static const int THRESHOLD = 3;             // find at least x dupe snapshots to consider video duped
static const int KEYFRAMES = 5;             // how many snapshots (keyframes) to compare

// create snapshots from video file
void
createSnaps( const QString& file, const QString& tmpPath )
{
    QStringList args;
    args << "-sstep" << "1"                             // only output keyframes
         << "-nosound" << "-vo" << "jpeg"               // output as jpegs
         << "-ss" << "00:01:00"                         // start one minute into the video
         << "-frames" << QString::number( KEYFRAMES )   // output 10 frames
         << file;

    QProcess p;
    p.setWorkingDirectory( tmpPath );
    p.start( "mplayer", args );
    p.waitForFinished( 60000 );             // wait one minute at most
}

// create perceptual hash for snapshots
QHash<ulong64, int>
hashSnaps( const QString& path )
{
    QHash<ulong64, int> hashes;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( !fileInfo.fileName().endsWith( ".jpg" ) )
            continue;

        ulong64 hash;
        int err = ph_dct_imagehash(fileInfo.absoluteFilePath().toLocal8Bit(), hash);
        if ( err )
            continue;

        hashes.insertMulti( hash, i );

        // delete snapshot
        QFile::remove( fileInfo.absoluteFilePath() );
    }

    return hashes;
}

// finds similar hashes by hamming distance
QList <QPair <int, QString> >
closestHashes( QHash<ulong64, QPair<int, QString> >& hashes, const ulong64& searchKey )
{
    QList <QPair <int, QString> > res;

    for ( int i = 0; i < hashes.keys().count(); i++ )
    {
        ulong64 key = hashes.keys().at( i );
        if ( ph_hamming_distance( searchKey, key ) < 10 )
        {
            QPair<int, QString> pair = hashes.values().at( i );
            res << pair;
        }
    }

    return res;
}

void
scanDir( QHash<ulong64, QPair<int, QString> >& hashes, const QString& path )
{
//    qDebug() << "Scanning dir:" << path;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( fileInfo.isSymLink() )
            continue;
        if ( fileInfo.fileName().startsWith( "." ) )
            continue;

        if ( fileInfo.isDir() )
        {
            // scan recursively
            scanDir( hashes, fileInfo.absolutePath() + "/" + fileInfo.fileName() );
            continue;
        }

        if ( !fileInfo.fileName().endsWith(".wmv") && !fileInfo.fileName().endsWith(".avi") &&
             !fileInfo.fileName().endsWith(".mp4") && !fileInfo.fileName().endsWith(".mkv") &&
             !fileInfo.fileName().endsWith(".flv") && !fileInfo.fileName().endsWith(".mpg") &&
             !fileInfo.fileName().endsWith(".m4v") && !fileInfo.fileName().endsWith(".mov") &&
             !fileInfo.fileName().endsWith(".divx") && !fileInfo.fileName().endsWith(".mpeg") )
        {
            // only index videos
            continue;
        }

        std::cout << "Indexing \"" << qPrintable( fileInfo.absoluteFilePath() ) << "\" - size: " << fileInfo.size() << std::endl;

        // create snapshots
        const QString tmpPath = QDir::tempPath() + "/" + TMPNAME;
        createSnaps( fileInfo.absoluteFilePath(), tmpPath );
        // analyze and hash snapshots
        QHash<ulong64, int> hash = hashSnaps( tmpPath );

        QPair<int, QString> pair;       // snapshot #, filename
        QHash<QString, int> matches;    // filename, matches

        // go through all extracted snapshots and find dupes
        for ( int j = 0; j < hash.keys().count(); j++ )
        {
            ulong64 key = hash.keys().at( j );  // hash
            int value = hash.values().at( j );  // snapshot #

            {
                QList<QPair<int, QString> > res;    // snapshot #, filename

                // find closest snapshots by hamming distance
                res = closestHashes( hashes, key );
                for ( int x = 0; x < res.count(); x++ )
                {
                    pair = res.at( x );
                    if ( pair.second == fileInfo.absoluteFilePath() )
                    {
                        // ignore matches to self
                        continue;
                    }

                    // add/increment match count
                    if ( !matches.contains( pair.second ) )
                        matches[pair.second] = 1;
                    else
                        matches[pair.second] = matches[pair.second] + 1;
                }
            }

            // store hashes for future comparisons
            pair.first = value;
            pair.second = fileInfo.absoluteFilePath();
            hashes.insertMulti( key, pair );
        }

        for ( int y = 0; y < matches.keys().count(); y++ )
        {
            // threshold of matched snapshots to consider duped
            if ( matches.values().at( y ) >= THRESHOLD )
            {
                std::cout << "   --> Dupe of \"" << qPrintable( matches.keys().at( y ) ) << "\" - size: " << QFileInfo( matches.keys().at( y ) ).size()
                          << " (scores " << qMin( KEYFRAMES, matches.values().at( y ) ) << " out of " << KEYFRAMES << ")" << std::endl;
            }
        }
    }
}

int
main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    if ( app.arguments().count() < 2 )
    {
        std::cout << "Usage: xray /some/dir/full/of/videos" << std::endl;
        std::cout << "xray indexes video files by their perceptual hash and finds duplicates." << std::endl
                  << "This means files are not compared byte for byte, but by their visual content." << std::endl
                  << "It will/should find dupes of videos, even when they are encoded in different formats and resolutions." << std::endl;
        return 1;
    }

    QHash<ulong64, QPair<int, QString> > hashes;    // perceptual hash, pair<snapshot #, filename>

    QDir::temp().mkdir( TMPNAME );
    scanDir( hashes, app.arguments().at( 1 ) );
    QDir::temp().rmdir( TMPNAME );

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <conio.h>
#include "input_data.h"
#include "calc_u.h"

class PairStream {
public:
    PairStream(std::ostream &f): file(f) {}

    template<typename T>
    PairStream& operator<<(const T &t)
    {
        std::cout << t;
        file << t;
        return *this;
    }

    std::ostream &file;
};

int main (void)
{
    std::cout << "Identification of reaction rate parameters in a combustion model\n\n";
    InputParam input_param = read_input_param();
    Config config = read_config();
    std::ifstream fe("flame_speed.txt");
    if (!fe) {
        std::cerr << "Can not open input file: flame_speed.txt\n";
        getch();
        exit(1);
    }
    int Dnum;
    fe >> Dnum;
    std::vector<real_t> phiD(Dnum), uD(Dnum), w(Dnum), Q_div_cp(Dnum);
    for (int j = 0; j < Dnum; ++j) {
        fe >> phiD[j] >> uD[j] >> w[j];
    }
    int Bnum;
    std::ifstream fb("burnt_temperature.txt");
    if (!fb) {
        std::cerr << "Can not open input file: burnt_temperature.txt\n";
        getch();
        exit(1);
    }
    fb >> Bnum;
    std::vector<real_t> phiB(Bnum), TB(Bnum);
    for (int k = 0; k < Bnum; ++k)
        fb >> phiB[k] >> TB[k];
    real_t z_val = calc_z(input_param.data);
    for (int j = 0; j < Dnum; ++j) {
        bool ok = false;
        for (int k = 0; k < Bnum - 1; ++k) {
            if (phiB[k] <= phiD[j] && phiD[j] <= phiB[k+1]) {
                real_t Tb = TB[k] + (TB[k+1] - TB[k]) * (phiD[j] - phiB[k]) / (phiB[k+1] - phiB[k]);
                Q_div_cp[j] = (Tb - input_param.data.T0)
                    * (phiD[j] + z_val) / fmin(phiD[j], 1);
                ok = true;
                break;
            }
        }
        if (!ok) {
            std::cerr << "Undefined adiabatic temperature: phi = " << phiD[j] << "\n";
            getch();
            exit(1);
        }
    }

    std::ofstream flog("log.txt");
    flog.precision(10);
    std::cout.precision(10);
    PairStream pstr(flog);

    calc_u_Data data0 = input_param.data;
    real_t lambda_init = input_param.lambda_init;
    real_t delta_A = config.delta_A;
    real_t delta_E_div_R = config.delta_E_div_R;
    real_t delta_alpha = config.delta_alpha;
    real_t delta_beta = config.delta_beta;
    real_t delta_n = config.delta_n;

    calc_u_Data data = data0;
    real_t A_cur, E_div_R_cur, alpha_cur, beta_cur, n_cur;
    real_t F;
    std::vector<real_t> u_cur(Dnum), u_new(Dnum);
    real_t lambda;

    const int PARAMS = 5;
    real_t *param_cur[PARAMS] = {&A_cur, &E_div_R_cur, &alpha_cur, &beta_cur, &n_cur};
    real_t *delta[PARAMS] = {&delta_A, &delta_E_div_R, &delta_alpha, &delta_beta, &delta_n};
    real_t *data_param[PARAMS] = {&data.A, &data.E_div_R, &data.alpha, &data.beta, &data.n};
    bool *optimize_param[PARAMS] = {&config.optimize_A, &config.optimize_E_div_R,
        &config.optimize_alpha, &config.optimize_beta, &config.optimize_n};
    std::string param_name[PARAMS] = {"A", "E/R", "alpha", "beta", "n"};

    lambda = lambda_init;
    A_cur = data0.A;
    E_div_R_cur = data0.E_div_R;
    alpha_cur = data0.alpha;
    beta_cur = data0.beta;
    n_cur = data0.n;
    F = 0;
    for (int j = 0; j < Dnum; ++j) {
        data.phi = phiD[j];
        data.Q_div_cp = Q_div_cp[j];
        for (int p = 0; p < PARAMS; ++p)
            *data_param[p] = *param_cur[p];
        u_cur[j] = calc_u(data, config);
        F += w[j] * pow(u_cur[j] - uD[j], 2);
    }
    for (int p = 0; p < PARAMS; ++p)
        pstr << param_name[p] << " = " << *param_cur[p] << "\n";
    pstr << "F = " << F << "\nlambda = " << lambda << "\n\n";

    //the number of subsequent iterations at which lambda was not changed
    int lambda_not_changed = 0;
    for (int iter = 1; iter <= input_param.steps; ++iter) {
        pstr << "iteration " << input_param.prev_iterations + iter << "\n";
        real_t F_deriv[PARAMS], F_deriv2[PARAMS];
        for (int p = 0; p < PARAMS; ++p) {
            F_deriv[p] = 0;
            F_deriv2[p] = 0;
        }
        for (int j = 0; j < Dnum; ++j) {
            for (int p = 0; p < PARAMS; ++p) {
                for (int q = 0; q < PARAMS; ++q) {
                    if (q == p)
                        *data_param[q] = *param_cur[q] + *delta[q];
                    else
                        *data_param[q] = *param_cur[q];
                }
                data.phi = phiD[j];
                data.Q_div_cp = Q_div_cp[j];
                real_t u_val = calc_u(data, config);
                // derivative with respect to p-th parameter
                real_t u_deriv = (u_val - u_cur[j]) / *delta[p];
                F_deriv[p] += w[j] * (u_cur[j] - uD[j]) * u_deriv;
                F_deriv2[p] += w[j] * pow(u_deriv, 2);
            }
        }
        for (int p = 0; p < PARAMS; ++p)
            flog << "F_" << param_name[p] << " = " << F_deriv[p] << "   ";
        flog << "\n";

        int lambda_decr = 0; // the number of subsequent decreases of lambda
        while (1) {
            real_t param_new[PARAMS];
            for (int p = 0; p < PARAMS; ++p) {
                if (*optimize_param[p])
                    param_new[p] = *param_cur[p] - lambda / F_deriv2[p] * F_deriv[p];
                else
                    param_new[p] = *param_cur[p];
            }
            real_t F_new = 0;
            for (int j = 0; j < Dnum; ++j) {
                data.phi = phiD[j];
                data.Q_div_cp = Q_div_cp[j];
                for (int p = 0; p < PARAMS; ++p)
                    *data_param[p] = param_new[p];
                u_new[j] = calc_u(data, config);
                F_new += w[j] * pow(u_new[j] - uD[j], 2);
            }
            if (F_new <= F) {
                for (int p = 0; p < PARAMS; ++p)
                    *param_cur[p] = param_new[p];
                F = F_new;
                for (int j = 0; j < Dnum; ++j)
                    u_cur[j] = u_new[j];
                break;
            }
            else {
                lambda_not_changed = -1;
                lambda /= 2;
                pstr << "lambda = " << lambda << "\n\n";
                ++lambda_decr;
                if (lambda_decr == config.lambda_decr_max) {
                    pstr << "lambda_decr_max achieved\n";
                    break;
                }
            }
        }
        if (lambda_decr == config.lambda_decr_max)
            break;
        for (int p = 0; p < PARAMS; ++p)
            pstr << param_name[p] << " = " << *param_cur[p] << "\n";
        pstr << "F = " << F << "\n\n";
        ++lambda_not_changed;
        if (lambda_not_changed == config.lambda_threshold) {
            lambda_not_changed = 0;
            lambda *= 2;
            pstr << "lambda increased = " << lambda << "\n\n";
        }
    } // for iter

    std::ofstream fout_u("plot.txt");
    for (int i = 0; i < Dnum; ++i)
        fout_u << phiD[i] << "   " << u_cur[i] << "   " << uD[i] << "\n";

    std::ofstream fout("output_param.txt");
    fout.precision(10);
    fout << "T0 = " << data0.T0 << "\n";
    fout << "D = " << data0.D << "\n";
    fout << "nu = " << data0.nu << "\n\n";
    for (int p = 0; p < PARAMS; ++p)
        fout << param_name[p] << " = " << *param_cur[p] << "\n";
    fout << "\nlambda = " << lambda << "\n";
    fout << "iterations = " << input_param.prev_iterations + input_param.steps << "\n\n";
    fout << "steps = " << input_param.steps;

    return 0;
}
<commit_msg>Add comments<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <conio.h>
#include "input_data.h"
#include "calc_u.h"

class PairStream {
public:
    PairStream(std::ostream &f): file(f) {}

    template<typename T>
    PairStream& operator<<(const T &t)
    {
        std::cout << t;
        file << t;
        return *this;
    }

    std::ostream &file;
};

int main (void)
{
    std::cout << "Identification of reaction rate parameters in a combustion model\n\n";
    //Read input data
    InputParam input_param = read_input_param();
    Config config = read_config();
    std::ifstream fe("flame_speed.txt");
    if (!fe) {
        std::cerr << "Can not open input file: flame_speed.txt\n";
        getch();
        exit(1);
    }
    int Dnum;
    fe >> Dnum;
    std::vector<real_t> phiD(Dnum), uD(Dnum), w(Dnum), Q_div_cp(Dnum);
    for (int j = 0; j < Dnum; ++j) {
        fe >> phiD[j] >> uD[j] >> w[j];
    }
    int Bnum;
    std::ifstream fb("burnt_temperature.txt");
    if (!fb) {
        std::cerr << "Can not open input file: burnt_temperature.txt\n";
        getch();
        exit(1);
    }
    fb >> Bnum;
    std::vector<real_t> phiB(Bnum), TB(Bnum);
    for (int k = 0; k < Bnum; ++k)
        fb >> phiB[k] >> TB[k];
    real_t z_val = calc_z(input_param.data);
    for (int j = 0; j < Dnum; ++j) {
        bool ok = false;
        for (int k = 0; k < Bnum - 1; ++k) {
            if (phiB[k] <= phiD[j] && phiD[j] <= phiB[k+1]) {
                // interpolate the temperature data
                real_t Tb = TB[k] + (TB[k+1] - TB[k]) * (phiD[j] - phiB[k]) / (phiB[k+1] - phiB[k]);
                Q_div_cp[j] = (Tb - input_param.data.T0) * (phiD[j] + z_val) / fmin(phiD[j], 1);
                ok = true;
                break;
            }
        }
        if (!ok) {
            std::cerr << "Undefined adiabatic temperature: phi = " << phiD[j] << "\n";
            getch();
            exit(1);
        }
    }

    std::ofstream flog("log.txt");
    flog.precision(10);
    std::cout.precision(10);
    PairStream pstr(flog);

    // data0 contains unchangeable data and initial guess
    calc_u_Data data0 = input_param.data;
    real_t lambda_init = input_param.lambda_init;
    // deltas are steps for numerical differentiation
    real_t delta_A = config.delta_A;
    real_t delta_E_div_R = config.delta_E_div_R;
    real_t delta_alpha = config.delta_alpha;
    real_t delta_beta = config.delta_beta;
    real_t delta_n = config.delta_n;

    // data contains data for current flame speed calculations
    calc_u_Data data = data0;
    // ..._cur are current guesses of parameters
    real_t A_cur, E_div_R_cur, alpha_cur, beta_cur, n_cur;
    // F_cur contains the value of the objective function corresponding to parameters ..._cur
    real_t F_cur;
    // u_cur contains the values of the flame speeds corresponding to parameters ..._cur
    std::vector<real_t> u_cur(Dnum), u_new(Dnum);
    real_t lambda;

    // Define arrays of pointers for convenient access to 5 parameters
    const int PARAMS = 5;
    real_t *param_cur[PARAMS] = {&A_cur, &E_div_R_cur, &alpha_cur, &beta_cur, &n_cur};
    real_t *delta[PARAMS] = {&delta_A, &delta_E_div_R, &delta_alpha, &delta_beta, &delta_n};
    real_t *data_param[PARAMS] = {&data.A, &data.E_div_R, &data.alpha, &data.beta, &data.n};
    bool *optimize_param[PARAMS] = {&config.optimize_A, &config.optimize_E_div_R,
        &config.optimize_alpha, &config.optimize_beta, &config.optimize_n};
    std::string param_name[PARAMS] = {"A", "E/R", "alpha", "beta", "n"};

    lambda = lambda_init;
    // Define the initial guess
    A_cur = data0.A;
    E_div_R_cur = data0.E_div_R;
    alpha_cur = data0.alpha;
    beta_cur = data0.beta;
    n_cur = data0.n;
    // Calculate the flame speeds u_cur and the objective function F_cur
    F_cur = 0;
    for (int j = 0; j < Dnum; ++j) {
        data.phi = phiD[j];
        data.Q_div_cp = Q_div_cp[j];
        for (int p = 0; p < PARAMS; ++p)
            *data_param[p] = *param_cur[p];
        u_cur[j] = calc_u(data, config);
        F_cur += w[j] * pow(u_cur[j] - uD[j], 2);
    }
    for (int p = 0; p < PARAMS; ++p)
        pstr << param_name[p] << " = " << *param_cur[p] << "\n";
    pstr << "F = " << F_cur << "\nlambda = " << lambda << "\n\n";

    //lambda_not_changed is the number of subsequent iterations at which lambda was not changed
    int lambda_not_changed = 0;
    for (int iter = 1; iter <= input_param.steps; ++iter) {
        pstr << "iteration " << input_param.prev_iterations + iter << "\n";
        // F_deriv and F_deriv2 are approximations of the first and the second derivatives of F
        real_t F_deriv[PARAMS], F_deriv2[PARAMS];
        for (int p = 0; p < PARAMS; ++p) {
            F_deriv[p] = 0;
            F_deriv2[p] = 0;
        }
        for (int j = 0; j < Dnum; ++j) {
            for (int p = 0; p < PARAMS; ++p) {
                if (!*optimize_param[p])
                    break;
                for (int q = 0; q < PARAMS; ++q) {
                    if (q == p)
                        *data_param[q] = *param_cur[q] + *delta[q];
                    else
                        *data_param[q] = *param_cur[q];
                }
                data.phi = phiD[j];
                data.Q_div_cp = Q_div_cp[j];
                real_t u_val = calc_u(data, config);
                // derivative with respect to p-th parameter
                real_t u_deriv = (u_val - u_cur[j]) / *delta[p];
                F_deriv[p] += w[j] * (u_cur[j] - uD[j]) * u_deriv;
                F_deriv2[p] += w[j] * pow(u_deriv, 2);
            }
        }
        for (int p = 0; p < PARAMS; ++p)
            flog << "F_" << param_name[p] << " = " << F_deriv[p] << "   ";
        flog << "\n";

        int lambda_decr = 0; // the number of subsequent decreases of lambda
        while (1) {
            // Calculate the new guess
            real_t param_new[PARAMS];
            for (int p = 0; p < PARAMS; ++p) {
                if (*optimize_param[p])
                    param_new[p] = *param_cur[p] - lambda / F_deriv2[p] * F_deriv[p];
                else
                    param_new[p] = *param_cur[p];
            }
            // Calculate the flame speeds and the objective function for the new guess
            real_t F_new = 0;
            for (int j = 0; j < Dnum; ++j) {
                data.phi = phiD[j];
                data.Q_div_cp = Q_div_cp[j];
                for (int p = 0; p < PARAMS; ++p)
                    *data_param[p] = param_new[p];
                u_new[j] = calc_u(data, config);
                F_new += w[j] * pow(u_new[j] - uD[j], 2);
            }
            if (F_new <= F_cur) {
                // Accept the new guess
                for (int p = 0; p < PARAMS; ++p)
                    *param_cur[p] = param_new[p];
                F_cur = F_new;
                for (int j = 0; j < Dnum; ++j)
                    u_cur[j] = u_new[j];
                break;
            }
            else {
                // Reject the new guess and decrease lambda
                lambda_not_changed = -1;
                lambda /= 2;
                pstr << "lambda = " << lambda << "\n\n";
                ++lambda_decr;
                if (lambda_decr == config.lambda_decr_max) {
                    pstr << "lambda_decr_max achieved\n";
                    break;
                }
            }
        }
        if (lambda_decr == config.lambda_decr_max)
            break;
        for (int p = 0; p < PARAMS; ++p)
            pstr << param_name[p] << " = " << *param_cur[p] << "\n";
        pstr << "F = " << F_cur << "\n\n";
        ++lambda_not_changed;
        // If lambda was not decreased for many times, then increase lambda;
        // if lambda was not increased for many times, then increase lambda again
        if (lambda_not_changed == config.lambda_threshold) {
            lambda_not_changed = 0;
            lambda *= 2;
            pstr << "lambda increased = " << lambda << "\n\n";
        }
    } // for iter

    // Print data for plotting
    std::ofstream fout_u("plot.txt");
    for (int i = 0; i < Dnum; ++i)
        fout_u << phiD[i] << "   " << u_cur[i] << "   " << uD[i] << "\n";

    // Print output parameters
    std::ofstream fout("output_param.txt");
    fout.precision(10);
    fout << "T0 = " << data0.T0 << "\n";
    fout << "D = " << data0.D << "\n";
    fout << "nu = " << data0.nu << "\n\n";
    for (int p = 0; p < PARAMS; ++p)
        fout << param_name[p] << " = " << *param_cur[p] << "\n";
    fout << "\nlambda = " << lambda << "\n";
    fout << "iterations = " << input_param.prev_iterations + input_param.steps << "\n\n";
    fout << "steps = " << input_param.steps;

    return 0;
}
<|endoftext|>


<commit_before>741ad582-2749-11e6-b5e5-e0f84713e7b8<commit_msg>master branch<commit_after>742ab378-2749-11e6-8821-e0f84713e7b8<|endoftext|>


<commit_before>#include <stdio.h>
#include <alsa/asoundlib.h>
#include "NoteEvaluator.h"

using namespace std;

unsigned char verbose = 0;
MidiEngine::NoteEvaluator* eng;

static void usage(void) {
	fprintf(stderr, "usage: RBHelper [options] <device>\n");
	fprintf(stderr, " options:\n");
	fprintf(stderr, "    -v: verbose mode\n");
	fprintf(stderr, "\n example:\n");
	fprintf(stderr, "    RBHelper /dev/midi1\n");
}

int confirm_device_is_streaming(int fd,unsigned char seconds){
	struct timeval timeout;
	fd_set set;
	//Set timeout structure
	timeout.tv_sec = seconds;
	timeout.tv_usec = 0;
	//Set add our fd to the set
	FD_ZERO(&set);
	FD_SET(fd, &set);
	//Expecting positive number if communication is happening
	return(select(fd + 1,&set,NULL,NULL,&timeout));
}

int closedevice(int fd){
	if (verbose) {
		fprintf(stderr, "Closing\n");
	}
	//Close our handle
	close(fd);
	//Return success
	return 1;
}

int main(int argc, char** argv) {

	int closedevice(int);
	int confirm_device_is_streaming(int,unsigned char);

	int i;
	unsigned char ch;
	char *device = NULL;
	int fd = -1;
	int status;
	char* message = NULL;

	//No args
	if (argc == 1) {
		usage();
		exit(1);
	}

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
			case 'v':
				verbose = 1;
				break;
			}
		}else{
			//Assume <device>
			if (i + 1 == argc) {
				device = argv[i];
				fd = open(device, O_RDWR);
				continue;
			}
		}
	}
	if (fd < 0) {
		fprintf(stderr, "open %s for input and output failed, aborting\n", device);
		exit(-1);
	}
	if(confirm_device_is_streaming(fd,3) < 1){
		ch = 10;
		fprintf(stderr, "Device not streaming data, waiting additional %d seconds...\n",ch);
		if(confirm_device_is_streaming(fd,ch) < 1){
			fprintf(stderr, "Device is not streaming data, aborting\n");
			closedevice(fd);
			exit(-1);
		}
	}
	if (verbose) {
		fprintf(stderr, "Using Device: %s\n", device);
	}
	//Create our engine and hand it control
	fprintf(stderr, "Press ctrl-c to stop\n");
	eng = new MidiEngine::NoteEvaluator();
	eng->set_fd(fd);
	eng->set_verbose(verbose);
	status = eng->process_input_as_loop(message);
	closedevice(fd);
	if(status == -1){
		//Error, display it
		fprintf(stderr, "Error: %s\n",message);
	}else{
		fprintf(stdout, "%s\n",message);
		if(status == 1){
			exit(0);
		}
	}
	exit(status);
}
<commit_msg>Build in debug mode (-d)<commit_after>#include <stdio.h>
#include <alsa/asoundlib.h>
#include "NoteEvaluator.h"

using namespace std;

unsigned char verbose = 0;
unsigned char debug = 0;
MidiEngine::NoteEvaluator* eng;

static void usage(void) {
	fprintf(stderr, "usage: RBHelper [options] <device>\n");
	fprintf(stderr, " options:\n");
	fprintf(stderr, "    -v: verbose mode\n");
	fprintf(stderr, "\n example:\n");
	fprintf(stderr, "    RBHelper /dev/midi1\n");
}

int confirm_device_is_streaming(int fd,unsigned char seconds){
	struct timeval timeout;
	fd_set set;
	//Set timeout structure
	timeout.tv_sec = seconds;
	timeout.tv_usec = 0;
	//Set add our fd to the set
	FD_ZERO(&set);
	FD_SET(fd, &set);
	//Expecting positive number if communication is happening
	return(select(fd + 1,&set,NULL,NULL,&timeout));
}

int closedevice(int fd){
	if (verbose) {
		fprintf(stderr, "Closing\n");
	}
	//Close our handle
	close(fd);
	//Return success
	return 1;
}

int main(int argc, char** argv) {

	int closedevice(int);
	int confirm_device_is_streaming(int,unsigned char);

	int i;
	unsigned char ch;
	char *device = NULL;
	int fd = -1;
	int status;
	char* message = NULL;

	//No args
	if (argc == 1) {
		usage();
		exit(1);
	}

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
			case 'v':
				verbose = 1;
				break;
			case 'd':
				debug = 1;
				break;
			}
		}else{
			//Assume <device>
			if (i + 1 == argc) {
				device = argv[i];
				continue;
			}
		}
	}
	eng = new MidiEngine::NoteEvaluator();
	eng->set_verbose(verbose);
	if(debug){
		eng->set_input(INPUT_SOURCE_DEBUG);
		fprintf(stderr, "***DEBUG MODE***\n");
	}else{
		fd = open(device, O_RDWR);
		if (fd < 0) {
			fprintf(stderr, "open %s for input and output failed, aborting\n", device);
			exit(-1);
		}
		if(confirm_device_is_streaming(fd,3) < 1){
			ch = 10;
			fprintf(stderr, "Device not streaming data, waiting additional %d seconds...\n",ch);
			if(confirm_device_is_streaming(fd,ch) < 1){
				fprintf(stderr, "Device is not streaming data, aborting\n");
				closedevice(fd);
				exit(-1);
			}
		}
		if (verbose) {
			fprintf(stderr, "Using Device: %s\n", device);
		}
		//Create our engine and hand it control
		fprintf(stderr, "Press ctrl-c to stop\n");
		eng->set_fd(fd);
	}
	status = eng->process_input_as_loop(message);
	if(!debug){
		closedevice(fd);
	}
	if(status == -1){
		//Error, display it
		fprintf(stderr, "Error: %s\n",message);
	}else{
		fprintf(stdout, "%s\n",message);
		if(status == 1){
			exit(0);
		}
	}
	exit(status);
}
<|endoftext|>


<commit_before>b1efda35-4b02-11e5-a4a6-28cfe9171a43<commit_msg>fixed bug<commit_after>b1fd4900-4b02-11e5-a421-28cfe9171a43<|endoftext|>


<commit_before>99b5e678-2747-11e6-b2df-e0f84713e7b8<commit_msg>Backup, rebase this later<commit_after>99c65417-2747-11e6-90bd-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
using namespace std;

void testVector();

int main()
{
	cout << "Hello, world!" << endl;
	return 0;
}

void testVector()
{
	std::vector<int> numbers;
	numbers.push_back(1);
	numbers.push_back(2);
	for (int i = 0; i < (int)numbers.size(); ++i)
		cout << i << endl;
}
<commit_msg>Test boost::lexical_cast<commit_after>#include <iostream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <sstream>
using namespace std;

void testVector();
void testLexicalCast();

int main()
{
	cout << "Hello, world!" << endl;

	testLexicalCast();
	return 0;
}

void testVector()
{
	std::vector<int> numbers;
	numbers.push_back(1);
	numbers.push_back(2);
	for (int i = 0; i < (int)numbers.size(); ++i)
		cout << i << endl;
}

void testLexicalCast()
{
	// »׳쳣
	//cout << boost::lexical_cast<int>("  123  ") << endl;
	//cout << boost::lexical_cast<int>("123  ") << endl;
	//cout << boost::lexical_cast<int>("12 3") << endl;
	//cout << boost::lexical_cast<int>("1 2 3") << endl;

	// ַ׳쳣
	//cout << boost::lexical_cast<int>("") << endl;

	// ֧ʮ
	//cout << boost::lexical_cast<int>("0x0362") << endl;

	// ʮַת 0xǰ׺п
	// C++11 е std::stoi <string>
	stringstream ss;
	ss << hex << "0x0362f"; // 13871
	int i;
	ss >> i;
	cout << i << endl;
}
<|endoftext|>


<commit_before>#include "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <cassert>

#ifdef PRINT_SPEC
void print_spec(int type, PowerSpec * PSpec, Cosmology & cosmo, std::string& filename, double Redshift, double UnitLength_in_cm);
#endif

int main(int argc, char **argv)
{
  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  //Read the config file
  SpbConfigParser config(argv[1]);
  //Cosmological parameters
  const auto Omega = config.PopValue<double>("Omega");
  const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
  const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
  const auto OmegaDM_2ndSpecies = config.PopValue<double>("OmegaDM_2ndSpecies");
  const auto HubbleParam = config.PopValue<double>("HubbleParam");
  //Which output format should we use. 3 is HDF5, 2 is Gadget 2. Default to 3.
  const auto ICFormat = config.PopValue<int>("ICFormat", 3);
  //How many output files to use in the set
  const auto NumFiles = config.PopValue<int>("NumFiles");
  //Parameters of the simulation box
  const auto Box = config.PopValue<double>("Box");
  const auto Redshift = config.PopValue<double>("Redshift");
  const double InitTime = 1 / (1 + Redshift);
  //Size of FFT
  const size_t Nmesh = config.PopValue<int>("Nmesh");
  //Unused unless CAMB spectrum
  const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
  const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
  const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
  //Output filenames
  const auto OutputDir = config.PopValue<std::string>("OutputDir");
  const auto FileBase = config.PopValue<std::string>("FileBase");
  //Random number seed
  const auto Seed = config.PopValue<int>("Seed");
  //Various boolean flags
  const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
  const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
  //Power spectrum to use. Default to CAMB
  const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
  //Is twolpt on?
  const auto twolpt = config.PopValue<bool>("TWOLPT",true);
  //Unit system
  const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
  const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
  const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
  const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
  //WDM options
  bool WDM_Vtherm_On = config.PopValue<bool>("WDM_On",false);
  WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false) && WDM_Vtherm_On;
  const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
  //Neutrino options
  //Enable particle neutrinos for type 2 particles. Does nothing unless NU_Vtherm is also true
  bool NU_Vtherm_On = config.PopValue<bool>("NU_On",false);
  //Add thermal velocities to type 2 particles if NU_On is also true.
  NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",false) && NU_Vtherm_On;
  //This triggers the use of neutrinos via an altered transfer function
  //Should be on only if you are faking neutrinos by combining them with the dark matter,
  //and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
  const auto combined_neutrinos = config.PopValue<bool>("NU_KSPACE",false);
  //Changes whether we have two heavy and one light neutrino or one heavy two light.
  const auto InvertedHierarchy = config.PopValue<bool>("InvertedHierarchy",false);
  //Total neutrino mass
  const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
  //Parameter for the Efstathiou power spectrum. Generally does nothing.
  const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
  //Needed if ReNormaliseInputSpectrum is on. Otherwise unused
  const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
  const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
  //Number of particles desired
  std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
  int CbRtNpart[6] = {0};
  CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
  CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
  CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
  for(int type=0; type<N_TYPES; ++type)
      npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];

  printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
  assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);

  if (Nmesh % 2 != 0){
    printf("Nmesh must be even or correct output is not guaranteed.\n");
    exit(1);
  }

  std::vector<std::string> unexpected = config.GetRemainingKeys();
  if(unexpected.size() > 0){
    std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
    for(auto unex: unexpected)
        std::cerr<<unex<<std::endl;
    exit(1);
  }
  DisplacementFields displace(Nmesh, Seed, Box, twolpt);
  /*Set particle numbers*/
  if(npart.sum() == 0)
          exit(1);
  //Initialise a power spectrum
  PowerSpec * PSpec;
  switch(WhichSpectrum)
  {
      case 1:
            PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
            break;
      case 2:
            PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, OmegaDM_2ndSpecies,InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
            break;
      default:
            PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
  }

  //Make a cosmology
  Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, InvertedHierarchy);
  //If normalisation or WDM are on, decorate the base power spectrum
  //to do that
  if (ReNormalizeInputSpectrum) {
      PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, cosmo.GrowthFactor(InitTime, 1.0), UnitLength_in_cm);
  }
  if(WDM_Vtherm_On)
      PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);

  std::string extension("");
  if (ICFormat > 4 || ICFormat < 2) {
          fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
          exit(1);
  }
  if (ICFormat == 3){
      printf("Outputting HDF5 ICs\n");
      extension=".hdf5";
  }

#ifdef NEUTRINO_PAIRS
  npart[NEUTRINO_TYPE] *= 2;
#endif //NEUTRINO_PAIRS
  GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BIGFILE
  if(ICFormat == 4)
     osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
  else
#endif
  osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
  /*Write headers*/
  gadget_header header = generate_header(npart, Omega, OmegaBaryon, OmegaDM_2ndSpecies, OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);

  //Generate regular particle grid
  part_grid Pgrid(CbRtNpart, header.mass, Box);

  if(osnap->WriteHeaders(header)) {
      fprintf(stderr, "Could not write headers to snapshot\n");
      exit(1);
  }

  int64_t FirstId=1;
  //Compute the factors to go from velocity to displacement
  const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
  const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
  //Only used if twolpt is on
  //This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
  const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
  printf("vel_prefac= %g  hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);

  for(int type=0; type<N_TYPE;type++){
      if(npart[type] == 0)
              continue;
      FermiDiracVel * therm_vels = NULL;
      //For WDM thermal velocities
      if(WDM_Vtherm_On && type == 1){
        const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
        therm_vels = new FermiDiracVel (wdm_vth);
        printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
      }
#ifdef NEUTRINOS
      //Neutrino thermal velocities
      if(NU_Vtherm_On && type == 2) {
          //Init structure for neutrino velocities
          const double v_th = NU_V0(Redshift, NU_PartMass_in_ev, UnitVelocity_in_cm_per_s);
          therm_vels = new FermiDiracVel (v_th);
          printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
      }
#endif //NEUTRINOS
      lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
      outdata.SetVelPrefac(vel_prefac, vel_prefac2);
      FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
      delete therm_vels;
#ifdef PRINT_SPEC
      std::string spec_filename = std::string(OutputDir)+std::string("/")+std::string("inputspec_")+std::string(FileBase)+std::string(".txt");
      print_spec(type, PSpec, cosmo, spec_filename, Redshift, UnitLength_in_cm);
#endif
  }

    delete PSpec;
  printf("Initial scale factor = %g\n", InitTime);

  return 0;
}
<commit_msg>Add calls to MPI init and finalize for bigfile<commit_after>#include "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <cassert>
#ifdef HAVE_BIGFILE
#include <mpi.h>
#endif

#ifdef PRINT_SPEC
void print_spec(int type, PowerSpec * PSpec, Cosmology & cosmo, std::string& filename, double Redshift, double UnitLength_in_cm);
#endif

int main(int argc, char **argv)
{
  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  //Read the config file
  SpbConfigParser config(argv[1]);
  //Cosmological parameters
  const auto Omega = config.PopValue<double>("Omega");
  const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
  const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
  const auto OmegaDM_2ndSpecies = config.PopValue<double>("OmegaDM_2ndSpecies");
  const auto HubbleParam = config.PopValue<double>("HubbleParam");
  //Which output format should we use. 3 is HDF5, 2 is Gadget 2. Default to 3.
  const auto ICFormat = config.PopValue<int>("ICFormat", 3);
  //How many output files to use in the set
  const auto NumFiles = config.PopValue<int>("NumFiles");
  //Parameters of the simulation box
  const auto Box = config.PopValue<double>("Box");
  const auto Redshift = config.PopValue<double>("Redshift");
  const double InitTime = 1 / (1 + Redshift);
  //Size of FFT
  const size_t Nmesh = config.PopValue<int>("Nmesh");
  //Unused unless CAMB spectrum
  const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
  const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
  const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
  //Output filenames
  const auto OutputDir = config.PopValue<std::string>("OutputDir");
  const auto FileBase = config.PopValue<std::string>("FileBase");
  //Random number seed
  const auto Seed = config.PopValue<int>("Seed");
  //Various boolean flags
  const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
  const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
  //Power spectrum to use. Default to CAMB
  const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
  //Is twolpt on?
  const auto twolpt = config.PopValue<bool>("TWOLPT",true);
  //Unit system
  const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
  const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
  const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
  const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
  //WDM options
  bool WDM_Vtherm_On = config.PopValue<bool>("WDM_On",false);
  WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false) && WDM_Vtherm_On;
  const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
  //Neutrino options
  //Enable particle neutrinos for type 2 particles. Does nothing unless NU_Vtherm is also true
  bool NU_Vtherm_On = config.PopValue<bool>("NU_On",false);
  //Add thermal velocities to type 2 particles if NU_On is also true.
  NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",false) && NU_Vtherm_On;
  //This triggers the use of neutrinos via an altered transfer function
  //Should be on only if you are faking neutrinos by combining them with the dark matter,
  //and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
  const auto combined_neutrinos = config.PopValue<bool>("NU_KSPACE",false);
  //Changes whether we have two heavy and one light neutrino or one heavy two light.
  const auto InvertedHierarchy = config.PopValue<bool>("InvertedHierarchy",false);
  //Total neutrino mass
  const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
  //Parameter for the Efstathiou power spectrum. Generally does nothing.
  const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
  //Needed if ReNormaliseInputSpectrum is on. Otherwise unused
  const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
  const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
  //Number of particles desired
  std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
  int CbRtNpart[6] = {0};
  CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
  CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
  CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
  for(int type=0; type<N_TYPES; ++type)
      npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];

  printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
  assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);

  if (Nmesh % 2 != 0){
    printf("Nmesh must be even or correct output is not guaranteed.\n");
    exit(1);
  }

  std::vector<std::string> unexpected = config.GetRemainingKeys();
  if(unexpected.size() > 0){
    std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
    for(auto unex: unexpected)
        std::cerr<<unex<<std::endl;
    exit(1);
  }
  DisplacementFields displace(Nmesh, Seed, Box, twolpt);
  /*Set particle numbers*/
  if(npart.sum() == 0)
          exit(1);
  //Initialise a power spectrum
  PowerSpec * PSpec;
  switch(WhichSpectrum)
  {
      case 1:
            PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
            break;
      case 2:
            PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, OmegaDM_2ndSpecies,InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
            break;
      default:
            PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
  }

  //Make a cosmology
  Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, InvertedHierarchy);
  //If normalisation or WDM are on, decorate the base power spectrum
  //to do that
  if (ReNormalizeInputSpectrum) {
      PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, cosmo.GrowthFactor(InitTime, 1.0), UnitLength_in_cm);
  }
  if(WDM_Vtherm_On)
      PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);

  std::string extension("");
  if (ICFormat > 4 || ICFormat < 2) {
          fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
          exit(1);
  }
  if (ICFormat == 3){
      printf("Outputting HDF5 ICs\n");
      extension=".hdf5";
  }
#ifdef NEUTRINO_PAIRS
  npart[NEUTRINO_TYPE] *= 2;
#endif //NEUTRINO_PAIRS
  GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BIGFILE
  if(ICFormat == 4) {
     MPI_Init(&argc, &argv);
     osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
  }
  else
#endif
  osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
  /*Write headers*/
  gadget_header header = generate_header(npart, Omega, OmegaBaryon, OmegaDM_2ndSpecies, OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);

  //Generate regular particle grid
  part_grid Pgrid(CbRtNpart, header.mass, Box);

  if(osnap->WriteHeaders(header)) {
      fprintf(stderr, "Could not write headers to snapshot\n");
      exit(1);
  }

  int64_t FirstId=1;
  //Compute the factors to go from velocity to displacement
  const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
  const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
  //Only used if twolpt is on
  //This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
  const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
  printf("vel_prefac= %g  hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);

  for(int type=0; type<N_TYPE;type++){
      if(npart[type] == 0)
              continue;
      FermiDiracVel * therm_vels = NULL;
      //For WDM thermal velocities
      if(WDM_Vtherm_On && type == 1){
        const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
        therm_vels = new FermiDiracVel (wdm_vth);
        printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
      }
#ifdef NEUTRINOS
      //Neutrino thermal velocities
      if(NU_Vtherm_On && type == 2) {
          //Init structure for neutrino velocities
          const double v_th = NU_V0(Redshift, NU_PartMass_in_ev, UnitVelocity_in_cm_per_s);
          therm_vels = new FermiDiracVel (v_th);
          printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
      }
#endif //NEUTRINOS
      lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
      outdata.SetVelPrefac(vel_prefac, vel_prefac2);
      FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
      delete therm_vels;
#ifdef PRINT_SPEC
      std::string spec_filename = std::string(OutputDir)+std::string("/")+std::string("inputspec_")+std::string(FileBase)+std::string(".txt");
      print_spec(type, PSpec, cosmo, spec_filename, Redshift, UnitLength_in_cm);
#endif
  }

    delete PSpec;
  printf("Initial scale factor = %g\n", InitTime);

#ifdef HAVE_BIGFILE
  MPI_Finalize();
#endif
  return 0;
}
<|endoftext|>


<commit_before>#include <string>
#include "pongobj.h"
#include "pongstring.h"
#include "sysio.h"
#include "pongproperties.h"
#include "pongtrigger.h"

using pong::PString;
using pong::PRect;
using pong::PKProperty;
using pong::PGProperty;
using pong::PGTrigger;
using pong::sys::SOut;
using pong::sys::SInInitial;
using pong::sys::SCurrent;

int main(void)
{
	SOut sout;
	SInInitial sin;
	SCurrent scurrent;
	int keyinput;

	int terminal_length = sout.GetLength();
	int terminal_width = sout.GetWidth();
	PRect boundary_outer = PRect(1, 1, terminal_length, terminal_width, PColor(PColor::BLUE));
	PRect boundary_inner = PRect(2, 2, terminal_length-2, terminal_width-2, PColor(PColor::BLACK));
	PRect lcursor = PRect(5, terminal_width/2-4, 1, 8, PColor(PColor::DEFAULT));
	PRect rcursor = PRect(terminal_length-5, terminal_width/2-4, 1, 8, PColor(PColor::DEFAULT));
	PRect ball = PRect(1, 1, terminal_length/2, terminal_width/2, PColor(PColor::DEFAULT));
	PRect prectbuf;

	bool signal_terminate = false;
	PGTrigger gmode_event = PGTrigger::LOBBY;
	PGTrigger gmode_stage = PGTrigger::NONE;

	while (signal_terminate != true)
	{
		sin >> keyinput;

		if (gmode_event == PGTrigger(PGTrigger::LOBBY))
		{
			for (; gmode_stage != PGTrigger(PGTrigger::LOBBY); gmode_stage.Set(PGTrigger::LOBBY))
			{
				sout.Clear();

				boundary_outer.SetColor(PColor(PColor::BLUE));
				sout << boundary_outer << boundary_inner;

				sout << PString("Pipong - Classic Table Tennis Game", PColor(PColor::CYAN), Point(terminal_length/2-16, terminal_width/2-2));
				sout << PString("Press 's' to start game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2));
				sout << PString("Press 'q' to exit the game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2+1));
			}

			if (keyinput == PKProperty::PSTART)
				gmode_event.Set(PGTrigger::INGAME);
			else if (keyinput == PKProperty::PEXIT)
				signal_terminate = true;
		}
		else if (gmode_event == PGTrigger(PGTrigger::INGAME))
		{
			for (; gmode_stage != PGTrigger(PGTrigger::INGAME); gmode_stage.Set(PGTrigger::INGAME))
			{
				sout.Clear();

				boundary_outer.SetColor(PColor(PColor::BROWN));
				sout << boundary_outer << boundary_inner << lcursor << rcursor;
		}

			if (keyinput == PKProperty::PP1UP)
			{
				prectbuf = lcursor;
				prectbuf.SetColor(PColor(PColor::BLACK));
				lcursor.SetSypos((lcursor.GetSpoint()).GetYpos() - 1);
				if (boundary_inner.CheckInclude(lcursor) == false)
					lcursor.SetSypos((lcursor.GetSpoint()).GetYpos() + 1);

				sout << prectbuf << lcursor;
			}
			else if (keyinput == PKProperty::PP1DOWN)
			{

			}
			else if (keyinput == PKProperty::PP2UP)
			{

			}
			else if (keyinput == PKProperty::PP2DOWN)
			{

			}
			else if (keyinput == PKProperty::PEXIT)
				gmode_event.Set(PGTrigger::LOBBY);
		}

		scurrent.DelayMsec(PGProperty::PCYCLEDELAY);
	}
	return 0;
}
<commit_msg>Add lcursor init<commit_after>#include <string>
#include "pongobj.h"
#include "pongstring.h"
#include "sysio.h"
#include "pongproperties.h"
#include "pongtrigger.h"

using pong::PString;
using pong::PRect;
using pong::PKProperty;
using pong::PGProperty;
using pong::PGTrigger;
using pong::sys::SOut;
using pong::sys::SInInitial;
using pong::sys::SCurrent;

int main(void)
{
	SOut sout;
	SInInitial sin;
	SCurrent scurrent;
	int keyinput;

	int terminal_length = sout.GetLength();
	int terminal_width = sout.GetWidth();
	PRect boundary_outer = PRect(1, 1, terminal_length, terminal_width, PColor(PColor::BLUE));
	PRect boundary_inner = PRect(2, 2, terminal_length-2, terminal_width-2, PColor(PColor::BLACK));
	PRect lcursor = PRect(5, terminal_width/2-4, 1, 8, PColor(PColor::DEFAULT));
	PRect rcursor = PRect(terminal_length-5, terminal_width/2-4, 1, 8, PColor(PColor::DEFAULT));
	PRect ball = PRect(1, 1, terminal_length/2, terminal_width/2, PColor(PColor::DEFAULT));
	PRect prectbuf;

	bool signal_terminate = false;
	PGTrigger gmode_event = PGTrigger::LOBBY;
	PGTrigger gmode_stage = PGTrigger::NONE;

	while (signal_terminate != true)
	{
		sin >> keyinput;

		if (gmode_event == PGTrigger(PGTrigger::LOBBY))
		{
			for (; gmode_stage != PGTrigger(PGTrigger::LOBBY); gmode_stage.Set(PGTrigger::LOBBY))
			{
				sout.Clear();

				boundary_outer.SetColor(PColor(PColor::BLUE));
				sout << boundary_outer << boundary_inner;

				sout << PString("Pipong - Classic Table Tennis Game", PColor(PColor::CYAN), Point(terminal_length/2-16, terminal_width/2-2));
				sout << PString("Press 's' to start game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2));
				sout << PString("Press 'q' to exit the game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2+1));
			}

			if (keyinput == PKProperty::PSTART)
				gmode_event.Set(PGTrigger::INGAME);
			else if (keyinput == PKProperty::PEXIT)
				signal_terminate = true;
		}
		else if (gmode_event == PGTrigger(PGTrigger::INGAME))
		{
			for (; gmode_stage != PGTrigger(PGTrigger::INGAME); gmode_stage.Set(PGTrigger::INGAME))
			{
				sout.Clear();

				boundary_outer.SetColor(PColor(PColor::BROWN));
				lcursor.SetSypos(terminal_width/2-4);
				rcursor.SetSypos(terminal_width/2-4);
				sout << boundary_outer << boundary_inner << lcursor << rcursor;
		}

			if (keyinput == PKProperty::PP1UP)
			{
				prectbuf = lcursor;
				prectbuf.SetColor(PColor(PColor::BLACK));
				lcursor.SetSypos((lcursor.GetSpoint()).GetYpos() - 1);
				if (boundary_inner.CheckInclude(lcursor) == false)
					lcursor.SetSypos((lcursor.GetSpoint()).GetYpos() + 1);

				sout << prectbuf << lcursor;
			}
			else if (keyinput == PKProperty::PP1DOWN)
			{

			}
			else if (keyinput == PKProperty::PP2UP)
			{

			}
			else if (keyinput == PKProperty::PP2DOWN)
			{

			}
			else if (keyinput == PKProperty::PEXIT)
				gmode_event.Set(PGTrigger::LOBBY);
		}

		scurrent.DelayMsec(PGProperty::PCYCLEDELAY);
	}
	return 0;
}
<|endoftext|>


<commit_before>87479002-2749-11e6-860b-e0f84713e7b8<commit_msg>Nope, didn't work, now it does<commit_after>8750ca3d-2749-11e6-b864-e0f84713e7b8<|endoftext|>


<commit_before>#include<iostream>
#include<utility>
#include<boost/graph/adjacency_list.hpp>

using namespace boost;

int main(){
  typedef adjacency_list<vecS,
                         vecS,
                         directedS,
                         property<vertex_name_t, std::string> >  Graph;
  typedef graph_traits<Graph>::vertex_descriptor                 Vertex;
  typedef std::pair<graph_traits<Graph>::edge_descriptor, bool>  Edge;

  std::map<std::string, Vertex> word_map;

  Graph g(0);
  Vertex u = add_vertex(g);
  Vertex v = add_vertex(g);
  Edge e = add_edge(u, v, g);
  std::cout << num_vertices(g) << " " << num_edges(g) << std::endl;

  return 0;
}
<commit_msg>added example of getting input and adding vertices for words<commit_after>#include<iostream>
#include<utility>
#include<vector>

#include<boost/graph/adjacency_list.hpp>

#include<boost/algorithm/string/classification.hpp>
#include<boost/algorithm/string/split.hpp>

using namespace boost;

int main(){
  typedef adjacency_list<vecS,
                         vecS,
                         directedS,
                         property<vertex_name_t, std::string> >  Graph;
  typedef graph_traits<Graph>::vertex_descriptor                 Vertex;
  typedef std::pair<graph_traits<Graph>::edge_descriptor, bool>  Edge;

  Graph g(0);

  property_map<Graph, vertex_name_t>::type vertex_words = get(vertex_name, g);
  std::map<std::string, Vertex> word_map; //use to quickly find vertices

  //get input and split on space
  std::string input;
  std::getline(std::cin, input);
  std::vector<std::string> words;
  split(words, input, is_any_of(" "));

  for(auto s : words){
    if(word_map.find(s) == word_map.end()) { //currenty no vertex for word s
      //add vertex to graph, add string property, add string=>vertex to word_map
      Vertex v = add_vertex(g);
      vertex_words[v] = s;
      word_map.emplace(s, v);
    }
  }

  std::cout << num_vertices(g) << " " << num_edges(g) << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>9ed32b05-4b02-11e5-9855-28cfe9171a43<commit_msg>roselyn broke it<commit_after>9ee2bccc-4b02-11e5-8934-28cfe9171a43<|endoftext|>


<commit_before>/*
The MIT License

Copyright (c) 2010 Bryan Ivory bivory+textureatlas@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

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

#include "png.hpp"
#include "TexturePacker.h"
#include "tclap/CmdLine.h"

#define VERSION "2010.09.05"

class TextureInfo
   {
   public:
      TextureInfo(int index, std::string path)
         : idx(index), im_path(path)
      {
      im = png::image<png::rgb_pixel>(im_path);
      }

      int index() const { return idx; }
      std::string path() const { return im_path; }
      png::image< png::rgb_pixel > image() const { return im; }

      void writeTo(png::image< png::rgb_pixel > &outimage,
                   const size_t offset_x, const size_t offset_y,
                   const size_t out_width, const size_t out_height,
                   const bool rotate90)
      {
      for(size_t out_y = offset_y; out_y < (offset_y + out_height); ++out_y)
         {
         for(size_t out_x = offset_x; out_x < (offset_x + out_width); ++out_x)
            {
            if (rotate90)
               {
               size_t rot_y = im.get_height() - (out_x - offset_x) - 1;
               size_t rot_x = (out_y - offset_y);
               png::rgb_pixel px = im[rot_y][rot_x];
               outimage[out_y][out_x] = px;
               }
            else
               {
               size_t rot_y = out_y - offset_y;
               size_t rot_x = out_x - offset_x;
               outimage[out_y][out_x] = im[rot_y][rot_x];
               }
            }
         }
      }

   private:
      const int                     idx;
      std::string                   im_path;
      png::image< png::rgb_pixel >  im;
   };

int
main(int argc, char* argv[])
{
std::string                out_atlas_name = "";
size_t                     out_atlas_height = 0;
size_t                     out_atlas_width = 0;
std::vector<std::string>   image_names;

// Read in the command line arguements
try
   {
   TCLAP::CmdLine cmd("Creates a texture atlas from a list of PNG files.",
                      ' ', VERSION, true);

   // Output atlas file name
   TCLAP::ValueArg<std::string> out_atlas_name_arg(
         "o","out_name",
         "Output atlas image's file name.",
         false, "out_atlas", "string");
   cmd.add(out_atlas_name_arg);

   // Output atlas image dimensions
   TCLAP::ValueArg<size_t> out_atlas_width_arg(
         "x","out_width",
         "Maximum output atlas image's width.",
         false, 1024, "pixels");
   cmd.add(out_atlas_width_arg);

   TCLAP::ValueArg<size_t> out_atlas_height_arg(
         "y","out_height",
         "Maximum output atlas image's height.",
         false, 1024, "pixels");
   cmd.add(out_atlas_height_arg);

   // Input image files
   TCLAP::UnlabeledMultiArg<std::string> in_image_names_arg(
         "in_names", "List of the image filenames.", true, "PNG file path");
   cmd.add(in_image_names_arg);

   cmd.parse(argc, argv);
   out_atlas_name = out_atlas_name_arg.getValue();
   out_atlas_width = out_atlas_width_arg.getValue();
   out_atlas_height = out_atlas_height_arg.getValue();
   image_names = in_image_names_arg.getValue();
   }
catch (TCLAP::ArgException &e)
   {
   std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl;
   return 1;
   }

// Create the ist of texture to pack
std::list<TextureInfo> images;
for(size_t idx = 0; idx < image_names.size(); idx++)
   {
   try
      {
      TextureInfo ti(idx, image_names[idx]);
      images.push_back(ti);
      }
   catch(png::std_error &e)
      {
      std::cerr << e.what() << std::endl;
      return 1;
      }
   }

// Pack the textures
TEXTURE_PACKER::TexturePacker *tp = TEXTURE_PACKER::createTexturePacker();
tp->setTextureCount(images.size());
for(
 std::list<TextureInfo>::iterator images_iter = images.begin();
 images_iter != images.end();
 images_iter++)
   {
   png::image<png::rgb_pixel> im = images_iter->image();
   tp->addTexture(im.get_width(), im.get_height());
   }
// Force power of two, no pixel border
int act_out_atlas_width = 0;
int act_out_atlas_height = 0;
size_t unused_area = tp->packTextures(act_out_atlas_width,
      act_out_atlas_height, true, false);

std::cout << "Packed " << image_names.size() << " with "
         << unused_area << " unused area: "
         << "Width (" << act_out_atlas_width
         << ") x Height (" << act_out_atlas_height << ")"
         << std::endl;

// Output the packed textures
png::image<png::rgb_pixel> out_image(act_out_atlas_width, act_out_atlas_height);
for(
 std::list<TextureInfo>::iterator images_iter = images.begin();
 images_iter != images.end();
 images_iter++)
   {
   int x, y, width, height;
   bool rot90;

   rot90 = tp->getTextureLocation(images_iter->index(), x, y, width, height);
   std::cout   << images_iter->path() << " => "
               << "rotated 90: " << rot90 << " "
               << "x: " << x << " "
               << "y: " << y << " "
               << "width: " << width << " "
               << "height: " << height << " "
               << std::endl;

   images_iter->writeTo(out_image, x, y, width, height, rot90);
   }
out_image.write(out_atlas_name + ".png");

return 0;
}

<commit_msg>Individual images are now checked to ensure no image is larger than that maximum atlus width and height<commit_after>/*
The MIT License

Copyright (c) 2010 Bryan Ivory bivory+textureatlas@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

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

#include "png.hpp"
#include "TexturePacker.h"
#include "tclap/CmdLine.h"

#define VERSION "2010.09.05"

class TextureInfo
   {
   public:
      TextureInfo(int index, std::string path)
         : idx(index), im_path(path)
      {
      im = png::image<png::rgb_pixel>(im_path);
      }

      int index() const { return idx; }
      std::string path() const { return im_path; }
      png::image< png::rgb_pixel > image() const { return im; }

      void writeTo(png::image< png::rgb_pixel > &outimage,
                   const size_t offset_x, const size_t offset_y,
                   const size_t out_width, const size_t out_height,
                   const bool rotate90)
      {
      for(size_t out_y = offset_y; out_y < (offset_y + out_height); ++out_y)
         {
         for(size_t out_x = offset_x; out_x < (offset_x + out_width); ++out_x)
            {
            if (rotate90)
               {
               size_t rot_y = im.get_height() - (out_x - offset_x) - 1;
               size_t rot_x = (out_y - offset_y);
               png::rgb_pixel px = im[rot_y][rot_x];
               outimage[out_y][out_x] = px;
               }
            else
               {
               size_t rot_y = out_y - offset_y;
               size_t rot_x = out_x - offset_x;
               outimage[out_y][out_x] = im[rot_y][rot_x];
               }
            }
         }
      }

   private:
      const int                     idx;
      std::string                   im_path;
      png::image< png::rgb_pixel >  im;
   };

int
main(int argc, char* argv[])
{
std::string                out_atlas_name = "";
size_t                     out_atlas_height = 0;
size_t                     out_atlas_width = 0;
std::vector<std::string>   image_names;

// Read in the command line arguements
try
   {
   TCLAP::CmdLine cmd("Creates a texture atlas from a list of PNG files.",
                      ' ', VERSION, true);

   // Output atlas file name
   TCLAP::ValueArg<std::string> out_atlas_name_arg(
         "o","out_name",
         "Output atlas image's file name.",
         false, "out_atlas", "string");
   cmd.add(out_atlas_name_arg);

   // Output atlas image dimensions
   TCLAP::ValueArg<size_t> out_atlas_width_arg(
         "x","out_width",
         "Maximum output atlas image's width.",
         false, 1024, "pixels");
   cmd.add(out_atlas_width_arg);

   TCLAP::ValueArg<size_t> out_atlas_height_arg(
         "y","out_height",
         "Maximum output atlas image's height.",
         false, 1024, "pixels");
   cmd.add(out_atlas_height_arg);

   // Input image files
   TCLAP::UnlabeledMultiArg<std::string> in_image_names_arg(
         "in_names", "List of the image filenames.", true, "PNG file path");
   cmd.add(in_image_names_arg);

   cmd.parse(argc, argv);
   out_atlas_name = out_atlas_name_arg.getValue();
   out_atlas_width = out_atlas_width_arg.getValue();
   out_atlas_height = out_atlas_height_arg.getValue();
   image_names = in_image_names_arg.getValue();
   }
catch (TCLAP::ArgException &e)
   {
   std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl;
   return 1;
   }

// Create the ist of texture to pack
std::list<TextureInfo> images;
for(size_t idx = 0; idx < image_names.size(); idx++)
   {
   try
      {
      TextureInfo ti(idx, image_names[idx]);
      if (ti.image().get_width() > out_atlas_width ||
          ti.image().get_height() > out_atlas_height)
         {
         std::cerr << "Error: " << ti.path() << " is too big!" << std::endl;
         std::cerr << "Image dimensions: " <<  ti.image().get_width()
            << " x " << ti.image().get_height() << std::endl;
         std::cerr << "Atlas dimensions: " <<  out_atlas_width
            << " x " << out_atlas_height << std::endl;
         return 1;
         }

      images.push_back(ti);
      }
   catch(png::std_error &e)
      {
      std::cerr << e.what() << std::endl;
      return 1;
      }
   }

// Pack the textures
TEXTURE_PACKER::TexturePacker *tp = TEXTURE_PACKER::createTexturePacker();
tp->setTextureCount(images.size());
for(
 std::list<TextureInfo>::iterator images_iter = images.begin();
 images_iter != images.end();
 images_iter++)
   {
   png::image<png::rgb_pixel> im = images_iter->image();
   tp->addTexture(im.get_width(), im.get_height());
   }
// Force power of two, no pixel border
int act_out_atlas_width = 0;
int act_out_atlas_height = 0;
size_t unused_area = tp->packTextures(act_out_atlas_width,
      act_out_atlas_height, true, false);

std::cout << "Packed " << image_names.size() << " with "
         << unused_area << " unused area: "
         << "Width (" << act_out_atlas_width
         << ") x Height (" << act_out_atlas_height << ")"
         << std::endl;

// Output the packed textures
png::image<png::rgb_pixel> out_image(act_out_atlas_width, act_out_atlas_height);
for(
 std::list<TextureInfo>::iterator images_iter = images.begin();
 images_iter != images.end();
 images_iter++)
   {
   int x, y, width, height;
   bool rot90;

   rot90 = tp->getTextureLocation(images_iter->index(), x, y, width, height);
   std::cout   << images_iter->path() << " => "
               << "rotated 90: " << rot90 << " "
               << "x: " << x << " "
               << "y: " << y << " "
               << "width: " << width << " "
               << "height: " << height << " "
               << std::endl;

   images_iter->writeTo(out_image, x, y, width, height, rot90);
   }
out_image.write(out_atlas_name + ".png");

return 0;
}

<|endoftext|>


<commit_before>70546c4a-4b02-11e5-ae81-28cfe9171a43<commit_msg>My Backup<commit_after>7060c0e3-4b02-11e5-9e02-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <ctime>
#include <cmath>
#include <chrono>
#include <thread>

#include <omp.h>

#include <sys/time.h>

const int NUM_THREADS = 10;

struct Node {
    int val;
    Node *left;
    Node *right;
};

Node *generateTree(int depth, int val) {
    Node *node = new Node();
    node->val = val;

    if (depth > 0) {
        node->left = generateTree(depth - 1, val);
        node->right = generateTree(depth - 1, val);
    }
    return node;
}

void destroyTree(Node *node) {
    if (node != NULL) {
        destroyTree(node->left);
        destroyTree(node->right);
        delete node;
    }
}

void openMpSum(Node *node, int *sum) {
    if (node != NULL) {
        int left_sum = 0, right_sum = 0;
        #pragma omp task shared(left_sum)
        openMpSum(node->left, &left_sum);
        #pragma omp task shared(right_sum)
        openMpSum(node->right, &right_sum);
        #pragma omp taskwait

        std::this_thread::sleep_for(std::chrono::milliseconds(node->val));
        *sum = node->val + left_sum + right_sum;
        return;
    }
    *sum = 0;
}

void parallelSum(Node *node, int depth, int *sum) {
    if (node != NULL) {
        int left_sum = 0, right_sum = 0;
        if (std::pow(2, depth) < NUM_THREADS) {
            std::thread left (parallelSum, node->left, depth + 1, &left_sum);
            parallelSum(node->right, depth + 1, &right_sum);
            left.join();
        } else {
            parallelSum(node->left, depth + 1, &left_sum);
            parallelSum(node->right, depth + 1, &right_sum);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(node->val));
        *sum = node->val + left_sum + right_sum;
        return;
    }
    *sum = 0;;
}

double wall_time_ms() {
    struct timeval time;
    gettimeofday(&time, NULL);
    return 1000.0 * time.tv_sec + 0.001 * time.tv_usec;
}

int main() {

    omp_set_num_threads(NUM_THREADS);

    int depth, val;

    std::cout << "Tree depth: " << std::endl;
    std::cin >> depth;
    std::cout << "Node value: " << std::endl;
    std::cin >> val;

    double start = wall_time_ms();
    Node *root = generateTree(depth, val);
    double elapsed = wall_time_ms() - start;

    std::cout << "Tree generated with depth " << depth
        << " and node value " << val
        << " in " << elapsed << " ms" << std::endl;

    start = wall_time_ms();
    int sum;
    #pragma omp parallel
    {
        #pragma omp single
        openMpSum(root, &sum);
    }
    elapsed = wall_time_ms() - start;

    std::cout << "openMpSum completed in " << elapsed << "ms" << std::endl;
    std::cout << "Sum: " << sum << std::endl;

    start = wall_time_ms();
    parallelSum(root, 0, &sum);
    elapsed = wall_time_ms() - start;

    std::cout << "parallelSum completed in " << elapsed << "ms" << std::endl;
    std::cout << "Sum: " << sum << std::endl;

    destroyTree(root);

    std::cout << "Tree destroyed." << std::endl;
}
<commit_msg>Added sequential benchmark<commit_after>#include <iostream>
#include <string>
#include <ctime>
#include <cmath>
#include <chrono>
#include <thread>

#include <omp.h>

#include <sys/time.h>

const int NUM_THREADS = 10;

struct Node {
    int val;
    Node *left;
    Node *right;
};

Node *generateTree(int depth, int val) {
    Node *node = new Node();
    node->val = val;

    if (depth > 0) {
        node->left = generateTree(depth - 1, val);
        node->right = generateTree(depth - 1, val);
    }
    return node;
}

void destroyTree(Node *node) {
    if (node != NULL) {
        destroyTree(node->left);
        destroyTree(node->right);
        delete node;
    }
}

void compute(int val) {
    // perform some linear time operation
    std::this_thread::sleep_for(std::chrono::milliseconds(val));
}

int sequentialSum(Node *node) {
    if (node == NULL) {
        return 0;
    }
    int sum_children = sequentialSum(node->left) + sequentialSum(node->right);
    compute(node->val);
    return node->val + sum_children;
}

void openMpSum(Node *node, int *sum) {
    if (node == NULL) {
        *sum = 0;
        return;
    }
    int left_sum = 0, right_sum = 0;

    #pragma omp task shared(left_sum)   // parallelize one subtree
    openMpSum(node->left, &left_sum);

    openMpSum(node->right, &right_sum);
    #pragma omp taskwait

    compute(node->val);
    *sum = node->val + left_sum + right_sum;
}

void parallelSum(Node *node, int depth, int *sum) {
    if (node == NULL) {
        *sum = 0;
        return;
    }
    int left_sum = 0, right_sum = 0;
    if (std::pow(2, depth) < NUM_THREADS) {
        std::thread left (parallelSum, node->left, depth + 1, &left_sum);
        parallelSum(node->right, depth + 1, &right_sum);
        left.join();
    } else {
        parallelSum(node->left, depth + 1, &left_sum);
        parallelSum(node->right, depth + 1, &right_sum);
    }
    compute(node->val);
    *sum = node->val + left_sum + right_sum;
}

double wall_time_ms() {
    struct timeval time;
    gettimeofday(&time, NULL);
    return 1000.0 * time.tv_sec + 0.001 * time.tv_usec;
}

int main(int argc, char **argv) {

    omp_set_num_threads(NUM_THREADS);

    int depth, val;

    std::cout << "Tree depth: " << std::endl;
    std::cin >> depth;
    std::cout << "Node value: " << std::endl;
    std::cin >> val;

    double start = wall_time_ms();
    Node *root = generateTree(depth, val);
    double elapsed = wall_time_ms() - start;

    std::cout << "Tree generated with depth " << depth
        << " and node value " << val
        << " in " << elapsed << " ms" << std::endl;

    start = wall_time_ms();
    int sum = sequentialSum(root);
    elapsed = wall_time_ms() - start;

    std::cout << "sequentialSum completed in " << elapsed << "ms" << std::endl;
    std::cout << "Sum: " << sum << std::endl;

    start = wall_time_ms();
    #pragma omp parallel
    {
        #pragma omp single
        openMpSum(root, &sum);
    }
    elapsed = wall_time_ms() - start;

    std::cout << "openMpSum completed in " << elapsed << "ms" << std::endl;
    std::cout << "Sum: " << sum << std::endl;

    start = wall_time_ms();
    parallelSum(root, 0, &sum);
    elapsed = wall_time_ms() - start;

    std::cout << "parallelSum completed in " << elapsed << "ms" << std::endl;
    std::cout << "Sum: " << sum << std::endl;

    destroyTree(root);

    std::cout << "Tree destroyed." << std::endl;
}
<|endoftext|>


<commit_before>96b38c17-4b02-11e5-8e7b-28cfe9171a43<commit_msg>The previous fix has been fixed<commit_after>96c2082e-4b02-11e5-b672-28cfe9171a43<|endoftext|>


<commit_before>#include "main.h"
#include <chrono>

int num_rows;
int num_cols;
int num_nonzeros;

std::chrono::duration<double> blaze_time;
std::chrono::duration<double> eigen_time;
std::chrono::duration<double> vexcl_time;

std::chrono::time_point<std::chrono::system_clock> start, end;

int main(int argc, char* argv[]) {

  blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix("D_T_" + std::string(argv[1]) + ".dat");
  blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix("M_invD_" + std::string(argv[1]) + ".dat");

  blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector("gamma_" + std::string(argv[1]) + ".dat");
  blaze::DynamicVector<double> rhs_blaze = BlazeTest::ConvertVector("b_" + std::string(argv[1]) + ".dat");

  CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
  CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);

  // Compute some metrics and print them out
  num_rows = D_T_blaze.rows();
  num_cols = D_T_blaze.columns();
  num_nonzeros = D_T_blaze.nonZeros();
  printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
  printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n",
         num_rows,
         num_cols,
         num_nonzeros,
         M_invD_blaze.rows(),
         M_invD_blaze.columns(),
         M_invD_blaze.nonZeros(),
         gamma_blaze.size(),
         rhs_blaze.size(),
         ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) * sizeof(double)) / GFLOP);

  //  printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
  //  printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
  //  printf("gamma: size: %d\n", gamma_blaze.size());
  //  printf("b: size: %d\n", rhs_blaze.size());

  BlazeTest blaze_test;
  start = std::chrono::system_clock::now();
  blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
  end = std::chrono::system_clock::now();
  blaze_time = end - start;

  VexCLTest vexcl_test;
  vexcl_test.CreateContext();
  vexcl_test.WarmUp();

  vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
  vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
  vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma_blaze);

  start = std::chrono::system_clock::now();
  vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
  end = std::chrono::system_clock::now();
  vexcl_time = end - start;

  //
  //  // Two Spmv each with 2*nnz operations
  //  uint operations = 2 * 2 * num_nonzeros;
  //  uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
  //
  //  double blaze_single = blaze_time / RUNS;
  //  double vex_single = vexcl_time / RUNS;
  //  double eig_single = eigen_time / RUNS;
  //
  //  printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
  //  printf("%f, %f, %f, %f, %f, %f, %f\n",
  //         blaze_single,
  //         vex_single,
  //         blaze_single / vex_single,
  //         operations / blaze_single / GFLOP,
  //         operations / vex_single / GFLOP,
  //         moved / blaze_single / GFLOP,
  //         moved / vex_single / GFLOP);

  //  printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
  //  printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
  //  printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
  //  printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
  //
  //  printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
  //  printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);

  return 0;
}
<commit_msg>Output Timing<commit_after>#include "main.h"
#include <chrono>

int num_rows;
int num_cols;
int num_nonzeros;

std::chrono::duration<double> blaze_time;
std::chrono::duration<double> eigen_time;
std::chrono::duration<double> vexcl_time;

std::chrono::time_point<std::chrono::system_clock> start, end;

int main(int argc, char* argv[]) {

  blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix("D_T_" + std::string(argv[1]) + ".dat");
  blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix("M_invD_" + std::string(argv[1]) + ".dat");

  blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector("gamma_" + std::string(argv[1]) + ".dat");
  blaze::DynamicVector<double> rhs_blaze = BlazeTest::ConvertVector("b_" + std::string(argv[1]) + ".dat");

  CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
  CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);

  // Compute some metrics and print them out
  num_rows = D_T_blaze.rows();
  num_cols = D_T_blaze.columns();
  num_nonzeros = D_T_blaze.nonZeros();
  printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
  printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n",
         num_rows,
         num_cols,
         num_nonzeros,
         M_invD_blaze.rows(),
         M_invD_blaze.columns(),
         M_invD_blaze.nonZeros(),
         gamma_blaze.size(),
         rhs_blaze.size(),
         ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) * sizeof(double)) / GFLOP);

  //  printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
  //  printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
  //  printf("gamma: size: %d\n", gamma_blaze.size());
  //  printf("b: size: %d\n", rhs_blaze.size());

  BlazeTest blaze_test;
  start = std::chrono::system_clock::now();
  blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
  end = std::chrono::system_clock::now();
  blaze_time = end - start;

  VexCLTest vexcl_test;
  vexcl_test.CreateContext();
  vexcl_test.WarmUp();

  vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
  vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
  vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma_blaze);

  start = std::chrono::system_clock::now();
  vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
  end = std::chrono::system_clock::now();
  vexcl_time = end - start;

  // Two Spmv each with 2*nnz operations
  uint operations = 2 * 2 * num_nonzeros;
  uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);

  double blaze_single = blaze_time.count() / RUNS;
  double vex_single = vexcl_time.count() / RUNS;
  //double eig_single = eigen_time.count() / RUNS;

  printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
  printf("%f, %f, %f, %f, %f, %f, %f\n",
         blaze_single,
         vex_single,
         blaze_single / vex_single,
         operations / blaze_single / GFLOP,
         operations / vex_single / GFLOP,
         moved / blaze_single / GFLOP,
         moved / vex_single / GFLOP);
//
//  printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
//  printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
//  printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
//  printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
//
//  printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
//  printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);

  return 0;
}
<|endoftext|>


<commit_before>#include "window.h"
#include <stdlib.h> //this is just for random numbers
#include <iostream>

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Window window;
    window.show();

    time_t timer;
    time(&timer);
    int start = timer;
    int old_time = 0;

    while(!window.close){
    	time(&timer);//timer is unneccessary, I just needed test cases that didn't go by at the speed of light
    	if(timer-start!= old_time and window.graph){
    		old_time=timer-start;
    		int num = rand() % 1000;
            window.addPoint(1,-num); //this gives graph 1 a negative min value which is nice for testing
            for(int i=1;i<=24;i++){
    		  window.addPoint(i,num);
            }
    	}

    	app.processEvents();
    }

    return 0;
}
<commit_msg>Improved comment in main<commit_after>#include "window.h"
#include <stdlib.h> //this is just for random numbers
#include <iostream>

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Window window;
    window.show();

    time_t timer;
    time(&timer);
    int start = timer;
    int old_time = 0;

    while(!window.close){
    	time(&timer); //Most of this code is just to add test values for the gui
    	if(timer-start!= old_time and window.graph){
    		old_time=timer-start;
    		int num = rand() % 1000;
            window.addPoint(1,-num); //this gives graph 1 a negative min value which is nice for testing
            for(int i=1;i<=24;i++){
    		  window.addPoint(i,num);
            }
    	}

    	app.processEvents();
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <QDesktopWidget>
#include <QWidget>
#include <QIcon>
#include <QString>
#include <string>
#include "mainWindow.hpp"
#include "keyboard.hpp"
#include <iostream>
#include <unistd.h>

int main(int argc, char *argv[])
{
    QString layoutFile = "assets/default.keys";
    int opt;
    int min = 2, max = 5;
    std::string usage = keyBoard::Usage().toUtf8().constData();
    while ( (opt = getopt(argc, argv, "hvk:b:t:")) != -1 ) {
        switch ( opt ) {
            case 'v':
                std::cout << "CPPiano v1.02 - Licensed under GNU/LGPL v3.0" << std::endl;
                return 0;
                break;
            case 'h':
                std::cout << "Usage:" << std::endl;
                std::cout << usage << std::endl;
                return 0;
                break;
            case 'k':
                layoutFile = QString::fromStdString(optarg);
                break;
            case 'l':
                min =  atoi(optarg);
                break;
            case 'u':
                max = atoi(optarg);
                break;
            case '?':
                return 1;
                break;
        }
    }
    QApplication app(argc, argv);
    mainWindow * window = new mainWindow;

    QDesktopWidget * dt = QApplication::desktop();

    keyBoard * kb = new keyBoard(window);

    window->setMainWidget<keyBoard*>(kb);

    kb->generate(min,max,layoutFile);

    kb->draw();
    // set Height and Width of the main window
    int wHeight = 20 + (window->getToolbars() * 30) + ((keyBoard*)(window->getMainWidget()))->height();
    int wWidth  = ((keyBoard*)(window->getMainWidget()))->width();

    //centering the window
    int x,y;
    x = ( dt->width() - wWidth ) / 2;
    y = ( dt->height() - wHeight ) / 2;

    window->resize(wWidth, wHeight);
    window->move( x , y );
    window->setWindowTitle("CPPiano");
    window->setWindowIcon(QIcon("assets/icon.png"));
    window->draw()->show();

    return app.exec();
}
<commit_msg>Fixed cli options<commit_after>#include <QDesktopWidget>
#include <QWidget>
#include <QIcon>
#include <QString>
#include <string>
#include "mainWindow.hpp"
#include "keyboard.hpp"
#include <iostream>
#include <unistd.h>

int main(int argc, char *argv[])
{
    QString layoutFile = "assets/default.keys";
    int opt;
    int min = 2, max = 5;
    std::string usage = keyBoard::Usage().toUtf8().constData();
    while ( (opt = getopt(argc, argv, "hvk:b:t:")) != -1 ) {
        switch ( opt ) {
            case 'v':
                std::cout << "CPPiano v1.02 - Licensed under GNU/LGPL v3.0" << std::endl;
                return 0;
                break;
            case 'h':
                std::cout << "Usage:" << std::endl;
                std::cout << usage << std::endl;
                return 0;
                break;
            case 'k':
                layoutFile = QString::fromStdString(optarg);
                break;
            case 'b':
                min =  atoi(optarg);
                break;
            case 't':
                max = atoi(optarg);
                break;
            case '?':
                return 1;
                break;
        }
    }
    QApplication app(argc, argv);
    mainWindow * window = new mainWindow;

    QDesktopWidget * dt = QApplication::desktop();

    keyBoard * kb = new keyBoard(window);

    window->setMainWidget<keyBoard*>(kb);

    kb->generate(min,max,layoutFile);

    kb->draw();
    // set Height and Width of the main window
    int wHeight = 20 + (window->getToolbars() * 30) + ((keyBoard*)(window->getMainWidget()))->height();
    int wWidth  = ((keyBoard*)(window->getMainWidget()))->width();

    //centering the window
    int x,y;
    x = ( dt->width() - wWidth ) / 2;
    y = ( dt->height() - wHeight ) / 2;

    window->resize(wWidth, wHeight);
    window->move( x , y );
    window->setWindowTitle("CPPiano");
    window->setWindowIcon(QIcon("assets/icon.png"));
    window->draw()->show();

    return app.exec();
}
<|endoftext|>