<commit_before>// ==========================================================================
//                                 bam_stats
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Read a BAM file and collect statistics on the alignments therein.
// ==========================================================================

#include <iostream>

#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h>      // For printing SeqAn Strings.

#include <seqan/stream.h>
#include <seqan/bam_io.h>
#include <seqan/misc/misc_cmdparser.h>

#if SEQAN_HAS_ZLIB

using namespace seqan;

enum Format
{
    FORMAT_AUTO,
    FORMAT_SAM,
    FORMAT_BAM
};

struct Options
{
    bool showHelp;
    bool showVersion;
    unsigned verbosity;
    CharString refFile;
    CharString inFile;
    Format inFormat;

    Options()
    {
        showHelp = false;
        showVersion = false;
        verbosity = 1;
        inFormat = FORMAT_AUTO;
    }
};

void
setupCommandLineParser(CommandLineParser & parser, Options const & options)
{
    addVersionLine(parser, "1.0");

    addTitleLine(parser, "*************");
    addTitleLine(parser, "* bam_stats *");
    addTitleLine(parser, "*************");
    addTitleLine(parser, "");
    addTitleLine(parser, "BAM Statistics.");
    addTitleLine(parser, "");
    addTitleLine(parser, "Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>");

    addUsageLine(parser, "bam_stats [OPTIONS] REF.fasta ALIGN.bam");

	addSection(parser, "General Options");
    addOption(parser, CommandLineOption("v", "verbose", "Enable verbose mode (show steps).", OptionType::Bool));
    addOption(parser, CommandLineOption("vv", "very-verbose", "Enable very verbose mode (show SAM lines and actual aligments).", OptionType::Bool));

	addSection(parser, "Input Specification");
    addOption(parser, CommandLineOption("i", "input-file", "Path to input, '-' for stdin.", OptionType::String, options.inFile));
    addOption(parser, CommandLineOption("S", "input-sam", "Input file is SAM (default: auto).", OptionType::Bool, options.inFormat == FORMAT_SAM));
    addOption(parser, CommandLineOption("B", "input-bam", "Input file is BAM (default: auto).", OptionType::Bool, options.inFormat == FORMAT_BAM));

    requiredArguments(parser, 2);
}

int parseCommandLineAndCheck(Options & options,
                             CommandLineParser & parser,
                             int argc,
                             char const ** argv)
{
    bool stop = !parse(parser, argc, argv);
    if (stop)
        return 1;
    if (isSetLong(parser, "help"))
    {
        options.showHelp = true;
        return 0;
    }
    if (isSetLong(parser, "version"))
    {
        options.showVersion = true;
        return 0;
    }

    if (isSetLong(parser, "verbose"))
        options.verbosity = 2;
    if (isSetLong(parser, "very-verbose"))
        options.verbosity = 3;

    getOptionValueLong(parser, "input-file", options.inFile);
    if (isSetLong(parser, "input-sam"))
        options.inFormat = FORMAT_SAM;
    if (isSetLong(parser, "input-bam"))
        options.inFormat = FORMAT_BAM;

    options.refFile = getArgumentValue(parser, 0);
    options.inFile = getArgumentValue(parser, 1);

	return 0;
}

struct Stats
{
    __uint64 numRecords;
    __uint64 alignedRecords;
    String<unsigned> editDistanceHisto;
    String<unsigned> mismatchHisto;
    String<unsigned> insertHisto;
    String<unsigned> deletionHisto;

    Stats() : numRecords(0), alignedRecords(0)
    {}
};

template <typename TStreamOrReader, typename TSeqString, typename TSpec, typename TFormat>
int doWork(TStreamOrReader & reader, StringSet<TSeqString, TSpec> & seqs, Options const & options, TFormat const & tag)
{
    StringSet<CharString> refNames;
    NameStoreCache<StringSet<CharString> > refNamesCache(refNames);
    BamIOContext<StringSet<CharString> > context(refNames, refNamesCache);

    // Read header.
    BamHeader header;
    if (options.verbosity >= 2)
        std::cerr << "Reading header" << std::endl;
    if (readRecord(header, context, reader, tag) != 0)
    {
        std::cerr << "Could not read header!" << std::endl;
        return 1;
    }

    Stats stats;

    // Read alignments.
    BamAlignmentRecord record;
    if (options.verbosity >= 2)
        std::cerr << "Reading alignments" << std::endl;
    Align<Dna5String> align;
    while (!atEnd(reader))
    {
        // Read alignment record.
        if (readRecord(record, context, reader, tag) != 0)
        {
            std::cerr << "Could not read alignment!" << std::endl;
            return 1;
        }
        if (options.verbosity >= 3)
            write2(std::cerr, record, context, Sam());

        // Now, do something with it ;)
        stats.numRecords += 1;  // One more record.
        stats.alignedRecords += !hasFlagUnmapped(record);
        // Compute alignment.
        if (record.rId != -1 && record.rId < static_cast<int>(length(seqs)))
        {
            bamRecordToAlignment(align, seqs[record.rId], record);
            if (options.verbosity >= 3)
                std::cerr << align << std::endl;
            typedef Align<Dna5String>             TAlign;
            typedef typename Row<TAlign>::Type    TRow;
            typedef typename Iterator<TRow>::Type TRowIter;
            unsigned editDistance = 0;
            unsigned posRead = 0;
            for (TRowIter it0 = begin(row(align, 0)), it1 = begin(row(align, 1)); !atEnd(it0); goNext(it0), goNext(it1))
            {
                if (isGap(it0) && isGap(it1))
                    continue;
                if (isGap(it0) || isGap(it1))
                {
                    if (isGap(it0))
                    {
                        unsigned len = length(stats.insertHisto);
                        resize(stats.insertHisto, std::max(len, posRead + 1), 0);
                        stats.insertHisto[posRead] += 1;
                        posRead += 1;
                    }
                    else
                    {
                        unsigned len = length(stats.deletionHisto);
                        resize(stats.deletionHisto, std::max(len, posRead + 1), 0);
                        stats.deletionHisto[posRead] += 1;
                    }
                    editDistance += 1;
                    continue;
                }
                if (*it0 != *it1)
                {
                    unsigned len = length(stats.mismatchHisto);
                    resize(stats.mismatchHisto, std::max(len, posRead + 1), 0);
                    stats.mismatchHisto[posRead] += 1;
                    editDistance += 1;
                }
                posRead += 1;
            }
            if (options.verbosity >= 3)
                std::cerr << "edit distance: " << editDistance << std::endl;
            unsigned len = length(stats.editDistanceHisto);
            resize(stats.editDistanceHisto, std::max(len, editDistance + 1), 0);
            stats.editDistanceHisto[editDistance] += 1;
        }
    }

    // Print results.
    std::cerr << "RESULTS\n\n";
    std::cerr << "num records     \t" << stats.numRecords << std::endl;
    std::cerr << "aligned records \t" << stats.alignedRecords << std::endl;
    std::cerr << "aligned record %\t" << 100.0 * stats.alignedRecords / stats.numRecords << std::endl;
    std::cerr << "distance histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.editDistanceHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.editDistanceHisto[i] << std::endl;
    std::cerr << "mismatch histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.mismatchHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.mismatchHisto[i] << std::endl;
    std::cerr << "insertion histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.insertHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.insertHisto[i] << std::endl;
    std::cerr << "deletion histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.deletionHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.deletionHisto[i] << std::endl;

    return 0;
}

int main(int argc, char const ** argv)
{
    using namespace seqan;

    // -----------------------------------------------------------------------
    // Handle Command Line
    // -----------------------------------------------------------------------

    // Setup command line parser.
    CommandLineParser parser;
    Options options;
    setupCommandLineParser(parser, options);

    // Then, parse the command line and handle the cases where help display
    // is requested or erroneous parameters were given.
    int res = parseCommandLineAndCheck(options, parser, argc, argv);
    if (res != 0)
        return 1;
    if (options.showHelp || options.showVersion)
        return 0;

    // -----------------------------------------------------------------------
    // Guess format.
    // -----------------------------------------------------------------------

    if (options.inFormat == FORMAT_AUTO)
    {
        std::ifstream guessIn(toCString(options.inFile), std::ios::binary | std::ios::in);
        if (!guessIn.good())
        {
            std::cerr << "Could not open " << options.inFile << std::endl;
            return 1;
        }
        CharString magic;
        resize(magic, 2);
        guessIn.read(&magic[0], 2);
        if (magic != "\x1f\x8b")  // Is not gzip-compressed.
            options.inFormat = FORMAT_SAM;
        else
            options.inFormat = FORMAT_BAM;
    }

    // -----------------------------------------------------------------------
    // Do Work.
    // -----------------------------------------------------------------------

    // Read reference.
    if (options.verbosity >= 2)
        std::cerr << "Reading references from " << options.refFile << std::endl;
    StringSet<CharString> seqIds;
    StringSet<Dna5String> seqs;
    String<char, MMap<> > seqMMapString;
    if (!open(seqMMapString, toCString(options.refFile), OPEN_RDONLY))
    {
        std::cerr << "Could not open " << options.refFile << std::endl;
        return 1;
    }
    RecordReader<String<char, MMap<> >, DoublePass<Mapped> > refReader(seqMMapString);
    if (read2(seqIds, seqs, refReader, Fasta()) != 0)
    {
        std::cerr << "Could not read reference from " << options.refFile << std::endl;
        return 1;
    }

    // Open SAM/BAM file and do work.
    if (options.inFormat == FORMAT_SAM)
    {
        if (options.verbosity >= 2)
            std::cerr << "Opening SAM file " << options.inFile << std::endl;
        String<char, MMap<> > samMMapString;
        if (!open(samMMapString, toCString(options.inFile), OPEN_RDONLY))
        {
            std::cerr << "Could not open " << options.inFile << std::endl;
            return 1;
        }
        RecordReader<String<char, MMap<> >, SinglePass<Mapped> > samReader(samMMapString);
        return doWork(samReader, seqs, options, Sam());
    }
    else  // options.inFormat == FORMAT_BAM
    {
        if (options.verbosity >= 2)
            std::cerr << "Opening BAM file " << options.inFile << std::endl;
        Stream<Bgzf> bamStream;
        if (!open(bamStream, toCString(options.inFile), "r"))
        {
            std::cerr << "Could not open " << options.inFile << std::endl;
            return 1;
        }
        return doWork(bamStream, seqs, options, Bam());
    }

    return 0;
}

#else

int main(int argc, char const ** argv)
{
    std::cerr << "bam_stats can only be compiled correctly with zlib." << std::endl;
    return 0;
}

#endif  // #if SEQAN_HAS_ZLIB
<commit_msg>Removed unused parameter warning in bam_stats.cpp.<commit_after>// ==========================================================================
//                                 bam_stats
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Read a BAM file and collect statistics on the alignments therein.
// ==========================================================================

#include <iostream>

#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h>      // For printing SeqAn Strings.

#include <seqan/stream.h>
#include <seqan/bam_io.h>
#include <seqan/misc/misc_cmdparser.h>

#if SEQAN_HAS_ZLIB

using namespace seqan;

enum Format
{
    FORMAT_AUTO,
    FORMAT_SAM,
    FORMAT_BAM
};

struct Options
{
    bool showHelp;
    bool showVersion;
    unsigned verbosity;
    CharString refFile;
    CharString inFile;
    Format inFormat;

    Options()
    {
        showHelp = false;
        showVersion = false;
        verbosity = 1;
        inFormat = FORMAT_AUTO;
    }
};

void
setupCommandLineParser(CommandLineParser & parser, Options const & options)
{
    addVersionLine(parser, "1.0");

    addTitleLine(parser, "*************");
    addTitleLine(parser, "* bam_stats *");
    addTitleLine(parser, "*************");
    addTitleLine(parser, "");
    addTitleLine(parser, "BAM Statistics.");
    addTitleLine(parser, "");
    addTitleLine(parser, "Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>");

    addUsageLine(parser, "bam_stats [OPTIONS] REF.fasta ALIGN.bam");

	addSection(parser, "General Options");
    addOption(parser, CommandLineOption("v", "verbose", "Enable verbose mode (show steps).", OptionType::Bool));
    addOption(parser, CommandLineOption("vv", "very-verbose", "Enable very verbose mode (show SAM lines and actual aligments).", OptionType::Bool));

	addSection(parser, "Input Specification");
    addOption(parser, CommandLineOption("i", "input-file", "Path to input, '-' for stdin.", OptionType::String, options.inFile));
    addOption(parser, CommandLineOption("S", "input-sam", "Input file is SAM (default: auto).", OptionType::Bool, options.inFormat == FORMAT_SAM));
    addOption(parser, CommandLineOption("B", "input-bam", "Input file is BAM (default: auto).", OptionType::Bool, options.inFormat == FORMAT_BAM));

    requiredArguments(parser, 2);
}

int parseCommandLineAndCheck(Options & options,
                             CommandLineParser & parser,
                             int argc,
                             char const ** argv)
{
    bool stop = !parse(parser, argc, argv);
    if (stop)
        return 1;
    if (isSetLong(parser, "help"))
    {
        options.showHelp = true;
        return 0;
    }
    if (isSetLong(parser, "version"))
    {
        options.showVersion = true;
        return 0;
    }

    if (isSetLong(parser, "verbose"))
        options.verbosity = 2;
    if (isSetLong(parser, "very-verbose"))
        options.verbosity = 3;

    getOptionValueLong(parser, "input-file", options.inFile);
    if (isSetLong(parser, "input-sam"))
        options.inFormat = FORMAT_SAM;
    if (isSetLong(parser, "input-bam"))
        options.inFormat = FORMAT_BAM;

    options.refFile = getArgumentValue(parser, 0);
    options.inFile = getArgumentValue(parser, 1);

	return 0;
}

struct Stats
{
    __uint64 numRecords;
    __uint64 alignedRecords;
    String<unsigned> editDistanceHisto;
    String<unsigned> mismatchHisto;
    String<unsigned> insertHisto;
    String<unsigned> deletionHisto;

    Stats() : numRecords(0), alignedRecords(0)
    {}
};

template <typename TStreamOrReader, typename TSeqString, typename TSpec, typename TFormat>
int doWork(TStreamOrReader & reader, StringSet<TSeqString, TSpec> & seqs, Options const & options, TFormat const & tag)
{
    StringSet<CharString> refNames;
    NameStoreCache<StringSet<CharString> > refNamesCache(refNames);
    BamIOContext<StringSet<CharString> > context(refNames, refNamesCache);

    // Read header.
    BamHeader header;
    if (options.verbosity >= 2)
        std::cerr << "Reading header" << std::endl;
    if (readRecord(header, context, reader, tag) != 0)
    {
        std::cerr << "Could not read header!" << std::endl;
        return 1;
    }

    Stats stats;

    // Read alignments.
    BamAlignmentRecord record;
    if (options.verbosity >= 2)
        std::cerr << "Reading alignments" << std::endl;
    Align<Dna5String> align;
    while (!atEnd(reader))
    {
        // Read alignment record.
        if (readRecord(record, context, reader, tag) != 0)
        {
            std::cerr << "Could not read alignment!" << std::endl;
            return 1;
        }
        if (options.verbosity >= 3)
            write2(std::cerr, record, context, Sam());

        // Now, do something with it ;)
        stats.numRecords += 1;  // One more record.
        stats.alignedRecords += !hasFlagUnmapped(record);
        // Compute alignment.
        if (record.rId != -1 && record.rId < static_cast<int>(length(seqs)))
        {
            bamRecordToAlignment(align, seqs[record.rId], record);
            if (options.verbosity >= 3)
                std::cerr << align << std::endl;
            typedef Align<Dna5String>             TAlign;
            typedef typename Row<TAlign>::Type    TRow;
            typedef typename Iterator<TRow>::Type TRowIter;
            unsigned editDistance = 0;
            unsigned posRead = 0;
            for (TRowIter it0 = begin(row(align, 0)), it1 = begin(row(align, 1)); !atEnd(it0); goNext(it0), goNext(it1))
            {
                if (isGap(it0) && isGap(it1))
                    continue;
                if (isGap(it0) || isGap(it1))
                {
                    if (isGap(it0))
                    {
                        unsigned len = length(stats.insertHisto);
                        resize(stats.insertHisto, std::max(len, posRead + 1), 0);
                        stats.insertHisto[posRead] += 1;
                        posRead += 1;
                    }
                    else
                    {
                        unsigned len = length(stats.deletionHisto);
                        resize(stats.deletionHisto, std::max(len, posRead + 1), 0);
                        stats.deletionHisto[posRead] += 1;
                    }
                    editDistance += 1;
                    continue;
                }
                if (*it0 != *it1)
                {
                    unsigned len = length(stats.mismatchHisto);
                    resize(stats.mismatchHisto, std::max(len, posRead + 1), 0);
                    stats.mismatchHisto[posRead] += 1;
                    editDistance += 1;
                }
                posRead += 1;
            }
            if (options.verbosity >= 3)
                std::cerr << "edit distance: " << editDistance << std::endl;
            unsigned len = length(stats.editDistanceHisto);
            resize(stats.editDistanceHisto, std::max(len, editDistance + 1), 0);
            stats.editDistanceHisto[editDistance] += 1;
        }
    }

    // Print results.
    std::cerr << "RESULTS\n\n";
    std::cerr << "num records     \t" << stats.numRecords << std::endl;
    std::cerr << "aligned records \t" << stats.alignedRecords << std::endl;
    std::cerr << "aligned record %\t" << 100.0 * stats.alignedRecords / stats.numRecords << std::endl;
    std::cerr << "distance histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.editDistanceHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.editDistanceHisto[i] << std::endl;
    std::cerr << "mismatch histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.mismatchHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.mismatchHisto[i] << std::endl;
    std::cerr << "insertion histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.insertHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.insertHisto[i] << std::endl;
    std::cerr << "deletion histogram" << std::endl;
    for (unsigned i = 0; i < length(stats.deletionHisto); ++i)
        std::cerr << "  " << i << "\t" << stats.deletionHisto[i] << std::endl;

    return 0;
}

int main(int argc, char const ** argv)
{
    using namespace seqan;

    // -----------------------------------------------------------------------
    // Handle Command Line
    // -----------------------------------------------------------------------

    // Setup command line parser.
    CommandLineParser parser;
    Options options;
    setupCommandLineParser(parser, options);

    // Then, parse the command line and handle the cases where help display
    // is requested or erroneous parameters were given.
    int res = parseCommandLineAndCheck(options, parser, argc, argv);
    if (res != 0)
        return 1;
    if (options.showHelp || options.showVersion)
        return 0;

    // -----------------------------------------------------------------------
    // Guess format.
    // -----------------------------------------------------------------------

    if (options.inFormat == FORMAT_AUTO)
    {
        std::ifstream guessIn(toCString(options.inFile), std::ios::binary | std::ios::in);
        if (!guessIn.good())
        {
            std::cerr << "Could not open " << options.inFile << std::endl;
            return 1;
        }
        CharString magic;
        resize(magic, 2);
        guessIn.read(&magic[0], 2);
        if (magic != "\x1f\x8b")  // Is not gzip-compressed.
            options.inFormat = FORMAT_SAM;
        else
            options.inFormat = FORMAT_BAM;
    }

    // -----------------------------------------------------------------------
    // Do Work.
    // -----------------------------------------------------------------------

    // Read reference.
    if (options.verbosity >= 2)
        std::cerr << "Reading references from " << options.refFile << std::endl;
    StringSet<CharString> seqIds;
    StringSet<Dna5String> seqs;
    String<char, MMap<> > seqMMapString;
    if (!open(seqMMapString, toCString(options.refFile), OPEN_RDONLY))
    {
        std::cerr << "Could not open " << options.refFile << std::endl;
        return 1;
    }
    RecordReader<String<char, MMap<> >, DoublePass<Mapped> > refReader(seqMMapString);
    if (read2(seqIds, seqs, refReader, Fasta()) != 0)
    {
        std::cerr << "Could not read reference from " << options.refFile << std::endl;
        return 1;
    }

    // Open SAM/BAM file and do work.
    if (options.inFormat == FORMAT_SAM)
    {
        if (options.verbosity >= 2)
            std::cerr << "Opening SAM file " << options.inFile << std::endl;
        String<char, MMap<> > samMMapString;
        if (!open(samMMapString, toCString(options.inFile), OPEN_RDONLY))
        {
            std::cerr << "Could not open " << options.inFile << std::endl;
            return 1;
        }
        RecordReader<String<char, MMap<> >, SinglePass<Mapped> > samReader(samMMapString);
        return doWork(samReader, seqs, options, Sam());
    }
    else  // options.inFormat == FORMAT_BAM
    {
        if (options.verbosity >= 2)
            std::cerr << "Opening BAM file " << options.inFile << std::endl;
        Stream<Bgzf> bamStream;
        if (!open(bamStream, toCString(options.inFile), "r"))
        {
            std::cerr << "Could not open " << options.inFile << std::endl;
            return 1;
        }
        return doWork(bamStream, seqs, options, Bam());
    }

    return 0;
}

#else

int main(int, char const **)
{
    std::cerr << "bam_stats can only be compiled correctly with zlib." << std::endl;
    return 0;
}

#endif  // #if SEQAN_HAS_ZLIB
<|endoftext|>


<commit_before>#pragma once

//! The shape function (on the reference element) for LINEAR FEM.
//!
//! We have three shape functions.
//!
//! lambda(0, x, y) should be 1 in the point (0,0) and zero in (1,0) and (0,1)
//! lambda(1, x, y) should be 1 in the point (1,0) and zero in (0,0) and (0,1)
//! lambda(2, x, y) should be 1 in the point (0,1) and zero in (0,0) and (1,0)
//!
//! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.
//! @param x x coordinate in the reference element.
//! @param y y coordinate in the reference element.
inline double lambda(int i, double x, double y) {
	if (i == 0) {
		return 1 - x - y;
	} else if (i == 1) {
		return x;
	} else {
		return y;
	}
}

//----------------shapefunBegin----------------
//! The shape function (on the reference element) for QUADRATIC FEM
//!
//! We have six shape functions.
//!
//! shapefun(0, x, y) should be 1 in the point (0,0) and zero in the other 5
//! shapefun(1, x, y) should be 1 in the point (1,0) and zero in the other 5
//! shapefun(2, x, y) should be 1 in the point (0,1) and zero in the other 5
//! shapefun(3, x, y) should be 1 in the point (0.5,0) and zero in the other 5
//! shapefun(4, x, y) should be 1 in the point (0.5,0.5) and zero in the other 5
//! shapefun(5, x, y) should be 1 in the point (0,0.5) and zero in the other 5
//!
//! @param i integer between 0 and 5 (inclusive). Decides which shape function to return.
//! @param x x coordinate in the reference element.
//! @param y y coordinate in the reference element.
inline double shapefun(int i, double x, double y) {
	double value = 0.0;
	// (write your solution here)
	return value;
}
//----------------shapefunEnd----------------
<commit_msg>Solved series 3 problem 1b<commit_after>#pragma once
#include <cassert>
#include <stdexcept>

//! The shape function (on the reference element) for LINEAR FEM.
//!
//! We have three shape functions.
//!
//! lambda(0, x, y) should be 1 in the point (0,0) and zero in (1,0) and (0,1)
//! lambda(1, x, y) should be 1 in the point (1,0) and zero in (0,0) and (0,1)
//! lambda(2, x, y) should be 1 in the point (0,1) and zero in (0,0) and (1,0)
//!
//! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.
//! @param x x coordinate in the reference element.
//! @param y y coordinate in the reference element.
inline double lambda(int i, double x, double y) {
	if (i == 0) {
		return 1 - x - y;
	} else if (i == 1) {
		return x;
	} else {
		return y;
	}
}

//----------------shapefunBegin----------------
//! The shape function (on the reference element) for QUADRATIC FEM
//!
//! We have six shape functions.
//!
//! shapefun(0, x, y) should be 1 in the point (0,0) and zero in the other 5
//! shapefun(1, x, y) should be 1 in the point (1,0) and zero in the other 5
//! shapefun(2, x, y) should be 1 in the point (0,1) and zero in the other 5
//! shapefun(3, x, y) should be 1 in the point (0.5,0) and zero in the other 5
//! shapefun(4, x, y) should be 1 in the point (0.5,0.5) and zero in the other 5
//! shapefun(5, x, y) should be 1 in the point (0,0.5) and zero in the other 5
//!
//! @param i integer between 0 and 5 (inclusive). Decides which shape function to return.
//! @param x x coordinate in the reference element.
//! @param y y coordinate in the reference element.
inline double shapefun(int i, double x, double y) {
	// double value = 0.0;
	// (write your solution here)
	assert(0 <= i && i <= 5);
	switch (i) {
		case 0:
			return (2 * lambda(0, x, y) - 1) * lambda(0, x, y);
		case 1:
			return (2 * lambda(1, x, y) - 1) * lambda(1, x, y);
		case 2:
			return (2 * lambda(2, x, y) - 1) * lambda(2, x, y);
		case 3:
			return 4 * lambda(0, x, y) * lambda(1, x, y);
		case 4:
			return 4 * lambda(1, x, y) * lambda(2, x, y);
		case 5:
			return 4 * lambda(0, x, y) * lambda(2, x, y);
		default:
			throw std::domain_error("i not in {0,1,2,3,4,5}");
	}
	// return value;
}
//----------------shapefunEnd----------------
<|endoftext|>


<commit_before>#include "scenewidget.h"
#include <QSurfaceFormat>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>

SceneWidget::SceneWidget(QWidget *parent) :
    QOpenGLWidget(parent), m_modelScale(1.0f, 1.0f, 1.0f)
{
    // Set opengl version & profile
    QSurfaceFormat format;

    format.setRenderableType(QSurfaceFormat::OpenGL);
    format.setVersion(3, 2);
    format.setProfile(QSurfaceFormat::CoreProfile);
    format.setDepthBufferSize(24);
    format.setSamples(4);

    setFormat(format);
}

SceneWidget::~SceneWidget()
{

}

void SceneWidget::initializeGL()
{
    // Init opengl
    bool success = initializeOpenGLFunctions();

    // Check if opengl init was successfull
    if (!success)
        throw std::runtime_error("Could not load OpenGL functions.\nDo you have OpenGL v3.2?");

    // Print version info
    std::clog << "OpenGL version: " << glGetString(GL_VERSION) <<
                 "\nGLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) <<
                 "\nRenderer: " << glGetString(GL_RENDERER) <<
                 "\nVendor: " << glGetString(GL_VENDOR) << '\n' << std::endl;

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

    // Enable face culling
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CW);
    glCullFace(GL_BACK);

    initProgram();
    initData();
}

void SceneWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(m_program);
    glBindVertexArray(m_vao);

    glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, reinterpret_cast<void*>(0));

    glBindVertexArray(0);
    glUseProgram(0);
}

void SceneWidget::resizeGL(int w, int h)
{
    // Adjust viewport
    glViewport(0, 0, w, h);

    // Adjust perspective matrix
    float aspect = static_cast<float>(w) / h;

    recalcModelMatrix();
    m_viewMatrix = glm::lookAt(glm::vec3(0, 0, 0), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0));
    m_projectionMatrix = glm::perspective(90.0f, aspect, 0.01f, 100.0f);

    updateMvpMatrix();
}

void SceneWidget::initProgram()
{
    GLuint vs = compileShader("../res/shader.vert", GL_VERTEX_SHADER);
    GLuint fs = compileShader("../res/shader.frag", GL_FRAGMENT_SHADER);

    m_program = glCreateProgram();

    glAttachShader(m_program, vs);
    glAttachShader(m_program, fs);

    glLinkProgram(m_program);
    checkShaderErrors(m_program, true, GL_LINK_STATUS, "Could not link program");

    glValidateProgram(m_program);
    checkShaderErrors(m_program, true, GL_VALIDATE_STATUS, "Could not validate program");

    glDetachShader(m_program, vs);
    glDetachShader(m_program, fs);

    glDeleteShader(vs);
    glDeleteShader(fs);

    // Load uniforms
    m_mvpMatrixUnif = glGetUniformLocation(m_program, "mvpMatrix");
}

std::string SceneWidget::getFileContents(const std::string &path) const
{
    std::ifstream file(path);
    if (!file.is_open())
        throw std::runtime_error("Could not open file: " + path);

    std::ostringstream oss;
    oss << file.rdbuf();
    return oss.str();
}

void SceneWidget::checkShaderErrors(GLuint shader, bool isProgram, GLenum param, const std::string &errorMsg)
{
    GLint status;
    if (isProgram)
        glGetProgramiv(shader, param, &status);
    else
        glGetShaderiv(shader, param, &status);

    if (status)
        return; // No errors

    GLint logLength;
    if (isProgram)
        glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &logLength);
    else
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);

    GLchar *buffer = new GLchar[logLength];
    if (isProgram)
        glGetProgramInfoLog(shader, logLength, nullptr, buffer);
    else
        glGetShaderInfoLog(shader, logLength, nullptr, buffer);

    std::ostringstream msgStream;
    msgStream << errorMsg << ":\n" << buffer;
    std::string msg = msgStream.str();

    delete[] buffer;
    throw std::runtime_error(msg);
}

GLuint SceneWidget::compileShader(const std::string &path, GLenum type)
{
    std::string typeStr;
    switch (type)
    {
    case GL_VERTEX_SHADER:
        typeStr = "vertex";
        break;
    case GL_FRAGMENT_SHADER:
        typeStr = "fragment";
        break;
    default:
        typeStr = "unknown";
        break;
    }

    GLuint shader = glCreateShader(type);

    std::string source = getFileContents(path);
    const GLchar *sourceCStr = source.c_str();

    glShaderSource(shader, 1, &sourceCStr, nullptr);
    glCompileShader(shader);
    checkShaderErrors(shader, false, GL_COMPILE_STATUS, "Could not compile " + typeStr + " shader");

    return shader;
}

void SceneWidget::initData()
{
    // Data
    GLfloat data[] =
    {
        /* POSITIONS */

        // Front face
        -1.0f, -1.0f, +1.0f,
        -1.0f, +1.0f, +1.0f,
        +1.0f, +1.0f, +1.0f,
        +1.0f, -1.0f, +1.0f,

        // Right face
        +1.0f, -1.0f, +1.0f,
        +1.0f, +1.0f, +1.0f,
        +1.0f, +1.0f, -1.0f,
        +1.0f, -1.0f, -1.0f,

        // Top face
        -1.0f, +1.0f, +1.0f,
        -1.0f, +1.0f, -1.0f,
        +1.0f, +1.0f, -1.0f,
        +1.0f, +1.0f, +1.0f,

        // Back face
        -1.0f, -1.0f, -1.0f,
        -1.0f, +1.0f, -1.0f,
        +1.0f, +1.0f, -1.0f,
        +1.0f, -1.0f, -1.0f,

        // Left face
        -1.0f, -1.0f, +1.0f,
        -1.0f, +1.0f, +1.0f,
        -1.0f, +1.0f, -1.0f,
        -1.0f, -1.0f, -1.0f,

        // Bottom face
        -1.0f, -1.0f, +1.0f,
        -1.0f, -1.0f, -1.0f,
        +1.0f, -1.0f, -1.0f,
        +1.0f, -1.0f, +1.0f,

        /* COLORS */

        // Front face
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,

        // Right face
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,

        // Top face
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,

        // Back face
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,

        // Left face
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,

        // Bottom face
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
    };

    // Indices
    GLushort indices[] =
    {
        // Front face
        0, 1, 2,
        0, 2, 3,

        // Right face
        4, 5, 6,
        4, 6, 7,

        // Top face
        8, 9, 10,
        8, 10, 11,

        // Back face
        12, 14, 13,
        12, 15, 14,

        // Left face
        16, 18, 17,
        16, 19, 18,

        // Bottom face
        20, 22, 21,
        20, 23, 22,
    };

    // Create and bind vao
    glGenVertexArrays(1, &m_vao);
    glBindVertexArray(m_vao);

    // Create and bind position vbo
    glGenBuffers(1, &m_vertexDataVbo);
    glBindBuffer(GL_ARRAY_BUFFER, m_vertexDataVbo);

    // Create and bind indices vbo
    glGenBuffers(1, &m_indicesVbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indicesVbo);

    // Fill position buffer
    glBufferData(GL_ARRAY_BUFFER, sizeof data, data, GL_STATIC_DRAW);

    // Position attrib
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(0));

    // Color attrib
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(numOfVertices * 3 * sizeof(GLfloat)));

    // Fill indices buffer
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, GL_STATIC_DRAW);

    // Cleanup
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void SceneWidget::recalcModelMatrix()
{
    m_modelMatrix = glm::mat4();
    m_modelMatrix *= glm::translate(glm::mat4(), m_modelTranslate);
    m_modelMatrix *= glm::rotate(glm::mat4(), m_modelRotate.z, glm::vec3(0, 0, 1));
    m_modelMatrix *= glm::rotate(glm::mat4(), m_modelRotate.y, glm::vec3(0, 1, 0));
    m_modelMatrix *= glm::rotate(glm::mat4(), m_modelRotate.x, glm::vec3(1, 0, 0));
    m_modelMatrix *= glm::scale(glm::mat4(), m_modelScale);

    updateMvpMatrix();
}

void SceneWidget::updateMvpMatrix()
{
    m_mvpMatrix = m_projectionMatrix * m_viewMatrix * m_modelMatrix;

    glUseProgram(m_program);
    glUniformMatrix4fv(m_mvpMatrixUnif, 1, GL_FALSE, glm::value_ptr(m_mvpMatrix));
    glUseProgram(0);
}
<commit_msg>Converted model rotation angles to radians<commit_after>#include "scenewidget.h"
#include <QSurfaceFormat>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>

SceneWidget::SceneWidget(QWidget *parent) :
    QOpenGLWidget(parent), m_modelScale(1.0f, 1.0f, 1.0f)
{
    // Set opengl version & profile
    QSurfaceFormat format;

    format.setRenderableType(QSurfaceFormat::OpenGL);
    format.setVersion(3, 2);
    format.setProfile(QSurfaceFormat::CoreProfile);
    format.setDepthBufferSize(24);
    format.setSamples(4);

    setFormat(format);
}

SceneWidget::~SceneWidget()
{

}

void SceneWidget::initializeGL()
{
    // Init opengl
    bool success = initializeOpenGLFunctions();

    // Check if opengl init was successfull
    if (!success)
        throw std::runtime_error("Could not load OpenGL functions.\nDo you have OpenGL v3.2?");

    // Print version info
    std::clog << "OpenGL version: " << glGetString(GL_VERSION) <<
                 "\nGLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) <<
                 "\nRenderer: " << glGetString(GL_RENDERER) <<
                 "\nVendor: " << glGetString(GL_VENDOR) << '\n' << std::endl;

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

    // Enable face culling
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CW);
    glCullFace(GL_BACK);

    initProgram();
    initData();
}

void SceneWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(m_program);
    glBindVertexArray(m_vao);

    glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, reinterpret_cast<void*>(0));

    glBindVertexArray(0);
    glUseProgram(0);
}

void SceneWidget::resizeGL(int w, int h)
{
    // Adjust viewport
    glViewport(0, 0, w, h);

    // Adjust perspective matrix
    float aspect = static_cast<float>(w) / h;

    recalcModelMatrix();
    m_viewMatrix = glm::lookAt(glm::vec3(0, 0, 0), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0));
    m_projectionMatrix = glm::perspective(90.0f, aspect, 0.01f, 100.0f);

    updateMvpMatrix();
}

void SceneWidget::initProgram()
{
    GLuint vs = compileShader("../res/shader.vert", GL_VERTEX_SHADER);
    GLuint fs = compileShader("../res/shader.frag", GL_FRAGMENT_SHADER);

    m_program = glCreateProgram();

    glAttachShader(m_program, vs);
    glAttachShader(m_program, fs);

    glLinkProgram(m_program);
    checkShaderErrors(m_program, true, GL_LINK_STATUS, "Could not link program");

    glValidateProgram(m_program);
    checkShaderErrors(m_program, true, GL_VALIDATE_STATUS, "Could not validate program");

    glDetachShader(m_program, vs);
    glDetachShader(m_program, fs);

    glDeleteShader(vs);
    glDeleteShader(fs);

    // Load uniforms
    m_mvpMatrixUnif = glGetUniformLocation(m_program, "mvpMatrix");
}

std::string SceneWidget::getFileContents(const std::string &path) const
{
    std::ifstream file(path);
    if (!file.is_open())
        throw std::runtime_error("Could not open file: " + path);

    std::ostringstream oss;
    oss << file.rdbuf();
    return oss.str();
}

void SceneWidget::checkShaderErrors(GLuint shader, bool isProgram, GLenum param, const std::string &errorMsg)
{
    GLint status;
    if (isProgram)
        glGetProgramiv(shader, param, &status);
    else
        glGetShaderiv(shader, param, &status);

    if (status)
        return; // No errors

    GLint logLength;
    if (isProgram)
        glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &logLength);
    else
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);

    GLchar *buffer = new GLchar[logLength];
    if (isProgram)
        glGetProgramInfoLog(shader, logLength, nullptr, buffer);
    else
        glGetShaderInfoLog(shader, logLength, nullptr, buffer);

    std::ostringstream msgStream;
    msgStream << errorMsg << ":\n" << buffer;
    std::string msg = msgStream.str();

    delete[] buffer;
    throw std::runtime_error(msg);
}

GLuint SceneWidget::compileShader(const std::string &path, GLenum type)
{
    std::string typeStr;
    switch (type)
    {
    case GL_VERTEX_SHADER:
        typeStr = "vertex";
        break;
    case GL_FRAGMENT_SHADER:
        typeStr = "fragment";
        break;
    default:
        typeStr = "unknown";
        break;
    }

    GLuint shader = glCreateShader(type);

    std::string source = getFileContents(path);
    const GLchar *sourceCStr = source.c_str();

    glShaderSource(shader, 1, &sourceCStr, nullptr);
    glCompileShader(shader);
    checkShaderErrors(shader, false, GL_COMPILE_STATUS, "Could not compile " + typeStr + " shader");

    return shader;
}

void SceneWidget::initData()
{
    // Data
    GLfloat data[] =
    {
        /* POSITIONS */

        // Front face
        -1.0f, -1.0f, +1.0f,
        -1.0f, +1.0f, +1.0f,
        +1.0f, +1.0f, +1.0f,
        +1.0f, -1.0f, +1.0f,

        // Right face
        +1.0f, -1.0f, +1.0f,
        +1.0f, +1.0f, +1.0f,
        +1.0f, +1.0f, -1.0f,
        +1.0f, -1.0f, -1.0f,

        // Top face
        -1.0f, +1.0f, +1.0f,
        -1.0f, +1.0f, -1.0f,
        +1.0f, +1.0f, -1.0f,
        +1.0f, +1.0f, +1.0f,

        // Back face
        -1.0f, -1.0f, -1.0f,
        -1.0f, +1.0f, -1.0f,
        +1.0f, +1.0f, -1.0f,
        +1.0f, -1.0f, -1.0f,

        // Left face
        -1.0f, -1.0f, +1.0f,
        -1.0f, +1.0f, +1.0f,
        -1.0f, +1.0f, -1.0f,
        -1.0f, -1.0f, -1.0f,

        // Bottom face
        -1.0f, -1.0f, +1.0f,
        -1.0f, -1.0f, -1.0f,
        +1.0f, -1.0f, -1.0f,
        +1.0f, -1.0f, +1.0f,

        /* COLORS */

        // Front face
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,

        // Right face
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,

        // Top face
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,

        // Back face
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,

        // Left face
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,

        // Bottom face
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
    };

    // Indices
    GLushort indices[] =
    {
        // Front face
        0, 1, 2,
        0, 2, 3,

        // Right face
        4, 5, 6,
        4, 6, 7,

        // Top face
        8, 9, 10,
        8, 10, 11,

        // Back face
        12, 14, 13,
        12, 15, 14,

        // Left face
        16, 18, 17,
        16, 19, 18,

        // Bottom face
        20, 22, 21,
        20, 23, 22,
    };

    // Create and bind vao
    glGenVertexArrays(1, &m_vao);
    glBindVertexArray(m_vao);

    // Create and bind position vbo
    glGenBuffers(1, &m_vertexDataVbo);
    glBindBuffer(GL_ARRAY_BUFFER, m_vertexDataVbo);

    // Create and bind indices vbo
    glGenBuffers(1, &m_indicesVbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indicesVbo);

    // Fill position buffer
    glBufferData(GL_ARRAY_BUFFER, sizeof data, data, GL_STATIC_DRAW);

    // Position attrib
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(0));

    // Color attrib
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(numOfVertices * 3 * sizeof(GLfloat)));

    // Fill indices buffer
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, GL_STATIC_DRAW);

    // Cleanup
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void SceneWidget::recalcModelMatrix()
{
    m_modelMatrix = glm::mat4();
    m_modelMatrix *= glm::translate(glm::mat4(), m_modelTranslate);
    m_modelMatrix *= glm::rotate(glm::mat4(), glm::radians(m_modelRotate.z), glm::vec3(0, 0, 1));
    m_modelMatrix *= glm::rotate(glm::mat4(), glm::radians(m_modelRotate.y), glm::vec3(0, 1, 0));
    m_modelMatrix *= glm::rotate(glm::mat4(), glm::radians(m_modelRotate.x), glm::vec3(1, 0, 0));
    m_modelMatrix *= glm::scale(glm::mat4(), m_modelScale);

    updateMvpMatrix();
}

void SceneWidget::updateMvpMatrix()
{
    m_mvpMatrix = m_projectionMatrix * m_viewMatrix * m_modelMatrix;

    glUseProgram(m_program);
    glUniformMatrix4fv(m_mvpMatrixUnif, 1, GL_FALSE, glm::value_ptr(m_mvpMatrix));
    glUseProgram(0);
}
<|endoftext|>


<commit_before>#include "csvmodelwriter.h"

#include <QAbstractItemModel>
#include <QFile>
#include <QTextStream>

CSVModelWriter::CSVModelWriter(const QString &filename, QObject *parent) :
    QObject(parent),
    filename(filename)
{
}

void CSVModelWriter::setModel(const QAbstractItemModel *model)
{
    this->model = model;
}

void CSVModelWriter::addColumn(const QString &title, int column, int role)
{
    Column col;
    col.title = title;
    col.column = column;
    col.role = role;

    columns.append(col);
}

static void writeValue(QTextStream &f, const QString &value)
{
    // TODO: quoting if " or \n in string
    f << "\"" << value << "\"";
}

static void writeSep(QTextStream &f)
{
    f << ",";
}

static void writeNewline(QTextStream &f)
{
    f << "\n";
}

bool CSVModelWriter::write()
{
    QFile file(filename);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(&file);

    int numRows = 0;
    if(model)
    {
        numRows = model->rowCount();
    }

    // Header row
    for(int i=0; i<columns.size(); ++i)
    {
        if(i!=0)
        {
            writeSep(out);
        }
        writeValue(out, columns[i].title);
    }
    writeNewline(out);

    // Data rows
    for(int j=0; j<numRows; ++j)
    {
        for(int i=0; i<columns.size(); ++i)
        {
            if(i!=0)
            {
                writeSep(out);
            }
            QVariant data = model->index(j, columns[i].column).data(columns[i].role);
            writeValue(out, data.toString());
        }
        writeNewline(out);
    }

    file.close();

    return file.error() == QFile::NoError;
}

<commit_msg>Add forgotten initializer<commit_after>#include "csvmodelwriter.h"

#include <QAbstractItemModel>
#include <QFile>
#include <QTextStream>

CSVModelWriter::CSVModelWriter(const QString &filename, QObject *parent) :
    QObject(parent),
    filename(filename), model(0)
{
}

void CSVModelWriter::setModel(const QAbstractItemModel *model)
{
    this->model = model;
}

void CSVModelWriter::addColumn(const QString &title, int column, int role)
{
    Column col;
    col.title = title;
    col.column = column;
    col.role = role;

    columns.append(col);
}

static void writeValue(QTextStream &f, const QString &value)
{
    // TODO: quoting if " or \n in string
    f << "\"" << value << "\"";
}

static void writeSep(QTextStream &f)
{
    f << ",";
}

static void writeNewline(QTextStream &f)
{
    f << "\n";
}

bool CSVModelWriter::write()
{
    QFile file(filename);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(&file);

    int numRows = 0;
    if(model)
    {
        numRows = model->rowCount();
    }

    // Header row
    for(int i=0; i<columns.size(); ++i)
    {
        if(i!=0)
        {
            writeSep(out);
        }
        writeValue(out, columns[i].title);
    }
    writeNewline(out);

    // Data rows
    for(int j=0; j<numRows; ++j)
    {
        for(int i=0; i<columns.size(); ++i)
        {
            if(i!=0)
            {
                writeSep(out);
            }
            QVariant data = model->index(j, columns[i].column).data(columns[i].role);
            writeValue(out, data.toString());
        }
        writeNewline(out);
    }

    file.close();

    return file.error() == QFile::NoError;
}

<|endoftext|>


<commit_before>#include "statisticspage.h"
#include "ui_statisticspage.h"
#include "main.h"
#include "wallet.h"
#include "init.h"
#include "base58.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "marketbrowser.h"
#include <sstream>
#include <string>

using namespace json_spirit;

StatisticsPage::StatisticsPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::StatisticsPage)
{
    ui->setupUi(this);

    setFixedSize(400, 420);

    connect(ui->startButton, SIGNAL(pressed()), this, SLOT(updateStatistics()));
}

int heightPrevious = -1;
int connectionPrevious = -1;
int volumePrevious = -1;
double netPawratePrevious = -1;
double pawratePrevious = -1;
double hardnessPrevious = -1;
double hardnessPrevious2 = -1;
int stakeminPrevious = -1;
int stakemaxPrevious = -1;
int64_t marketcapPrevious = -1;
QString stakecPrevious = "";
QString rewardPrevious = "";

void StatisticsPage::updateStatistics()
{
    double pHardness = GetDifficulty();
    double pHardness2 = GetDifficulty(GetLastBlockIndex(pindexBest, true));
    int pPawrate = GetPoWMHashPS();
    double pPawrate2 = 0.000;
    int nHeight = pindexBest->nHeight;
    uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
    pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
    uint64_t nNetworkWeight = GetPoSKernelPS();
    int64_t volume = ((pindexBest->nMoneySupply)/100000000);
	int64_t marketcap = dnrmarket.toDouble();
    int peers = this->model->getNumConnections();
    pPawrate2 = (double)pPawrate;
    QString height = QString::number(nHeight);
    QString stakemin = QString::number(nMinWeight);
    QString stakemax = QString::number(nNetworkWeight);
    QString phase = "";
    if (pindexBest->nHeight < 3000000)
    {
        phase = "Tribus Proof of Work with Proof of Stake";
    }
    else if (pindexBest->nHeight > 3000000)
    {
        phase = "Proof of Stake";
    }

    QString subsidy = "";
	if (pindexBest->nHeight < 1000000)
    {
        subsidy = "2 BZL per block";
    }
	else if (pindexBest->nHeight < 2000000)
    {
        subsidy = "2 BZL per block";
    }
	else if (pindexBest->nHeight < 3000000)
    {
        subsidy = "1 BZL per block";
    }
    else if (pindexBest->nHeight > 3000000)
    {
        subsidy = "No PoW Reward";
    }
    QString hardness = QString::number(pHardness, 'f', 6);
    QString hardness2 = QString::number(pHardness2, 'f', 6);
    QString pawrate = QString::number(pPawrate2, 'f', 3);
    QString Qlpawrate = model->getLastBlockDate().toString();

    QString QPeers = QString::number(peers);
    QString qVolume = QString::number(volume);

    if(nHeight > heightPrevious)
    {
        ui->heightBox->setText("" + height + "");
    } else {
		ui->heightBox->setText("" + height + "");
    }

    if(0 > stakeminPrevious)
    {
        ui->minBox->setText("" + stakemin + "");
    } else {
    ui->minBox->setText("" + stakemin + "");
    }
    if(0 > stakemaxPrevious)
    {
        ui->maxBox->setText("" + stakemax + "");
    } else {
    ui->maxBox->setText("" + stakemax + "");
    }

    if(phase != stakecPrevious)
    {
        ui->cBox->setText("" + phase + "");
    } else {
    ui->cBox->setText("" + phase + "");
    }

    if(subsidy != rewardPrevious)
    {
        ui->rewardBox->setText("" + subsidy + "");
    } else {
    ui->rewardBox->setText("" + subsidy + "");
    }

    if(pHardness > hardnessPrevious)
    {
        ui->diffBox->setText("" + hardness + "");
    } else if(pHardness < hardnessPrevious) {
        ui->diffBox->setText("" + hardness + "");
    } else {
        ui->diffBox->setText("" + hardness + "");
    }
	/*
    if(marketcap > marketcapPrevious)
    {
        ui->marketcap->setText("$" + QString::number(marketcap) + " USD");
    } else if(marketcap < marketcapPrevious) {
        ui->marketcap->setText("$" + QString::number(marketcap) + " USD");
    } else {
        ui->marketcap->setText("$"+QString::number(marketcap)+" USD");
    }
	*/
    if(pHardness2 > hardnessPrevious2)
    {
        ui->diffBox2->setText("" + hardness2 + "");
    } else if(pHardness2 < hardnessPrevious2) {
        ui->diffBox2->setText("" + hardness2 + "");
    } else {
        ui->diffBox2->setText("" + hardness2 + "");
    }

    if(pPawrate2 > netPawratePrevious)
    {
        ui->pawrateBox->setText("" + pawrate + " MH/s");
    } else if(pPawrate2 < netPawratePrevious) {
        ui->pawrateBox->setText("" + pawrate + " MH/s");
    } else {
        ui->pawrateBox->setText("" + pawrate + " MH/s");
    }

    if(Qlpawrate != pawratePrevious)
    {
        ui->localBox->setText("" + Qlpawrate + "");
    } else {
    ui->localBox->setText("" + Qlpawrate + "");
    }

    if(peers > connectionPrevious)
    {
        ui->connectionBox->setText("" + QPeers + "");
    } else if(peers < connectionPrevious) {
        ui->connectionBox->setText("" + QPeers + "");
    } else {
        ui->connectionBox->setText("" + QPeers + "");
    }

    if(volume > volumePrevious)
    {
        ui->volumeBox->setText("" + qVolume + " BZL" + "");
    } else if(volume < volumePrevious) {
        ui->volumeBox->setText("" + qVolume + " BZL" + "");
    } else {
        ui->volumeBox->setText("" + qVolume + " BZL" + "");
    }

    updatePrevious(nHeight, nMinWeight, nNetworkWeight, phase, subsidy, pHardness, pHardness2, pPawrate2, Qlpawrate, peers, volume, marketcap);
}

void StatisticsPage::updatePrevious(int nHeight, int nMinWeight, int nNetworkWeight, QString phase, QString subsidy, double pHardness, double pHardness2, double pPawrate2, QString Qlpawrate, int peers, int volume, int64_t marketcap)
{
    heightPrevious = nHeight;
    stakeminPrevious = nMinWeight;
    stakemaxPrevious = nNetworkWeight;
    stakecPrevious = phase;
    rewardPrevious = subsidy;
    hardnessPrevious = pHardness;
    hardnessPrevious2 = pHardness2;
    netPawratePrevious = pPawrate2;
    pawratePrevious = Qlpawrate;
    connectionPrevious = peers;
    volumePrevious = volume;
	marketcapPrevious = marketcap;
}

void StatisticsPage::setModel(ClientModel *model)
{
    updateStatistics();
    this->model = model;
}

StatisticsPage::~StatisticsPage()
{
    delete ui;
}
<commit_msg>V1.1 / Fork in block 3398<commit_after>#include "statisticspage.h"
#include "ui_statisticspage.h"
#include "main.h"
#include "wallet.h"
#include "init.h"
#include "base58.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "marketbrowser.h"
#include <sstream>
#include <string>

using namespace json_spirit;

StatisticsPage::StatisticsPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::StatisticsPage)
{
    ui->setupUi(this);

    setFixedSize(400, 420);

    connect(ui->startButton, SIGNAL(pressed()), this, SLOT(updateStatistics()));
}

int heightPrevious = -1;
int connectionPrevious = -1;
int volumePrevious = -1;
double netPawratePrevious = -1;
double pawratePrevious = -1;
double hardnessPrevious = -1;
double hardnessPrevious2 = -1;
int stakeminPrevious = -1;
int stakemaxPrevious = -1;
int64_t marketcapPrevious = -1;
QString stakecPrevious = "";
QString rewardPrevious = "";

void StatisticsPage::updateStatistics()
{
    double pHardness = GetDifficulty();
    double pHardness2 = GetDifficulty(GetLastBlockIndex(pindexBest, true));
    int pPawrate = GetPoWMHashPS();
    double pPawrate2 = 0.000;
    int nHeight = pindexBest->nHeight;
    uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
    pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
    uint64_t nNetworkWeight = GetPoSKernelPS();
    int64_t volume = ((pindexBest->nMoneySupply)/100000000);
	int64_t marketcap = dnrmarket.toDouble();
    int peers = this->model->getNumConnections();
    pPawrate2 = (double)pPawrate;
    QString height = QString::number(nHeight);
    QString stakemin = QString::number(nMinWeight);
    QString stakemax = QString::number(nNetworkWeight);
    QString phase = "";
    if (pindexBest->nHeight < 3000000)
    {
        phase = "Tribus Proof of Work with Proof of Stake";
    }
    else if (pindexBest->nHeight > 3000000)
    {
        phase = "Proof of Stake";
    }

    QString subsidy = "";
	if (pindexBest->nHeight < 3398) // V1.1
    {
        subsidy = "2 BZL per block";
    }
	else if (pindexBest->nHeight < 2000000)
    {
        subsidy = "1 BZL per block";
    }
	else if (pindexBest->nHeight < 3000000)
    {
        subsidy = "1 BZL per block";
    }
    else if (pindexBest->nHeight > 3000000)
    {
        subsidy = "No PoW Reward";
    }
    QString hardness = QString::number(pHardness, 'f', 6);
    QString hardness2 = QString::number(pHardness2, 'f', 6);
    QString pawrate = QString::number(pPawrate2, 'f', 3);
    QString Qlpawrate = model->getLastBlockDate().toString();

    QString QPeers = QString::number(peers);
    QString qVolume = QString::number(volume);

    if(nHeight > heightPrevious)
    {
        ui->heightBox->setText("" + height + "");
    } else {
		ui->heightBox->setText("" + height + "");
    }

    if(0 > stakeminPrevious)
    {
        ui->minBox->setText("" + stakemin + "");
    } else {
    ui->minBox->setText("" + stakemin + "");
    }
    if(0 > stakemaxPrevious)
    {
        ui->maxBox->setText("" + stakemax + "");
    } else {
    ui->maxBox->setText("" + stakemax + "");
    }

    if(phase != stakecPrevious)
    {
        ui->cBox->setText("" + phase + "");
    } else {
    ui->cBox->setText("" + phase + "");
    }

    if(subsidy != rewardPrevious)
    {
        ui->rewardBox->setText("" + subsidy + "");
    } else {
    ui->rewardBox->setText("" + subsidy + "");
    }

    if(pHardness > hardnessPrevious)
    {
        ui->diffBox->setText("" + hardness + "");
    } else if(pHardness < hardnessPrevious) {
        ui->diffBox->setText("" + hardness + "");
    } else {
        ui->diffBox->setText("" + hardness + "");
    }
	/*
    if(marketcap > marketcapPrevious)
    {
        ui->marketcap->setText("$" + QString::number(marketcap) + " USD");
    } else if(marketcap < marketcapPrevious) {
        ui->marketcap->setText("$" + QString::number(marketcap) + " USD");
    } else {
        ui->marketcap->setText("$"+QString::number(marketcap)+" USD");
    }
	*/
    if(pHardness2 > hardnessPrevious2)
    {
        ui->diffBox2->setText("" + hardness2 + "");
    } else if(pHardness2 < hardnessPrevious2) {
        ui->diffBox2->setText("" + hardness2 + "");
    } else {
        ui->diffBox2->setText("" + hardness2 + "");
    }

    if(pPawrate2 > netPawratePrevious)
    {
        ui->pawrateBox->setText("" + pawrate + " MH/s");
    } else if(pPawrate2 < netPawratePrevious) {
        ui->pawrateBox->setText("" + pawrate + " MH/s");
    } else {
        ui->pawrateBox->setText("" + pawrate + " MH/s");
    }

    if(Qlpawrate != pawratePrevious)
    {
        ui->localBox->setText("" + Qlpawrate + "");
    } else {
    ui->localBox->setText("" + Qlpawrate + "");
    }

    if(peers > connectionPrevious)
    {
        ui->connectionBox->setText("" + QPeers + "");
    } else if(peers < connectionPrevious) {
        ui->connectionBox->setText("" + QPeers + "");
    } else {
        ui->connectionBox->setText("" + QPeers + "");
    }

    if(volume > volumePrevious)
    {
        ui->volumeBox->setText("" + qVolume + " BZL" + "");
    } else if(volume < volumePrevious) {
        ui->volumeBox->setText("" + qVolume + " BZL" + "");
    } else {
        ui->volumeBox->setText("" + qVolume + " BZL" + "");
    }

    updatePrevious(nHeight, nMinWeight, nNetworkWeight, phase, subsidy, pHardness, pHardness2, pPawrate2, Qlpawrate, peers, volume, marketcap);
}

void StatisticsPage::updatePrevious(int nHeight, int nMinWeight, int nNetworkWeight, QString phase, QString subsidy, double pHardness, double pHardness2, double pPawrate2, QString Qlpawrate, int peers, int volume, int64_t marketcap)
{
    heightPrevious = nHeight;
    stakeminPrevious = nMinWeight;
    stakemaxPrevious = nNetworkWeight;
    stakecPrevious = phase;
    rewardPrevious = subsidy;
    hardnessPrevious = pHardness;
    hardnessPrevious2 = pHardness2;
    netPawratePrevious = pPawrate2;
    pawratePrevious = Qlpawrate;
    connectionPrevious = peers;
    volumePrevious = volume;
	marketcapPrevious = marketcap;
}

void StatisticsPage::setModel(ClientModel *model)
{
    updateStatistics();
    this->model = model;
}

StatisticsPage::~StatisticsPage()
{
    delete ui;
}
<|endoftext|>


<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "rdb_protocol/error.hpp"

#include "backtrace.hpp"
#include "rdb_protocol/datum.hpp"
#include "rdb_protocol/term_walker.hpp"
#include "rdb_protocol/val.hpp"

namespace ql {

#ifdef RQL_ERROR_BT
#define RQL_ERROR_VAR
#else
#define RQL_ERROR_VAR __attribute__((unused))
#endif

void runtime_fail(base_exc_t::type_t type,
                  RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
                  RQL_ERROR_VAR int line,
                  std::string msg, const Backtrace *bt_src) {
#ifdef RQL_ERROR_BT
    msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
                    msg.c_str(), test, file, line);
#endif
    throw exc_t(type, msg, bt_src);
}
void runtime_fail(base_exc_t::type_t type,
                  RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
                  RQL_ERROR_VAR int line, std::string msg) {
#ifdef RQL_ERROR_BT
    msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
                    msg.c_str(), test, file, line);
#endif
    throw datum_exc_t(type, msg);
}

void runtime_sanity_check(bool test) {
    if (!test) {
        lazy_backtrace_t bt;
        throw exc_t(base_exc_t::GENERIC,
                    "SANITY CHECK FAILED (server is buggy).  Backtrace:\n" + bt.addrs(),
                    backtrace_t());
    }
}

base_exc_t::type_t exc_type(const datum_t *d) {
    r_sanity_check(d);
    return d->get_type() == datum_t::R_NULL
        ? base_exc_t::NON_EXISTENCE
        : base_exc_t::GENERIC;
}
base_exc_t::type_t exc_type(const counted_t<const datum_t> &d) {
    r_sanity_check(d.has());
    return exc_type(d.get());
}
base_exc_t::type_t exc_type(const val_t *v) {
    r_sanity_check(v);
    if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
        return exc_type(v->as_datum());
    } else {
        return base_exc_t::GENERIC;
    }
}
base_exc_t::type_t exc_type(const counted_t<val_t> &v) {
    r_sanity_check(v.has());
    return exc_type(v.get());
}

void backtrace_t::fill_bt(Backtrace *bt) const {
    for (std::list<backtrace_t::frame_t>::const_iterator
             it = frames.begin(); it != frames.end(); ++it) {
        if (it->is_skip()) continue;
        if (it->is_head()) {
            rassert(it == frames.begin());
            continue;
        }
        *bt->add_frames() = it->toproto();
    }
}
void backtrace_t::fill_error(Response *res, Response_ResponseType type,
                             std::string msg) const {
    guarantee(type == Response::CLIENT_ERROR ||
              type == Response::COMPILE_ERROR ||
              type == Response::RUNTIME_ERROR);
    Datum error_msg;
    error_msg.set_type(Datum::R_STR);
    error_msg.set_r_str(msg);
    res->set_type(type);
    *res->add_response() = error_msg;
    fill_bt(res->mutable_backtrace());
}
void fill_error(Response *res, Response_ResponseType type, std::string msg,
                const backtrace_t &bt) {
    bt.fill_error(res, type, msg);
}

Frame backtrace_t::frame_t::toproto() const {
    Frame f;
    switch(type) {
    case POS: {
        f.set_type(Frame_FrameType_POS);
        f.set_pos(pos);
    } break;
    case OPT: {
        f.set_type(Frame_FrameType_OPT);
        f.set_opt(opt);
    } break;
    default: unreachable();
    }
    return f;
}

backtrace_t::frame_t::frame_t(const Frame &f) {
    switch(f.type()) {
    case Frame::POS: {
        type = POS;
        pos = f.pos();
    } break;
    case Frame::OPT: {
        type = OPT;
        opt = f.opt();
    } break;
    default: unreachable();
    }
}

protob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t) {
    return t.make_child(&t->GetExtension(ql2::extension::backtrace));
}

void pb_rcheckable_t::propagate(Term *t) const {
    propagate_backtrace(t, bt_src.get());
}

} // namespace ql
<commit_msg>Used UNUSED in a place.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "rdb_protocol/error.hpp"

#include "backtrace.hpp"
#include "rdb_protocol/datum.hpp"
#include "rdb_protocol/term_walker.hpp"
#include "rdb_protocol/val.hpp"

namespace ql {

#ifdef RQL_ERROR_BT
#define RQL_ERROR_VAR
#else
#define RQL_ERROR_VAR UNUSED
#endif

void runtime_fail(base_exc_t::type_t type,
                  RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
                  RQL_ERROR_VAR int line,
                  std::string msg, const Backtrace *bt_src) {
#ifdef RQL_ERROR_BT
    msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
                    msg.c_str(), test, file, line);
#endif
    throw exc_t(type, msg, bt_src);
}
void runtime_fail(base_exc_t::type_t type,
                  RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
                  RQL_ERROR_VAR int line, std::string msg) {
#ifdef RQL_ERROR_BT
    msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
                    msg.c_str(), test, file, line);
#endif
    throw datum_exc_t(type, msg);
}

void runtime_sanity_check(bool test) {
    if (!test) {
        lazy_backtrace_t bt;
        throw exc_t(base_exc_t::GENERIC,
                    "SANITY CHECK FAILED (server is buggy).  Backtrace:\n" + bt.addrs(),
                    backtrace_t());
    }
}

base_exc_t::type_t exc_type(const datum_t *d) {
    r_sanity_check(d);
    return d->get_type() == datum_t::R_NULL
        ? base_exc_t::NON_EXISTENCE
        : base_exc_t::GENERIC;
}
base_exc_t::type_t exc_type(const counted_t<const datum_t> &d) {
    r_sanity_check(d.has());
    return exc_type(d.get());
}
base_exc_t::type_t exc_type(const val_t *v) {
    r_sanity_check(v);
    if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
        return exc_type(v->as_datum());
    } else {
        return base_exc_t::GENERIC;
    }
}
base_exc_t::type_t exc_type(const counted_t<val_t> &v) {
    r_sanity_check(v.has());
    return exc_type(v.get());
}

void backtrace_t::fill_bt(Backtrace *bt) const {
    for (std::list<backtrace_t::frame_t>::const_iterator
             it = frames.begin(); it != frames.end(); ++it) {
        if (it->is_skip()) continue;
        if (it->is_head()) {
            rassert(it == frames.begin());
            continue;
        }
        *bt->add_frames() = it->toproto();
    }
}
void backtrace_t::fill_error(Response *res, Response_ResponseType type,
                             std::string msg) const {
    guarantee(type == Response::CLIENT_ERROR ||
              type == Response::COMPILE_ERROR ||
              type == Response::RUNTIME_ERROR);
    Datum error_msg;
    error_msg.set_type(Datum::R_STR);
    error_msg.set_r_str(msg);
    res->set_type(type);
    *res->add_response() = error_msg;
    fill_bt(res->mutable_backtrace());
}
void fill_error(Response *res, Response_ResponseType type, std::string msg,
                const backtrace_t &bt) {
    bt.fill_error(res, type, msg);
}

Frame backtrace_t::frame_t::toproto() const {
    Frame f;
    switch(type) {
    case POS: {
        f.set_type(Frame_FrameType_POS);
        f.set_pos(pos);
    } break;
    case OPT: {
        f.set_type(Frame_FrameType_OPT);
        f.set_opt(opt);
    } break;
    default: unreachable();
    }
    return f;
}

backtrace_t::frame_t::frame_t(const Frame &f) {
    switch(f.type()) {
    case Frame::POS: {
        type = POS;
        pos = f.pos();
    } break;
    case Frame::OPT: {
        type = OPT;
        opt = f.opt();
    } break;
    default: unreachable();
    }
}

protob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t) {
    return t.make_child(&t->GetExtension(ql2::extension::backtrace));
}

void pb_rcheckable_t::propagate(Term *t) const {
    propagate_backtrace(t, bt_src.get());
}

} // namespace ql
<|endoftext|>


<commit_before>// Copyright 2013 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <string>
#include <fstream>
#include <map>
#include <vector>
#include <cctype>

#include <readConfiguration.hpp>
#include <utils.hpp>

void readPadding(std::map< std::string, unsigned int > & padding, const std::string & paddingFilename) {
	std::string temp;
	std::ifstream paddingFile(paddingFilename);

	while ( ! paddingFile.eof() ) {
		unsigned int middle = 0;

		std::getline(paddingFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		middle = temp.find(" ");
		padding.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));
	}
}

void readVectorWidth(std::map< std::string, unsigned int > & vectorWidth, const std::string & vectorFilename) {
	std::string temp;
	std::ifstream vectorFile(vectorFilename);

	while ( ! vectorFile.eof() ) {
		unsigned int middle = 0;

		std::getline(vectorFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		middle = temp.find(" ");
		vectorWidth.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));
	}
}

void readDedispersion(std::map< std::string, std::map< unsigned int, PulsarSearch::DedispersionConf > > & dedispersionParameters, const std::string  & dedispersionFilename) {
	std::string temp;
	std::ifstream dedispersionFile(dedispersionFilename);

	while ( ! dedispersionFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(dedispersionFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    PulsarSearch::DedispersionConf conf;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setLocalMem(isa::utils::castToType< std::string, bool >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setUnroll(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		conf.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( dedispersionParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, PulsarSearch::DedispersionConf > container;

			container.insert(std::make_pair(nrDMs, conf));
			dedispersionParameters.insert(std::make_pair(deviceName, container));
		} else {
			dedispersionParameters[deviceName].insert(std::make_pair(nrDMs, conf));
		}
	}
}

void readTranspose(std::map< std::string, std::map< unsigned int, isa::OpenCL::transposeConf > > & transposeParameters, const std::string & transposeFilename) {
	std::string temp;
	std::ifstream transposeFile(transposeFilename);

	while ( ! transposeFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(transposeFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    isa::OpenCL::transposeConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		parameters.setNrItemsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( transposeParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, isa::OpenCL::transposeConf > container;

			container.insert(std::make_pair(nrDMs, parameters));
			transposeParameters.insert(std::make_pair(deviceName, container));
		} else {
			transposeParameters[deviceName].insert(std::make_pair(nrDMs, parameters));
		}
	}
}

void readSNRD(std::map< std::string, std::map< unsigned int, PulsarSearch::snrDedispersedConf > > & snrParameters, const std::string & snrFilename) {
	std::string temp;
	std::ifstream snrFile(snrFilename);

	while ( ! snrFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(snrFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    PulsarSearch::snrDedispersedConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));

		if ( snrParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;

			container.insert(std::make_pair(nrDMs, parameters));
			snrParameters.insert(std::make_pair(deviceName, container));
		} else {
			snrParameters[deviceName].insert(std::make_pair(nrDMs, parameters));
		}
	}
}

void readFolding(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > > & foldingParameters, const std::string & foldingFilename) {
	std::string temp;
	std::ifstream foldingFile(foldingFilename);

	while ( ! foldingFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(foldingFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
		unsigned int nrPeriods = 0;
    PulsarSearch::FoldingConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrBinsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrBinsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		parameters.setVector(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( foldingParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > externalContainer;
      std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			externalContainer.insert(std::make_pair(nrDMs, internalContainer));
			foldingParameters.insert(std::make_pair(deviceName, externalContainer));
		} else if ( foldingParameters[deviceName].count(nrDMs) == 0 ) {
      std::map< unsigned int, std::vector< unsigned int > > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			foldingParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));
		} else {
			foldingParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));
		}
	}
}

void readSNRF(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > > & snrParameters, const std::string & snrFilename) {
	std::string temp;
	std::ifstream snrFile(snrFilename);

	while ( ! snrFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(snrFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
		unsigned int nrPeriods = 0;
    PulsarSearch::snrFoldedConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		parameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( snrParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > externalContainer;
      std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			externalContainer.insert(std::make_pair(nrDMs, internalContainer));
			snrParameters.insert(std::make_pair(deviceName, externalContainer));
		} else if ( snrParameters[deviceName].count(nrDMs) == 0 ) {
      std::map< unsigned int, std::vector< unsigned int > > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			snrParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));
		} else {
			snrParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));
		}
	}
}

<commit_msg>Fixing bugs.<commit_after>// Copyright 2013 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <string>
#include <fstream>
#include <map>
#include <cctype>

#include <readConfiguration.hpp>
#include <utils.hpp>

void readPadding(std::map< std::string, unsigned int > & padding, const std::string & paddingFilename) {
	std::string temp;
	std::ifstream paddingFile(paddingFilename);

	while ( ! paddingFile.eof() ) {
		unsigned int middle = 0;

		std::getline(paddingFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		middle = temp.find(" ");
		padding.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));
	}
}

void readVectorWidth(std::map< std::string, unsigned int > & vectorWidth, const std::string & vectorFilename) {
	std::string temp;
	std::ifstream vectorFile(vectorFilename);

	while ( ! vectorFile.eof() ) {
		unsigned int middle = 0;

		std::getline(vectorFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		middle = temp.find(" ");
		vectorWidth.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));
	}
}

void readDedispersion(std::map< std::string, std::map< unsigned int, PulsarSearch::DedispersionConf > > & dedispersionParameters, const std::string  & dedispersionFilename) {
	std::string temp;
	std::ifstream dedispersionFile(dedispersionFilename);

	while ( ! dedispersionFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(dedispersionFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    PulsarSearch::DedispersionConf conf;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setLocalMem(isa::utils::castToType< std::string, bool >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setUnroll(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		conf.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		conf.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( dedispersionParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, PulsarSearch::DedispersionConf > container;

			container.insert(std::make_pair(nrDMs, conf));
			dedispersionParameters.insert(std::make_pair(deviceName, container));
		} else {
			dedispersionParameters[deviceName].insert(std::make_pair(nrDMs, conf));
		}
	}
}

void readTranspose(std::map< std::string, std::map< unsigned int, isa::OpenCL::transposeConf > > & transposeParameters, const std::string & transposeFilename) {
	std::string temp;
	std::ifstream transposeFile(transposeFilename);

	while ( ! transposeFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(transposeFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    isa::OpenCL::transposeConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		parameters.setNrItemsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( transposeParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, isa::OpenCL::transposeConf > container;

			container.insert(std::make_pair(nrDMs, parameters));
			transposeParameters.insert(std::make_pair(deviceName, container));
		} else {
			transposeParameters[deviceName].insert(std::make_pair(nrDMs, parameters));
		}
	}
}

void readSNRD(std::map< std::string, std::map< unsigned int, PulsarSearch::snrDedispersedConf > > & snrParameters, const std::string & snrFilename) {
	std::string temp;
	std::ifstream snrFile(snrFilename);

	while ( ! snrFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(snrFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    PulsarSearch::snrDedispersedConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));

		if ( snrParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;

			container.insert(std::make_pair(nrDMs, parameters));
			snrParameters.insert(std::make_pair(deviceName, container));
		} else {
			snrParameters[deviceName].insert(std::make_pair(nrDMs, parameters));
		}
	}
}

void readFolding(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > > & foldingParameters, const std::string & foldingFilename) {
	std::string temp;
	std::ifstream foldingFile(foldingFilename);

	while ( ! foldingFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(foldingFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
		unsigned int nrPeriods = 0;
    PulsarSearch::FoldingConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrBinsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrBinsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		parameters.setVector(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( foldingParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > externalContainer;
      std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			externalContainer.insert(std::make_pair(nrDMs, internalContainer));
			foldingParameters.insert(std::make_pair(deviceName, externalContainer));
		} else if ( foldingParameters[deviceName].count(nrDMs) == 0 ) {
      std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			foldingParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));
		} else {
			foldingParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));
		}
	}
}

void readSNRF(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > > & snrParameters, const std::string & snrFilename) {
	std::string temp;
	std::ifstream snrFile(snrFilename);

	while ( ! snrFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(snrFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
		unsigned int nrPeriods = 0;
    PulsarSearch::snrFoldedConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		parameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( snrParameters.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > externalContainer;
      std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			externalContainer.insert(std::make_pair(nrDMs, internalContainer));
			snrParameters.insert(std::make_pair(deviceName, externalContainer));
		} else if ( snrParameters[deviceName].count(nrDMs) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			snrParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));
		} else {
			snrParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));
		}
	}
}

<|endoftext|>