text:
/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <miopen/db.hpp>
#include <miopen/db_record.hpp>
#include <miopen/errors.hpp>
#include <miopen/lock_file.hpp>
#include <miopen/logger.hpp>
#include <miopen/md5.hpp>

#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/none.hpp>
#include <boost/optional.hpp>

#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <fstream>
#include <ios>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <vector>

namespace miopen {

PlainTextDb::PlainTextDb(const std::string& filename_, bool is_system)
    : filename(filename_),
      lock_file(LockFile::Get(LockFilePath(filename_).c_str())),
      warning_if_unreadable(is_system)
{
    if(is_system)
    {
        MIOPEN_THROW("PlainTextDb class is not supported as system database. Use the ReadOnlyRamDb "
                     "class instead.");
    }

    if(!DisableUserDbFileIO)
    {
        auto file            = boost::filesystem::path(filename_);
        const auto directory = file.remove_filename();

        if(!(boost::filesystem::exists(directory)))
        {
            if(!boost::filesystem::create_directories(directory))
                MIOPEN_LOG_W("Unable to create a directory: " << directory);
            else
                boost::filesystem::permissions(directory, boost::filesystem::all_all);
        }
    }
}

#define MIOPEN_VALIDATE_LOCK(lock)                       \
    do                                                   \
    {                                                    \
        if(!(lock))                                      \
            MIOPEN_THROW("Db lock has failed to lock."); \
    } while(false)

static std::chrono::seconds GetLockTimeout() { return std::chrono::seconds{60}; }

using exclusive_lock = std::unique_lock<LockFile>;
using shared_lock    = std::shared_lock<LockFile>;

boost::optional<DbRecord> PlainTextDb::FindRecord(const std::string& key)
{
    if(DisableUserDbFileIO)
        return {};
    const auto lock = shared_lock(lock_file, GetLockTimeout());
    MIOPEN_VALIDATE_LOCK(lock);
    return FindRecordUnsafe(key, nullptr);
}

bool PlainTextDb::StoreRecord(const DbRecord& record)
{
    if(DisableUserDbFileIO)
        return true;
    const auto lock = exclusive_lock(lock_file, GetLockTimeout());
    MIOPEN_VALIDATE_LOCK(lock);
    return StoreRecordUnsafe(record);
}

bool PlainTextDb::UpdateRecord(DbRecord& record)
{
    if(DisableUserDbFileIO)
        return true;
    const auto lock = exclusive_lock(lock_file, GetLockTimeout());
    MIOPEN_VALIDATE_LOCK(lock);
    return UpdateRecordUnsafe(record);
}

bool PlainTextDb::RemoveRecord(const std::string& key)
{
    if(DisableUserDbFileIO)
        return true;
    const auto lock = exclusive_lock(lock_file, GetLockTimeout());
    MIOPEN_VALIDATE_LOCK(lock);
    return RemoveRecordUnsafe(key);
}

bool PlainTextDb::Remove(const std::string& key, const std::string& id)
{
    if(DisableUserDbFileIO)
        return true;
    const auto lock = exclusive_lock(lock_file, GetLockTimeout());
    MIOPEN_VALIDATE_LOCK(lock);
    auto record = FindRecordUnsafe(key, nullptr);
    if(!record)
        return false;
    bool erased = record->EraseValues(id);
    if(!erased)
        return false;
    return StoreRecordUnsafe(*record);
}

boost::optional<DbRecord> PlainTextDb::FindRecordUnsafe(const std::string& key,
                                                        RecordPositions* pos)
{
    if(pos != nullptr)
    {
        pos->begin = -1;
        pos->end   = -1;
    }

    MIOPEN_LOG_I2("Looking for key " << key << " in file " << filename);

    std::ifstream file(filename);

    if(!file)
    {
        const auto log_level = IsWarningIfUnreadable() && !MIOPEN_DISABLE_SYSDB
                                   ? LoggingLevel::Warning
                                   : LoggingLevel::Info2;
        MIOPEN_LOG(log_level, "File is unreadable: " << filename);
        return boost::none;
    }

    int n_line = 0;
    while(true)
    {
        std::string line;
        const auto line_begin = file.tellg();
        if(!std::getline(file, line))
            break;
        ++n_line;
        const auto next_line_begin = file.tellg();

        const auto key_size = line.find('=');
        const bool is_key   = (key_size != std::string::npos && key_size != 0);
        if(!is_key)
        {
            if(!line.empty()) // Do not blame empty lines.
            {
                MIOPEN_LOG_E("Ill-formed record: key not found: " << filename << "#" << n_line);
            }
            continue;
        }
        const auto current_key = line.substr(0, key_size);

        if(current_key != key)
        {
            continue;
        }
        MIOPEN_LOG_I2("Key match: " << current_key);
        const auto contents = line.substr(key_size + 1);

        if(contents.empty())
        {
            MIOPEN_LOG_E("None contents under the key: " << current_key << " form file " << filename
                                                         << "#" << n_line);
            continue;
        }
        MIOPEN_LOG_I2("Contents found: " << contents);

        DbRecord record(key);
        const bool is_parse_ok = record.ParseContents(contents);

        if(!is_parse_ok)
        {
            MIOPEN_LOG_E("Error parsing payload under the key: " << current_key << " form file "
                                                                 << filename << "#" << n_line);
            MIOPEN_LOG_E("Contents: " << contents);
        }
        // A record with matching key have been found.
        if(pos != nullptr)
        {
            pos->begin = line_begin;
            pos->end   = next_line_begin;
        }
        return record;
    }
    // Record was not found
    return boost::none;
}

static void Copy(std::istream& from, std::ostream& to, std::streamoff count)
{
    constexpr auto buffer_size_limit = 4 * 1024 * 1024;
    const auto buffer_size           = std::min<std::streamoff>(buffer_size_limit, count);
    auto buffer                      = std::vector<char>(buffer_size, 0);
    auto left                        = count;

    while(left > 0 && !from.eof())
    {
        const auto to_read = std::min<std::streamoff>(left, buffer_size);
        from.read(buffer.data(), to_read);
        const auto read = from.gcount();
        to.write(buffer.data(), read);
        left -= read;
    }
}

bool PlainTextDb::FlushUnsafe(const DbRecord& record, const RecordPositions* pos)
{
    assert(pos);

    if(pos->begin < 0 || pos->end < 0)
    {
        {
            std::ofstream file(filename, std::ios::app);

            if(!file)
            {
                MIOPEN_LOG_E("File is unwritable: " << filename);
                return false;
            }

            (void)file.tellp();
            record.WriteContents(file);
        }

        boost::filesystem::permissions(filename, boost::filesystem::all_all);
    }
    else
    {
        std::ifstream from(filename, std::ios::ate);

        if(!from)
        {
            MIOPEN_LOG_E("File is unreadable: " << filename);
            return false;
        }

        const auto temp_name = filename + ".temp";
        std::ofstream to(temp_name);

        if(!to)
        {
            MIOPEN_LOG_E("Temp file is unwritable: " << temp_name);
            return false;
        }

        const auto from_size = from.tellg();
        from.seekg(std::ios::beg);

        Copy(from, to, pos->begin);
        record.WriteContents(to);
        from.seekg(pos->end);
        Copy(from, to, from_size - pos->end);

        from.close();
        to.close();

        std::remove(filename.c_str());
        std::rename(temp_name.c_str(), filename.c_str());
        /// \todo What if rename fails? Thou shalt not loose the original file.
        boost::filesystem::permissions(filename, boost::filesystem::all_all);
    }
    return true;
}

bool PlainTextDb::StoreRecordUnsafe(const DbRecord& record)
{
    MIOPEN_LOG_I2("Storing record: " << record.key);
    RecordPositions pos;
    FindRecordUnsafe(record.key, &pos);
    return FlushUnsafe(record, &pos);
}

bool PlainTextDb::UpdateRecordUnsafe(DbRecord& record)
{
    RecordPositions pos;
    const auto old_record = FindRecordUnsafe(record.key, &pos);
    DbRecord new_record(record);
    if(old_record)
    {
        new_record.Merge(*old_record);
        MIOPEN_LOG_I2("Updating record: " << record.key);
    }
    else
    {
        MIOPEN_LOG_I2("Storing record: " << record.key);
    }
    bool result = FlushUnsafe(new_record, &pos);
    if(result)
        record = std::move(new_record);
    return result;
}

bool PlainTextDb::RemoveRecordUnsafe(const std::string& key)
{
    // Create empty record with same key and replace original with that
    // This will remove record
    MIOPEN_LOG_I("Removing record: " << key);
    RecordPositions pos;
    FindRecordUnsafe(key, &pos);
    const DbRecord empty_record(key);
    return FlushUnsafe(empty_record, &pos);
}

} // namespace miopen


text:
////////////////////////////////////////////////////////////////////////////////
//  Copyright (c) 2007-2016 Hartmut Kaiser
//  Copyright (c) 2008-2009 Chirag Dekate, Anshul Tandon
//  Copyright (c) 2012-2013 Thomas Heller
//
//  SPDX-License-Identifier: BSL-1.0
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////

#pragma once

#include <hpx/config.hpp>
#include <hpx/assert.hpp>
#include <hpx/modules/errors.hpp>
#include <hpx/topology/cpu_mask.hpp>

#include <boost/variant.hpp>

#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <utility>
#include <vector>

namespace hpx { namespace threads {
    namespace detail {
        typedef std::vector<std::int64_t> bounds_type;

        enum distribution_type
        {
            compact = 0x01,
            scatter = 0x02,
            balanced = 0x04,
            numa_balanced = 0x08
        };

        struct spec_type
        {
            enum type
            {
                unknown,
                thread,
                socket,
                numanode,
                core,
                pu
            };
            HPX_CORE_EXPORT static char const* type_name(type t);

            static std::int64_t all_entities()
            {
                return (std::numeric_limits<std::int64_t>::min)();
            }

            spec_type(type t = unknown, std::int64_t min = all_entities(),
                std::int64_t max = all_entities())
              : type_(t)
              , index_bounds_()
            {
                if (t != unknown)
                {
                    if (max == 0 || max == all_entities())
                    {
                        // one or all entities
                        index_bounds_.push_back(min);
                    }
                    else if (min != all_entities())
                    {
                        // all entities between min and -max, or just min,max
                        HPX_ASSERT(min >= 0);
                        index_bounds_.push_back(min);
                        index_bounds_.push_back(max);
                    }
                }
            }

            bool operator==(spec_type const& rhs) const
            {
                if (type_ != rhs.type_ ||
                    index_bounds_.size() != rhs.index_bounds_.size())
                    return false;

                for (std::size_t i = 0; i < index_bounds_.size(); ++i)
                {
                    if (index_bounds_[i] != rhs.index_bounds_[i])
                        return false;
                }

                return true;
            }

            type type_;
            bounds_type index_bounds_;
        };

        typedef std::vector<spec_type> mapping_type;
        typedef std::pair<spec_type, mapping_type> full_mapping_type;
        typedef std::vector<full_mapping_type> mappings_spec_type;
        typedef boost::variant<distribution_type, mappings_spec_type>
            mappings_type;

        HPX_CORE_EXPORT bounds_type extract_bounds(
            spec_type const& m, std::size_t default_last, error_code& ec);

        HPX_CORE_EXPORT void parse_mappings(std::string const& spec,
            mappings_type& mappings, error_code& ec = throws);
    }    // namespace detail

    HPX_CORE_EXPORT void parse_affinity_options(std::string const& spec,
        std::vector<mask_type>& affinities, std::size_t used_cores,
        std::size_t max_cores, std::size_t num_threads,
        std::vector<std::size_t>& num_pus, bool use_process_mask,
        error_code& ec = throws);

    // backwards compatibility helper
    inline void parse_affinity_options(std::string const& spec,
        std::vector<mask_type>& affinities, error_code& ec = throws)
    {
        std::vector<std::size_t> num_pus;
        parse_affinity_options(
            spec, affinities, 1, 1, affinities.size(), num_pus, false, ec);
    }
}}    // namespace hpx::threads

ext: hpp

max_stars_repo_name: sudo-panda/hpx

max_issues_repo_name: sudo-panda/hpx

max_forks_repo_name: sudo-panda/hpx


text:
//
// Created by jiashuai on 17-11-7.
//
#include <config.h>

#ifndef USE_CUDA
#include <thundersvm/kernel/kernelmatrix_kernel.h>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <iostream>
#include <fstream>
namespace svm_kernel {
    void
    get_working_set_ins(const SyncData<float_type> &val, const SyncData<int> &col_ind, const SyncData<int> &row_ptr,
                        const SyncData<int> &data_row_idx, SyncData<float_type> &data_rows, int m) {
#pragma omp parallel for
        for (int i = 0; i < m; i++) {
            int row = data_row_idx[i];
            for (int j = row_ptr[row]; j < row_ptr[row + 1]; ++j) {
                int col = col_ind[j];
                data_rows[col * m + i] = val[j]; // row-major for cuSPARSE
            }
        }
    }

    void
    RBF_kernel(const SyncData<float_type> &self_dot0, const SyncData<float_type> &self_dot1,
               SyncData<float_type> &dot_product, int m,
               int n, float_type gamma) {
#pragma omp parallel for
        for (int idx = 0; idx < m * n; idx++) {
            int i = idx / n;//i is row id
            int j = idx % n;//j is column id
            dot_product[idx] = expf(-(self_dot0[i] + self_dot1[j] - dot_product[idx] * 2) * gamma);
        }
    }

    void
    RBF_kernel(const SyncData<int> &self_dot0_idx, const SyncData<float_type> &self_dot1,
               SyncData<float_type> &dot_product, int m,
               int n, float_type gamma) {
#pragma omp parallel for
        for (int idx = 0; idx < m * n; idx++) {
            int i = idx / n;//i is row id
            int j = idx % n;//j is column id
            dot_product[idx] = expf(-(self_dot1[self_dot0_idx[i]] + self_dot1[j] - dot_product[idx] * 2) * gamma);
        }

    }

    void poly_kernel(SyncData<float_type> &dot_product, float_type gamma, float_type coef0, int degree, int mn) {
#pragma omp parallel for
        for (int idx = 0; idx < mn; idx++) {
            dot_product[idx] = powf(gamma * dot_product[idx] + coef0, degree);
        }
    }

    void sigmoid_kernel(SyncData<float_type> &dot_product, float_type gamma, float_type coef0, int mn) {
#pragma omp parallel for
        for (int idx = 0; idx < mn; idx++) {
            dot_product[idx] = tanhf(gamma * dot_product[idx] + coef0);
        }
    }

    void sum_kernel_values(const SyncData<float_type> &coef, int total_sv, const SyncData<int> &sv_start,
                           const SyncData<int> &sv_count, const SyncData<float_type> &rho,
                           const SyncData<float_type> &k_mat,
                           SyncData<float_type> &dec_values, int n_classes, int n_instances) {
#pragma omp parallel for
        for (int idx = 0; idx < n_instances; idx++) {
            int k = 0;
            int n_binary_models = n_classes * (n_classes - 1) / 2;
            for (int i = 0; i < n_classes; ++i) {
                for (int j = i + 1; j < n_classes; ++j) {
                    int si = sv_start[i];
                    int sj = sv_start[j];
                    int ci = sv_count[i];
                    int cj = sv_count[j];
                    const float_type *coef1 = &coef[(j - 1) * total_sv];
                    const float_type *coef2 = &coef[i * total_sv];
                    const float_type *k_values = &k_mat[idx * total_sv];
                    float_type sum = 0;
#pragma omp parallel for reduction(+:sum)
                    for (int l = 0; l < ci; ++l) {
                        sum += coef1[si + l] * k_values[si + l];
                    }
#pragma omp parallel for reduction(+:sum)
                    for (int l = 0; l < cj; ++l) {
                        sum += coef2[sj + l] * k_values[sj + l];
                    }
                    dec_values[idx * n_binary_models + k] = sum - rho[k];
                    k++;
                }
            }
        }
    }

    void dns_csr_mul(int m, int n, int k, const SyncData<float_type> &dense_mat, const SyncData<float_type> &csr_val,
                     const SyncData<int> &csr_row_ptr, const SyncData<int> &csr_col_ind, int nnz,
                     SyncData<float_type> &result) {
        /*
        for(int row = 0; row < m; row ++){
            int nz_value_num = csr_row_ptr[row + 1] - csr_row_ptr[row];
            if(nz_value_num != 0){
                for(int col = 0; col < n; col++){
                    float_type sum = 0;
                    for(int nz_value_index = csr_row_ptr[row]; nz_value_index < csr_row_ptr[row + 1]; nz_value_index++){
                        sum += csr_val[nz_value_index] * dense_mat[col + csr_col_ind[nz_value_index] * n];
                    }
                    result[row * n + col] = sum;
                }
            }
        }
        */
	Eigen::Map<const Eigen::MatrixXf> denseMat(dense_mat.host_data(), n, k);
	Eigen::Map<const Eigen::SparseMatrix<float, Eigen::RowMajor>> sparseMat(m, k, nnz, csr_row_ptr.host_data(),
                                                                                csr_col_ind.host_data(),
                                                                                csr_val.host_data());
    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> dense_tran = denseMat.transpose();
	Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> retMat = sparseMat * dense_tran;
	Eigen::Map < Eigen::Matrix < float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor > > (result.host_data(),
                retMat.rows(),
                retMat.cols()) = retMat;

    }
}
#endif

ext: cpp

max_stars_repo_name: SoldierChen/thundersvm

max_issues_repo_name: SoldierChen/thundersvm

max_forks_repo_name: SoldierChen/thundersvm


text:
#ifndef GAMESETTINGS_HPP
#define GAMESETTINGS_HPP

#include <QTextStream>
#include <QStringList>
#include <QString>
#include <QMap>

#include <boost/filesystem/path.hpp>

namespace Files
{
  typedef std::vector<boost::filesystem::path> PathContainer;
  struct ConfigurationManager;
}

namespace Launcher
{
    class GameSettings
    {
    public:
        GameSettings(Files::ConfigurationManager &cfg);
        ~GameSettings();

        inline QString value(const QString &key, const QString &defaultValue = QString())
        {
            return mSettings.value(key).isEmpty() ? defaultValue : mSettings.value(key);
        }

        inline void setValue(const QString &key, const QString &value)
        {
            mSettings.insert(key, value);
            mUserSettings.insert(key, value);
        }

        inline void setMultiValue(const QString &key, const QString &value)
        {
            QStringList values = mSettings.values(key);
            if (!values.contains(value))
                mSettings.insertMulti(key, value);

            values = mUserSettings.values(key);
            if (!values.contains(value))
                mUserSettings.insertMulti(key, value);
        }

        inline void remove(const QString &key)
        {
            mSettings.remove(key);
            mUserSettings.remove(key);
        }

        inline QStringList getDataDirs() { return mDataDirs; }
        inline void addDataDir(const QString &dir) { if(!dir.isEmpty()) mDataDirs.append(dir); }
        inline QString getDataLocal() {return mDataLocal; }

        bool hasMaster();

        QStringList values(const QString &key, const QStringList &defaultValues = QStringList());

        bool readFile(QTextStream &stream);
        bool readFile(QTextStream &stream, QMap<QString, QString> &settings);
        bool readUserFile(QTextStream &stream);

        bool writeFile(QTextStream &stream);

    private:
        Files::ConfigurationManager &mCfgMgr;

        void validatePaths();
        QMap<QString, QString> mSettings;
        QMap<QString, QString> mUserSettings;

        QStringList mDataDirs;
        QString mDataLocal;
    };
}
#endif // GAMESETTINGS_HPP

max_stars_repo_name: Bodillium/openmw

max_issues_repo_name: Bodillium/openmw

max_forks_repo_name: Bodillium/openmw


text:
#include <pbcopper/poa/PoaConsensus.h>

#include <cstdlib>

#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/assign.hpp>
#include <boost/assign/std/vector.hpp>

#include <pbcopper/align/AlignConfig.h>

#include <gtest/gtest.h>

using boost::erase_all_copy;

using namespace boost::assign;  // NOLINT
using namespace PacBio::Poa;    // NOLINT
using namespace PacBio::Align;  // NOLINT

#define MAKE_ALL_PLOTS false

namespace PoaConsensusTests {
namespace {

void plotConsensus(const PacBio::Poa::PoaConsensus* pc, std::string description,
                   bool REALLY_MAKE_THIS_ONE = false)
{
    if (MAKE_ALL_PLOTS || REALLY_MAKE_THIS_ONE) {
        std::string dotFname = description + ".dot";
        std::string pngFname = description + ".png";
        std::string cmd = std::string("dot -Tpng ") + dotFname + " > " + pngFname;
        pc->Graph.WriteGraphVizFile(description + ".dot",
                                    (PoaGraph::COLOR_NODES | PoaGraph::VERBOSE_NODES), pc);
        // std::cout << cmd << std::endl;
        const int result = std::system(cmd.c_str());
        if (result) {
            std::cerr << "Running '" << cmd << "' failed\n";
        }
    }
}

}  // namespace
}  // namespace PoaConsensusTests

// TEST(PoaGraph, NoReadsTest)
// {
//  // Test that it works with no reads
//  std::vector<const SequenceFeatures*> reads;
//  std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{PoaConsensus::findConsensus(reads,
//  PoaConfig::GLOBAL_ALIGNMENT)};
//  std::string dot = pc->getGraph()->toGraphViz();
//  std::cout << dot << std::endl;
// }

TEST(PoaGraph, SmallBasicTest1)
{
    // Test that it works with a single sequence
    std::vector<std::string> reads;
    reads += "GGG";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
    std::string dot = pc->Graph.ToGraphViz();
    std::string expectedDot =
        "digraph G {"
        "rankdir=\"LR\";"
        "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
        "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
        "2[shape=Mrecord, label=\"{ G | 1 }\"];"
        "3[shape=Mrecord, label=\"{ G | 1 }\"];"
        "4[shape=Mrecord, label=\"{ G | 1 }\"];"
        "0->2 ;"
        "2->3 ;"
        "3->4 ;"
        "4->1 ;"
        "}";
    PoaConsensusTests::plotConsensus(pc.get(), "small-basic-1");
    EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
    EXPECT_EQ("GGG", pc->Sequence);
}

TEST(PoaGraph, SmallBasicTest2)
{
    // Test that it works with two identical sequences
    std::vector<std::string> reads;
    reads += "GGG", "GGG";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
    std::string dot = pc->Graph.ToGraphViz();
    std::string expectedDot =
        "digraph G {"
        "rankdir=\"LR\";"
        "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
        "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
        "2[shape=Mrecord, label=\"{ G | 2 }\"];"
        "3[shape=Mrecord, label=\"{ G | 2 }\"];"
        "4[shape=Mrecord, label=\"{ G | 2 }\"];"
        "0->2 ;"
        "2->3 ;"
        "3->4 ;"
        "4->1 ;"
        "}";
    PoaConsensusTests::plotConsensus(pc.get(), "small-basic-2");
    EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
    EXPECT_EQ("GGG", pc->Sequence);
}

TEST(PoaGraph, SmallExtraTests)
{
    // Extra at beginning
    {
        std::vector<std::string> reads;
        reads += "GGG", "TGGG";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 2 }\"];"
            "3[shape=Mrecord, label=\"{ G | 2 }\"];"
            "4[shape=Mrecord, label=\"{ G | 2 }\"];"
            "5[shape=Mrecord, label=\"{ T | 1 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "5->2 ;"
            "0->5 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "extra-at-beginning");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("GGG", pc->Sequence);
    }

    // Extra in middle
    {
        std::vector<std::string> reads;
        reads += "GGG", "GTGG";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        // this would be easier if we could use the C++0x raw
        // strings feature (in g++ 4.5+)
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 2 }\"];"
            "3[shape=Mrecord, label=\"{ G | 2 }\"];"
            "4[shape=Mrecord, label=\"{ G | 2 }\"];"
            "5[shape=Mrecord, label=\"{ T | 1 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "5->3 ;"
            "2->5 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "extra-in-middle");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("GGG", pc->Sequence);
    }

    // Extra at end
    {
        std::vector<std::string> reads;
        reads += "GGG", "GGGT";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 2 }\"];"
            "3[shape=Mrecord, label=\"{ G | 2 }\"];"
            "4[shape=Mrecord, label=\"{ G | 2 }\"];"
            "5[shape=Mrecord, label=\"{ T | 1 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "5->1 ;"
            "4->5 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "extra-at-end");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("GGG", pc->Sequence);
    }
}

TEST(PoaGraph, SmallMismatchTests)
{
    // Mismatch at beginning
    {
        std::vector<std::string> reads;
        reads += "GGG", "TGG";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 1 }\"];"
            "3[shape=Mrecord, label=\"{ G | 2 }\"];"
            "4[shape=Mrecord, label=\"{ G | 2 }\"];"
            "5[shape=Mrecord, label=\"{ T | 1 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "5->3 ;"
            "0->5 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "mismatch-at-beginning");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("GG", pc->Sequence);
    }

    // Mismatch in middle
    {
        std::vector<std::string> reads;
        reads += "GGG", "GTG", "GTG";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 3 }\"];"
            "3[shape=Mrecord, label=\"{ G | 1 }\"];"
            "4[shape=Mrecord, label=\"{ G | 3 }\"];"
            "5[shape=Mrecord, label=\"{ T | 2 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "5->4 ;"
            "2->5 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "mismatch-in-middle");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("GTG", pc->Sequence);
    }

    // Mismatch at end
    {
        std::vector<std::string> reads;
        reads += "GGG", "GGT";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 2 }\"];"
            "3[shape=Mrecord, label=\"{ G | 2 }\"];"
            "4[shape=Mrecord, label=\"{ G | 1 }\"];"
            "5[shape=Mrecord, label=\"{ T | 1 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "5->1 ;"
            "3->5 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "mismatch-at-end");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("GG", pc->Sequence);
    }
}

TEST(PoaGraph, SmallDeletionTests)
{
    // Deletion at beginning
    {
        std::vector<std::string> reads;
        reads += "GAT", "AT";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 1 }\"];"
            "3[shape=Mrecord, label=\"{ A | 2 }\"];"
            "4[shape=Mrecord, label=\"{ T | 2 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "0->3 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "deletion-at-beginning");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("AT", pc->Sequence);
    }

    // Deletion in middle
    {
        std::vector<std::string> reads;
        reads += "GAT", "GT";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 2 }\"];"
            "3[shape=Mrecord, label=\"{ A | 1 }\"];"
            "4[shape=Mrecord, label=\"{ T | 2 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "2->4 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "deletion-in-middle");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
    }

    // Deletion at end
    {
        std::vector<std::string> reads;
        reads += "GAT", "GA";
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
        std::string dot = pc->Graph.ToGraphViz();
        std::string expectedDot =
            "digraph G {"
            "rankdir=\"LR\";"
            "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
            "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
            "2[shape=Mrecord, label=\"{ G | 2 }\"];"
            "3[shape=Mrecord, label=\"{ A | 2 }\"];"
            "4[shape=Mrecord, label=\"{ T | 1 }\"];"
            "0->2 ;"
            "2->3 ;"
            "3->4 ;"
            "4->1 ;"
            "3->1 ;"
            "}";
        PoaConsensusTests::plotConsensus(pc.get(), "deletion-at-end");
        EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
        EXPECT_EQ("GA", pc->Sequence);
    }
}

TEST(PoaConsensus, TestSimple)
{
    std::vector<std::string> reads;
    reads += "TTTACAGGATAGTCCAGT", "ACAGGATACCCCGTCCAGT", "ACAGGATAGTCCAGT",
        "TTTACAGGATAGTCCAGTCCCC", "TTTACAGGATTAGTCCAGT", "TTTACAGGATTAGGTCCCAGT",
        "TTTACAGGATAGTCCAGT";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
    PoaConsensusTests::plotConsensus(pc.get(), "simple");
    EXPECT_EQ("TTTACAGGATAGTCCAGT", pc->Sequence);
}

TEST(PoaConsensus, TestOverhangSecond)
{
    std::vector<std::string> reads;
    reads += "TTTACAGGATAGTCCAGT", "TTTACAGGATAGTCCAGTAAA", "TTTACAGGATAGTCCAGTAAA";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
    EXPECT_EQ("TTTACAGGATAGTCCAGTAAA", pc->Sequence);
}

TEST(PoaConsensus, SmallSemiglobalTest)
{
    std::vector<std::string> reads;
    reads += "GGTGG", "GGTGG", "T";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::SEMIGLOBAL)};
    PoaConsensusTests::plotConsensus(pc.get(), "small-semiglobal");
    std::string expectedDot =
        "digraph G {"
        "rankdir=\"LR\";"
        "0[shape=Mrecord, label=\"{ ^ | 0 }\"];"
        "1[shape=Mrecord, label=\"{ $ | 0 }\"];"
        "2[shape=Mrecord, label=\"{ G | 2 }\"];"
        "3[shape=Mrecord, label=\"{ G | 2 }\"];"
        "4[shape=Mrecord, label=\"{ T | 3 }\"];"
        "5[shape=Mrecord, label=\"{ G | 2 }\"];"
        "6[shape=Mrecord, label=\"{ G | 2 }\"];"
        "0->2 ;"
        "2->3 ;"
        "3->4 ;"
        "4->5 ;"
        "5->6 ;"
        "6->1 ;"
        "4->1 ;"
        "0->4 ;"
        "}";
    std::string dot = pc->Graph.ToGraphViz();
    EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
    EXPECT_EQ("GGTGG", pc->Sequence);
}

TEST(PoaConsensus, SmallTilingTest)
{
    std::vector<std::string> reads;
    reads += "GGGGAAAA", "AAAATTTT", "TTTTCCCC", "CCCCAGGA";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::SEMIGLOBAL)};
    PoaConsensusTests::plotConsensus(pc.get(), "small-tiling");
    EXPECT_EQ("GGGGAAAATTTTCCCCAGGA", pc->Sequence);
}

TEST(PoaConsensus, TestVerboseGraphVizOutput)
{
    std::vector<std::string> reads;
    reads += "GGG", "TGGG";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
    std::string dot =
        pc->Graph.ToGraphViz(PoaGraph::COLOR_NODES | PoaGraph::VERBOSE_NODES, pc.get());

    std::string expectedDot =
        "digraph G {"
        "rankdir=\"LR\";"
        "0[shape=Mrecord, label=\"{ { 0 | ^ } | { 0 | 0 } | { 0.00 | 0.00 } "
        "}\"];"
        "1[shape=Mrecord, label=\"{ { 1 | $ } | { 0 | 0 } | { 0.00 | 0.00 } "
        "}\"];"
        "2[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" ,"
        " label=\"{ { 2 | G } | { 2 | 2 } | { 2.00 | 2.00 } }\"];"
        "3[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" ,"
        " label=\"{ { 3 | G } | { 2 | 2 } | { 2.00 | 4.00 } }\"];"
        "4[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" ,"
        " label=\"{ { 4 | G } | { 2 | 2 } | { 2.00 | 6.00 } }\"];"
        "5[shape=Mrecord, label=\"{ { 5 | T } | { 1 | 2 } | { -0.00 | -0.00 } "
        "}\"];"
        "0->2 ;"
        "2->3 ;"
        "3->4 ;"
        "4->1 ;"
        "5->2 ;"
        "0->5 ;}";

    EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
}

TEST(PoaConsensus, TestLocalStaggered)
{
    // Adapted from Pat's C# test
    std::vector<std::string> reads;
    reads += "TTTACAGGATAGTGCCGCCAATCTTCCAGT", "GATACCCCGTGCCGCCAATCTTCCAGTATATACAGCACGAGTAGC",
        "ATAGTGCCGCCAATCTTCCAGTATATACAGCACGGAGTAGCATCACGTACGTACGTCTACACGTAATT",
        "ACGTCTACACGTAATTTTGGAGAGCCCTCTCTCACG", "ACACGTAATTTTGGAGAGCCCTCTCTTCACG",
        "AGGATAGTGCCGCCAATCTTCCAGTAATATACAGCACGGAGTAGCATCACGTACG",
        "ATAGTGCCGCCAATCTTCCAGTATATACAGCACGGAGTAGCATCACGTACGTACGTCTACACGT";

    // 4 is a magic number here.  the .NET code had an entrenched
    // assumption that sequences in POA were subreads from a ZMW, so
    // the minCoverage was (numReads - 3), under assumption that basal
    // coverage for CCS is (numReads-2) (beginning, end read).
    // Application has to provide a sensible minCoverage.
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::LOCAL, 4)};
    PoaConsensusTests::plotConsensus(pc.get(), "local-staggered", false);
    EXPECT_EQ("ATAGTGCCGCCAATCTTCCAGTATATACAGCACGGAGTAGCATCACGTACGTACGTCTACACGTAATT", pc->Sequence);
}

TEST(PoaConsensus, TestLongInsert)
{
    // Adapted from Pat's C# test
    std::vector<std::string> reads;
    reads +=
        "TTTACAGGATAGTGCCGCCAATCTTCCAGTGATACCCCGTGCCGCCAATCTTCCAGTATATACAGCACGA"
        "GGTAGC",
        "TTTACAGGATAGTGCCGGCCAATCTTCCAGTGATACCCCGTGCCGCCAATCTTCCAGTATATACAGCACG"
        "AGTAGC",
        "TTGTACAGGATAGTGCCGCCAATCTTCCAGTGATGGGGGGGGGGGGGGGGGGGGGGGGGGGACCCCGTGC"
        "CGCCAATCTTCCAGTATATACAGCACGAGTAGC";
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
    EXPECT_EQ(
        "TTTACAGGATAGTGCCGCCAATCTTCCAGTGATACCCCGTGCCGCCAATCTTCCAGTATATACAGCACGA"
        "GTAGC",
        pc->Sequence);
}

TEST(PoaConsensus, TestSpanningReads)
{
    std::string read1 = "GAAAG";
    std::string read2 = "GATAG";
    std::vector<std::string> reads{read1, read1, read1, read2, read2, read2};
    std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
        PoaConsensus::FindConsensus(reads, AlignMode::LOCAL)};
    PoaConsensusTests::plotConsensus(pc.get(), "spanning-reads");

    std::string dot =
        pc->Graph.ToGraphViz(PoaGraph::VERBOSE_NODES | PoaGraph::COLOR_NODES, pc.get());
    // We expect to get spanning reads of 6 for the middle A/T nodes,
    // but each only has 3 reads passing through.
    // The PoaGraph doesn't really expose an API, we can only check it
    // by looking at the GraphViz output.

    // clang-format off
    std::string expectedDot =
        "digraph G {"
        "rankdir=\"LR\";"
        "0[shape=Mrecord, label=\"{ { 0 | ^ } | { 0 | 0 } | { 0.00 | 0.00 } }\"];"
        "1[shape=Mrecord, label=\"{ { 1 | $ } | { 0 | 0 } | { 0.00 | 0.00 } }\"];"
        "2[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" , label=\"{ { 2 | G } | { 6 | 6 } | { 6.00 | 6.00 } }\"];"
        "3[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" , label=\"{ { 3 | A } | { 6 | 6 } | { 6.00 | 12.00 } }\"];"
        "4[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" , label=\"{ { 4 | A } | { 3 | 6 } | { -0.00 | 12.00 } }\"];"
        "5[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" , label=\"{ { 5 | A } | { 6 | 6 } | { 6.00 | 18.00 } }\"];"
        "6[shape=Mrecord, style=\"filled\", fillcolor=\"lightblue\" , label=\"{ { 6 | G } | { 6 | 6 } | { 6.00 | 24.00 } }\"];"
        "7[shape=Mrecord, label=\"{ { 7 | T } | { 3 | 6 } | { -0.00 | 12.00 } }\"];"
        "0->2 ;"
        "2->3 ;"
        "3->4 ;"
        "4->5 ;"
        "5->6 ;"
        "6->1 ;"
        "7->5 ;"
        "3->7 ;"
        "}";
    // clang-format on

    EXPECT_EQ(expectedDot, erase_all_copy(dot, "\n"));
}

TEST(PoaConsensus, NondeterminismRegressionTest)
{
    //
    // This is a regression test for a real-world case of
    // nondeterminism found in the POA on a quiver job on Staph.
    //
    std::vector<std::string> reads;
    reads +=
        "TATCAATCAACGAAATTCGCCAATTCCGTCATGAATGTCAATATCTAACTACACTTTAGAATACATTCTT"
        "TGACATGCCTGGCCTATTGATATTTCAATAAAATCAGACTATAAAGACAACTTACAAATGATCCTATAAA"
        "TTAAAGATCGAGAATCTAAAGAGTGAAATTAAAGCTAATTACTGCTTTAAAAATTTTACGTGCACACAAA"
        "AATGAATTTATCCTCATTATATCGAAAATACCATGAAGTATAGTAAGCTAACTTGAATATGATCATTAAT"
        "CGGCTATATGATTATTTTGATAATGCAATGAGCATCAATCTGAATTTATGACCTATCATTCGCGTTGCAT"
        "TTATTGAAGTGAAAATTCATGTACGCTTTTTTATTTTATTAATATAATCCTTGATATTGGTTATATACCA"
        "CGCTGTCACATAATTTTCAATAAATTTTTCTACTAAATGAAGTGTCTGTTATCTATCAC";
    reads +=
        "TATCAACAACGAAAATGCGCAGTTACGTCATGATTTATGTCAAATAATCTAAACGACACTTTCAGAAATA"
        "AATACATTCGAGAAGATGAATGCCTGGCGCAAAGTGATTATTTCAATAAAATATTTGTACCTTGAAAGAC"
        "AATTTACAAATGAATGCTATAAAATTTAAATGGATCCGGAGAATCTTTAAAGTACGTGAAATTAAAGGCT"
        "AAGATTACTGCGAAAAATTTTCGTGCACAAGAAATGAATGTTCCAGATTAGTATCGGAAAATAAGCCATG"
        "AAGAAGCTAGCATTAACTTGAATATGATCGATTTAATCGGCAGTATTGGTAATTATCTTGATAAGCAATT"
        "GAGCATCAACTGAAATTGAATGACTCTACATGCCTCGCTGAGTATGCGATTTATTGAAAGTGAAATTCAG"
        "TAAAGTTTATTGTTATGAATAAATGCGTACTTGGATGAATATCCCGACGGTAGTTCAAGTGTAAATGGAG"
        "TGAGGGGGTTCTTTCTTATAGAATAGTTTTATACTACTGATAAGGTGTAACCTGAGTGAGTCGTGATTTT"
        "AGAGTTACTTGCGAAC";

    std::set<std::string> answers;
    for (int run = 0; run < 100; run++) {
        std::unique_ptr<const PacBio::Poa::PoaConsensus> pc{
            PoaConsensus::FindConsensus(reads, AlignMode::GLOBAL)};
#if 0
        char fname[100];
        sprintf(fname, "/tmp/gr%03d.dot", run);
        pc->WriteGraphVizFile(fname, (PoaGraph::VERBOSE_NODES | PoaGraph::COLOR_NODES));
#endif
        answers.insert(pc->Sequence);
    }
    ASSERT_EQ(1, answers.size());
}

max_stars_repo_name: PacificBiosciences/pbcopper

max_issues_repo_name: PacificBiosciences/pbcopper

max_forks_repo_name: PacificBiosciences/pbcopper


text:
/************************************************************************
 Copyright 2018 andrewpqc@mails.ccnu.edu.cn
 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.
 ************************************************************************/

#ifndef __VOGRO_TEST_REQUEST_HPP__
#define __VOGRO_TEST_REQUEST_HPP__

#include "utils.hpp"
#include "response.hpp"

#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <boost/asio.hpp>

using namespace boost::asio;

namespace vogro {

    class Request:std::enable_shared_from_this<Request> {
    private:

        std::string ip;
        std::string port;

        std::string method;
        const std::string &pathTpl;
        std::string requestURL;

        std::map <std::string, std::string> headers;
        std::map <std::string, std::string> resHeaders;
        std::map <std::string, std::string> queryParams;
        std::map <std::string, std::string> pathParams;

        std::string body;
        std::shared_ptr <ip::tcp::socket> &socket;

        std::string getBaseURL(std::string tplURL,
                               std::map <std::string, std::string> pathParam) {
            auto length = tplURL.length();
            std::string realPath;
            for (int i = 0; i < length; i++)
                if (tplURL[i] == '{') {
                    std::string key;
                    for (int j = i + 1; j < length; j++)
                        if (tplURL[j] == '}') {
                            auto got = pathParam.find(key);
                            if (got == pathParam.end()) throw "unknow key" + key;
                            else { realPath += got->second; i = j; break; }
                        } else key += tplURL[j];
                } else realPath += tplURL[i];

            if (realPath.back() != '/') realPath += '/';

            return realPath;
        }

        std::string getRequestURL(std::map <std::string, std::string> queryParameters) {
            std::stringstream pathStream;

            pathStream << getBaseURL(this->pathTpl, this->pathParams);

            if (!queryParameters.empty()) pathStream << "?";

            for (auto it : queryParameters)
                pathStream << it.first << "=" << it.second << "&";

            auto finalPath = pathStream.str();
            if (finalPath.back() == '&') finalPath.pop_back();

            return finalPath;
        }

        std::string makeRequestMessage() {
            this->headers["Host"] = this->ip + ":" + this->port;;

            auto reqURL = this->getRequestURL(this->queryParams);
            this->requestURL = reqURL;

            std::stringstream ss;
            ss << this->method << " " << url_encode(reqURL) << " HTTP/1.1\r\n";

            for (auto header : this->headers)
                ss << header.first << ": " << header.second << "\r\n";

            ss << "Content-Length: " << this->body.length() << "\r\n";
            ss << "\r\n";
            ss << this->body;
            return ss.str();
        }

    public:
        Request(const std::string &mthd, const std::string &path,
                std::shared_ptr <boost::asio::ip::tcp::socket> &sock,
                const std::string &serverIP, const std::string &serverPort)
                : method(mthd), pathTpl(path), socket(sock),
                ip(serverIP), port(serverPort) {}

        Request* withQuery(const std::string &key, const std::string &val) {
            this->queryParams[key] = val;
            return this;
        }

        Request* withBasicAuth(const std::string &username, const std::string &password) {
            auto basicAuthString = username + ":" + password;
            auto encodedString = "Basic " + base64_encode((unsigned char *) (basicAuthString.c_str()),
                    basicAuthString.length());
            return this->withHeader("Authorization", encodedString);
        }

        Request* withPath(const std::string &key, const std::string &val) {
            this->pathParams[key] = val;
            return this;
        }

        Request* withJSON(const std::string &bd) {
            this->body = bd;
            this->headers["Content-Type"] = "application/json";
            return this;
        }

        Request* withHeader(const std::string &key, const std::string &val) {
            this->headers[key] = val;
            return this;
        }

        std::shared_ptr<Response> Expect() {
            boost::asio::streambuf requestBuffer;
            std::ostream requestStream(&requestBuffer);
            requestStream << this->makeRequestMessage();
            boost::asio::write(*socket, requestBuffer);

            boost::asio::streambuf responseBuffer;
            boost::asio::read_until(*socket, responseBuffer, "\r\n");
            std::istream responseStream(&responseBuffer);

            std::string httpVersion, statusMessage;
            int statusCode;

            responseStream >> httpVersion;
            responseStream >> statusCode;
            std::getline(responseStream, statusMessage);

            auto bytesTransferred = boost::asio::read_until(*socket, responseBuffer, "\r\n\r\n");

            auto total = responseBuffer.size();

            std::string header;
            while (std::getline(responseStream, header) && header != "\r") {
                auto kvPairHeader = parse_header(header);
                resHeaders[kvPairHeader.first] = kvPairHeader.second;
            }

            auto bodyLength = (resHeaders.find("Content-Length") == resHeaders.end())
                                ? "0" : resHeaders["Content-Length"];
            auto Length = std::stoull(bodyLength);
            auto additionalBytesNum = total - bytesTransferred;
            auto remain = Length - additionalBytesNum;
            if (remain > 0) {
                boost::system::error_code error;
                boost::asio::read(*socket, responseBuffer, boost::asio::transfer_exactly(remain), error);
            }

            std::stringstream mybody;
            mybody << &responseBuffer;
//            std::string bodyString =

            return std::make_shared<Response>(mybody.str(), resHeaders, this->method, this->requestURL, statusCode);
        }
    }; // class Request
} // namespace vogro
#endif

max_stars_repo_name: vogro-x/vogro

max_issues_repo_name: vogro-x/vogro

max_forks_repo_name: vogro-x/vogro


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_CONCEPTS_COLOR_BASE_HPP
#define BOOST_GIL_CONCEPTS_COLOR_BASE_HPP

#include <boost/gil/concepts/basic.hpp>
#include <boost/gil/concepts/color.hpp>
#include <boost/gil/concepts/concept_check.hpp>
#include <boost/gil/concepts/fwd.hpp>

#include <boost/core/ignore_unused.hpp>
#include <type_traits>

#if defined(BOOST_CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-local-typedefs"
#endif

#if defined(BOOST_GCC) && (BOOST_GCC >= 40900)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif

namespace boost { namespace gil {

// Forward declarations of at_c
namespace detail {

template <typename Element, typename Layout, int K>
struct homogeneous_color_base;

} // namespace detail

template <int K, typename E, typename L, int N>
auto at_c(detail::homogeneous_color_base<E, L, N>& p)
    -> typename std::add_lvalue_reference<E>::type;

template <int K, typename E, typename L, int N>
auto at_c(detail::homogeneous_color_base<E, L, N> const& p)
    -> typename std::add_lvalue_reference<typename std::add_const<E>::type>::type;

template <typename P, typename C, typename L>
struct packed_pixel;

template <int K, typename P, typename C, typename L>
auto at_c(packed_pixel<P, C, L>& p)
    -> typename kth_element_reference_type<packed_pixel<P, C, L>, K>::type;

template <int K, typename P, typename C, typename L>
auto at_c(packed_pixel<P, C, L> const& p)
    -> typename kth_element_const_reference_type<packed_pixel<P, C, L>, K>::type;

template <typename B, typename C, typename L, bool M>
struct bit_aligned_pixel_reference;

template <int K, typename B, typename C, typename L, bool M>
inline auto at_c(bit_aligned_pixel_reference<B, C, L, M> const& p)
    -> typename kth_element_reference_type
        <
            bit_aligned_pixel_reference<B, C, L, M>,
            K
        >::type;

// Forward declarations of semantic_at_c
template <int K, typename ColorBase>
auto semantic_at_c(ColorBase& p)
    -> typename std::enable_if
        <
            !std::is_const<ColorBase>::value,
            typename kth_semantic_element_reference_type<ColorBase, K>::type
        >::type;

template <int K, typename ColorBase>
auto semantic_at_c(ColorBase const& p)
    -> typename kth_semantic_element_const_reference_type<ColorBase, K>::type;

/// \ingroup ColorBaseConcept
/// \brief A color base is a container of color elements (such as channels, channel references or channel pointers).
///
/// The most common use of color base is in the implementation of a pixel,
/// in which case the color elements are channel values. The color base concept,
/// however, can be used in other scenarios. For example, a planar pixel has
/// channels that are not contiguous in memory. Its reference is a proxy class
/// that uses a color base whose elements are channel references. Its iterator
/// uses a color base whose elements are channel iterators.
///
/// A color base must have an associated layout (which consists of a color space,
/// as well as an ordering of the channels).
/// There are two ways to index the elements of a color base: A physical index
/// corresponds to the way they are ordered in memory, and a semantic index
/// corresponds to the way the elements are ordered in their color space.
/// For example, in the RGB color space the elements are ordered as
/// {red_t, green_t, blue_t}. For a color base with a BGR layout, the first element
/// in physical ordering is the blue element, whereas the first semantic element
/// is the red one.
/// Models of \p ColorBaseConcept are required to provide the \p at_c<K>(ColorBase)
/// function, which allows for accessing the elements based on their physical order.
/// GIL provides a \p semantic_at_c<K>(ColorBase) function (described later)
/// which can operate on any model of ColorBaseConcept and returns the corresponding
/// semantic element.
///
/// \code
/// concept ColorBaseConcept<typename T> : CopyConstructible<T>, EqualityComparable<T>
/// {
///     // a GIL layout (the color space and element permutation)
///     typename layout_t;
///
///     // The type of K-th element
///     template <int K>
///     struct kth_element_type;
///         where Metafunction<kth_element_type>;
///
///     // The result of at_c
///     template <int K>
///     struct kth_element_const_reference_type;
///         where Metafunction<kth_element_const_reference_type>;
///
///     template <int K>
///     kth_element_const_reference_type<T,K>::type at_c(T);
///
///     // Copy-constructible and equality comparable with other compatible color bases
///     template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
///         T::T(T2);
///     template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
///         bool operator==(const T&, const T2&);
///     template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
///         bool operator!=(const T&, const T2&);
/// };
/// \endcode
template <typename ColorBase>
struct ColorBaseConcept
{
    void constraints()
    {
        gil_function_requires<CopyConstructible<ColorBase>>();
        gil_function_requires<EqualityComparable<ColorBase>>();

        using color_space_t = typename ColorBase::layout_t::color_space_t;
        gil_function_requires<ColorSpaceConcept<color_space_t>>();

        using channel_mapping_t = typename ColorBase::layout_t::channel_mapping_t;
        // TODO: channel_mapping_t must be an Boost.MP11-compatible random access sequence

        static const int num_elements = size<ColorBase>::value;

        using TN = typename kth_element_type<ColorBase, num_elements - 1>::type;
        using RN = typename kth_element_const_reference_type<ColorBase, num_elements - 1>::type;

        RN r = gil::at_c<num_elements - 1>(cb);
        boost::ignore_unused(r);

        // functions that work for every pixel (no need to require them)
        semantic_at_c<0>(cb);
        semantic_at_c<num_elements-1>(cb);
        // also static_max(cb), static_min(cb), static_fill(cb,value),
        // and all variations of static_for_each(), static_generate(), static_transform()
    }
    ColorBase cb;
};

/// \ingroup ColorBaseConcept
/// \brief Color base which allows for modifying its elements
/// \code
/// concept MutableColorBaseConcept<ColorBaseConcept T> : Assignable<T>, Swappable<T>
/// {
///     template <int K>
///     struct kth_element_reference_type; where Metafunction<kth_element_reference_type>;
///
///     template <int K>
///     kth_element_reference_type<kth_element_type<T,K>::type>::type at_c(T);
///
///     template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
///         T& operator=(T&, const T2&);
/// };
/// \endcode
template <typename ColorBase>
struct MutableColorBaseConcept
{
    void constraints()
    {
        gil_function_requires<ColorBaseConcept<ColorBase>>();
        gil_function_requires<Assignable<ColorBase>>();
        gil_function_requires<Swappable<ColorBase>>();

        using R0 = typename kth_element_reference_type<ColorBase, 0>::type;

        R0 r = gil::at_c<0>(cb);
        gil::at_c<0>(cb) = r;
    }
    ColorBase cb;
};

/// \ingroup ColorBaseConcept
/// \brief Color base that also has a default-constructor. Refines Regular
/// \code
/// concept ColorBaseValueConcept<typename T> : MutableColorBaseConcept<T>, Regular<T>
/// {
/// };
/// \endcode
template <typename ColorBase>
struct ColorBaseValueConcept
{
    void constraints()
    {
        gil_function_requires<MutableColorBaseConcept<ColorBase>>();
        gil_function_requires<Regular<ColorBase>>();
    }
};

/// \ingroup ColorBaseConcept
/// \brief Color base whose elements all have the same type
/// \code
/// concept HomogeneousColorBaseConcept<ColorBaseConcept CB>
/// {
///     // For all K in [0 ... size<C1>::value-1):
///     //     where SameType<kth_element_type<CB,K>::type, kth_element_type<CB,K+1>::type>;
///     kth_element_const_reference_type<CB,0>::type dynamic_at_c(CB const&, std::size_t n) const;
/// };
/// \endcode
template <typename ColorBase>
struct HomogeneousColorBaseConcept
{
    void constraints()
    {
        gil_function_requires<ColorBaseConcept<ColorBase>>();

        static const int num_elements = size<ColorBase>::value;

        using T0 = typename kth_element_type<ColorBase, 0>::type;
        using TN = typename kth_element_type<ColorBase, num_elements - 1>::type;

        static_assert(std::is_same<T0, TN>::value, "");   // better than nothing

        using R0 = typename kth_element_const_reference_type<ColorBase, 0>::type;
        R0 r = dynamic_at_c(cb, 0);
        boost::ignore_unused(r);
    }
    ColorBase cb;
};

/// \ingroup ColorBaseConcept
/// \brief Homogeneous color base that allows for modifying its elements
/// \code
/// concept MutableHomogeneousColorBaseConcept<ColorBaseConcept CB>
///     : HomogeneousColorBaseConcept<CB>
/// {
///     kth_element_reference_type<CB, 0>::type dynamic_at_c(CB&, std::size_t n);
/// };
/// \endcode
template <typename ColorBase>
struct MutableHomogeneousColorBaseConcept
{
    void constraints()
    {
        gil_function_requires<ColorBaseConcept<ColorBase>>();
        gil_function_requires<HomogeneousColorBaseConcept<ColorBase>>();
        using R0 = typename kth_element_reference_type<ColorBase, 0>::type;
        R0 r = dynamic_at_c(cb, 0);
        boost::ignore_unused(r);
        dynamic_at_c(cb, 0) = dynamic_at_c(cb, 0);
    }
    ColorBase cb;
};

/// \ingroup ColorBaseConcept
/// \brief Homogeneous color base that also has a default constructor.
/// Refines Regular.
///
/// \code
/// concept HomogeneousColorBaseValueConcept<typename T>
///     : MutableHomogeneousColorBaseConcept<T>, Regular<T>
/// {
/// };
/// \endcode
template <typename ColorBase>
struct HomogeneousColorBaseValueConcept
{
    void constraints()
    {
        gil_function_requires<MutableHomogeneousColorBaseConcept<ColorBase>>();
        gil_function_requires<Regular<ColorBase>>();
    }
};

/// \ingroup ColorBaseConcept
/// \brief Two color bases are compatible if they have the same color space and their elements are compatible, semantic-pairwise.
/// \code
/// concept ColorBasesCompatibleConcept<ColorBaseConcept C1, ColorBaseConcept C2>
/// {
///     where SameType<C1::layout_t::color_space_t, C2::layout_t::color_space_t>;
///     // also, for all K in [0 ... size<C1>::value):
///     //     where Convertible<kth_semantic_element_type<C1,K>::type, kth_semantic_element_type<C2,K>::type>;
///     //     where Convertible<kth_semantic_element_type<C2,K>::type, kth_semantic_element_type<C1,K>::type>;
/// };
/// \endcode
template <typename ColorBase1, typename ColorBase2>
struct ColorBasesCompatibleConcept
{
    void constraints()
    {
        static_assert(std::is_same
            <
                typename ColorBase1::layout_t::color_space_t,
                typename ColorBase2::layout_t::color_space_t
            >::value, "");

//        using e1 = typename kth_semantic_element_type<ColorBase1,0>::type;
//        using e2 = typename kth_semantic_element_type<ColorBase2,0>::type;
//        "e1 is convertible to e2"
    }
};

}} // namespace boost::gil

#if defined(BOOST_CLANG)
#pragma clang diagnostic pop
#endif

#if defined(BOOST_GCC) && (BOOST_GCC >= 40900)
#pragma GCC diagnostic pop
#endif

#endif

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
#include "rtfw/detail/core.hpp"
#include "rtfw/detail/util.hpp"
#include "propertytree.hpp"

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>

namespace rtfw{
namespace detail{
using namespace std::literals::chrono_literals;

namespace pt = propertytree;
namespace bpt = boost::property_tree;

namespace {

bool file_exists(const std::string& path){
	std::ifstream f{path};
	return f.good();
}

template<class Iter>
std::string join(Iter iter, Iter end){
	std::string out{};
	while(iter != end){
		out += *iter;
		++iter;
		if(iter != end)
			out.push_back('.');
		else
			break;
	}
	return out;
}

void print_keys(const pt::Dict& d, std::vector<std::string>& stack){
	for(const auto& [key, node] : d){
		stack.push_back(key.cast<std::string>());
		if(node.type() == pt::Node::Type::Dict){
			print_keys(node.as_dict(), stack);
		} else{
			std::cerr << join(stack.begin(), stack.end()) << '\n';
		}
		stack.pop_back();
	}
}

void validate_config_files(const pt::Dict& mod_confs, const pt::Dict& file_confs){
	auto tmp = file_confs;
	tmp -= mod_confs;
	if(!tmp.empty()){
		std::cerr << "\nWARNING: unsupported configurations in config files:\n";
		std::vector<std::string> stack;
		print_keys(tmp, stack);
		std::cerr << '\n';
	}
}

template<class Iter>
pt::Node read_ini_file(Iter iter, Iter end){
	pt::Node result{pt::Dict()};
	while(iter != end){
		if(file_exists(*iter)){
			bpt::ptree tree;
			bpt::read_ini(*iter, tree);
			result.as_dict().right_union(pt::Node{tree}.as_dict());
		} else{
			std::cerr << "file " << *iter << " not found. Skipping\n";
		}
		++iter;
	}
	return result;
}

pt::Node populate_configs(pt::Node&& confs){
	std::vector<std::string> ini_files{"rtfw.ini"};
	auto from_files = read_ini_file(ini_files.begin(), ini_files.end());
	validate_config_files(confs.as_dict(), from_files.as_dict());
	confs.as_dict().right_union(from_files.as_dict());
	return confs;
}

pt::Node invoke_configs(List& module_list){
	auto* iter = module_list.first();
	pt::Node dict{pt::Dict()};
	while(iter){
		auto* ptr = static_cast<ModuleHolder*>(iter);
		std::cerr << "configuring " << ptr->name() << '\n';
		auto& conf = ptr->config();
		if(conf.name() == "")
			conf.name() = ptr->name();

		if(dict.as_dict().count(conf.name()))
			throw std::runtime_error("Conflicting module names");

		pt::Node tmp{std::move(conf)};
		dict.as_dict().left_union(tmp.as_dict());
		iter = List::next(*iter);
	}
	return dict;
}

void init(List& init_stack, List& module_list, const pt::Node& configs){
	ListHead* iterator = module_list.first();
	while(iterator){
		auto* target = iterator;
		iterator = List::next(*iterator);
		init_stack.push_back(*target);
		std::cerr << "initializing " << static_cast<ModuleHolder*>(target)->name() << '\n';
		static_cast<ModuleHolder*>(target)->init(rtfw::Config());
		module_list.push_front(*target);
	}
}

void deinit(List& module_list){
	ListHead* iterator = module_list.first();
	while(iterator){
		auto* target = static_cast<ModuleHolder*>(iterator);
		std::cerr << "destroying " << target->name() << '\n';
		iterator = List::next(*iterator);
		target->clear();
	}

}

}

Core::Core(){}

Core::~Core(){}

void Core::run(){

	// Lambda is called in object destructor
	Defer defer{[&](){
		setup_ = false;
	}};

	setup_ = false;
	rtfw_thread_id_ = std::this_thread::get_id();
	auto configs = invoke_configs(ModuleHolder::instances);
	configs = populate_configs(std::move(configs));
	init(init_stack_, ModuleHolder::instances, configs);
	setup_ = true;
	std::this_thread::sleep_for(1s);
	deinit(ModuleHolder::instances);
}

Core core{};
}
}

max_stars_repo_name: tlammi/rtfw

max_issues_repo_name: tlammi/rtfw

max_forks_repo_name: tlammi/rtfw


text:
#ifndef BART_SRC_INSTRUMENTATION_PORT_HPP_
#define BART_SRC_INSTRUMENTATION_PORT_HPP_

#include "instrumentation/instrument_i.h"

#include <deal.II/base/exceptions.h>

#include <memory>

namespace bart::instrumentation {

template <typename DataType, typename DataName>
class Port {
 public:
  using InstrumentType = InstrumentI<DataType>;
  virtual ~Port() = default;
  void AddInstrument(std::shared_ptr<InstrumentType> instrument_ptr) {instrument_ptr_ = instrument_ptr; }
  void Expose(const DataType& data_to_expose) {
    if (instrument_ptr_ != nullptr) {
      instrument_ptr_->Read(data_to_expose);
    }
  }
  InstrumentType* instrument_ptr() { return instrument_ptr_.get(); }
  struct Use_dot_after_GetPort_not_arrow {};
 protected:
  std::shared_ptr<InstrumentType> instrument_ptr_ = nullptr;
 private:
  Use_dot_after_GetPort_not_arrow* operator->() { return nullptr; }
};

template <typename PortType, typename T>
PortType& GetPort(T& to_expose) {
  static_assert(std::is_polymorphic_v<T>,
      "Error in GetPort, passed object must be a reference to a polymorphic class that can be cast to a Port. Pointers "
      "cannot be passed, you must dereference to the underlying object using *");
  return dynamic_cast<PortType&>(to_expose);
}

} // namespace bart::instrumentation

#endif //BART_SRC_INSTRUMENTATION_PORT_HPP_

max_stars_repo_name: SlaybaughLab/Transport

max_issues_repo_name: SlaybaughLab/Transport

max_forks_repo_name: SlaybaughLab/Transport


text:
#ifndef LINEAR_BASIS_HPP
#define LINEAR_BASIS_HPP

#include <armadillo>
#include <math.h>

class LinearBasisFunction : public Basis {

public:

    int _nX;
    int _nK;
    int _nU;
    int _nM;
    int _nKU;

    LinearBasisFunction(int _nX = 7, int _nK = 9, int _nU = 2 , int _nM = 6, int _nKU = 2) : Basis(_nX,_nK,_nU,_nM,_nKU) {
        this->_nX = _nX;
        this->_nK = _nK;
        this->_nU = _nU;
        this->_nM = _nM;
        this->_nKU = _nKU;
    }

    arma::vec fk(const arma::vec & x, const arma::vec & u ) {
        return arma::join_cols( fkx(x), fku(x, u) );
    }

    arma::vec fkx( const arma::vec& x ) {
        return arma::vec({
            x[0],
            x[1],
            x[2],
            x[3],
            x[4],
            x[5],
            1
        });
    }

    arma::vec fku( const arma::vec & x, const arma::vec& u ) {

        return arma::vec({
            u[0],
            u[1]
          });

    }

    arma::mat fkudu( const arma::vec & x, const arma::vec & u) {
        return arma::mat({
            {1,0},
            {0,1}
        });
    }

};

#endif


text:
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
 All rights reserved.

 This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
 under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
 MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/

/**
* \file     dynamic_object_renderer.cpp
* \author   Collin Johnson
*
* Definition of DynamicObjectRenderer.
*/

#include <ui/components/dynamic_object_renderer.h>
#include <ui/components/object_boundary_renderer.h>
#include <ui/common/color_interpolator.h>
#include <ui/common/gl_shapes.h>
#include <tracker/dynamic_object_collection.h>
#include <tracker/dynamic_object.h>
#include <tracker/objects/person.h>
#include <tracker/objects/rigid.h>
#include <tracker/objects/unclassified.h>
#include <tracker/objects/pivoting_object.h>
#include <tracker/objects/sliding_object.h>
#include <GL/gl.h>
#include <boost/variant/static_visitor.hpp>

namespace vulcan
{
namespace ui
{

struct GoalRenderer : boost::static_visitor<>
{
    GLColor color;
    Point<float> objectPosition;
    bool drawDistribution;

    void operator()(const Point<double>& position)
    {
        color.set(0.9);
        gl_draw_filled_circle(position, 0.125);
        color.set();
        gl_draw_line_circle(position, 0.125, 1.0);

        glLineWidth(4.0);
        color.set(0.9);
        glBegin(GL_LINES);
        glVertex2f(objectPosition.x, objectPosition.y);
        glVertex2f(position.x, position.y);
        glEnd();
    }

    void operator()(const Line<double>& boundary)
    {
        glLineWidth(4.0);
        color.set(0.9);
        glBegin(GL_TRIANGLES);
        glVertex2f(objectPosition.x, objectPosition.y);
        glVertex2f(boundary.a.x, boundary.a.y);
        glVertex2f(boundary.b.x, boundary.b.y);
        glEnd();
    }
};

DynamicObjectRenderer::DynamicObjectRenderer(void)
: uncertaintyFlags_(0)
, unclassifiedColor_(0, 0, 0, 200)
, pivotingColor_(157, 104, 12, 200)
, slidingColor_(136, 136, 136, 200)
, stridingColor_(55, 166, 70, 200)
, rigidColor_(58, 131, 205, 200)
{
}

void DynamicObjectRenderer::renderCollectionStateEstimates(const tracker::DynamicObjectCollection& collection,
                                                           uint32_t uncertaintyOptions)
{
    uncertaintyFlags_ = uncertaintyOptions;
    collection.visitAll(*this);
}

void DynamicObjectRenderer::renderObjectStateEstimate(const tracker::DynamicObject& object,
                                                      uint32_t uncertaintyOptions)
{
    uncertaintyFlags_ = uncertaintyOptions;
    object.accept(*this);
}

void DynamicObjectRenderer::renderObjectGoals(const tracker::DynamicObject& object, bool showFullDistribution)
{
    auto goals = object.goals();

    // If not showing the full distribution, just erase all not-the-best goals
    if(!showFullDistribution)
    {
        goals = tracker::ObjectGoalDistribution{goals.bestGoal()};
    }

    GoalRenderer r;
    r.drawDistribution = showFullDistribution;

    ValueColorInterpolator interpolator(GLColor(233./255, 132./255, 255./255, 0.5));

    for(auto& g : goals)
    {
        r.color = interpolator.calculateColor(g.probability());
        r.objectPosition = object.position();
        auto dest = g.destination();
        apply_visitor(r, dest);
    }
}

void DynamicObjectRenderer::visitPerson(const tracker::Person& person)
{
    drawObject(person, stridingColor_);
}

void DynamicObjectRenderer::visitPivotingObject(const tracker::PivotingObject& door)
{
    drawObject(door, pivotingColor_);

    // Draw the arc through which the door sweeps
    pivotingColor_.set(0.25);
    gl_draw_filled_arc(door.arc());
    pivotingColor_.set(0.5);
    gl_draw_line_arc(door.arc());
}

void DynamicObjectRenderer::visitRigid(const tracker::RigidObject& object)
{
    drawBoundary(object.boundary(), rigidColor_, true);
    drawRigidObjectState(object, rigidColor_);
}

void DynamicObjectRenderer::visitSlidingObject(const tracker::SlidingObject& door)
{
    drawObject(door, slidingColor_);
}

void DynamicObjectRenderer::visitUnclassified(const tracker::UnclassifiedObject& object)
{
    drawObject(object, unclassifiedColor_);
}

void DynamicObjectRenderer::drawObject(const tracker::DynamicObject& object, const GLColor& color)
{
    drawBoundary(object.boundary(), color, true);
    drawVelocity(object, color);
}

void DynamicObjectRenderer::drawBoundary(const tracker::ObjectBoundary& boundary, const GLColor& color, bool filled)
{
//     if(filled)
//     {
//         boundary.visitShape(ObjectBoundaryRenderer(color));
//     }
//     else
//     {
//         boundary.visitShape(OutlineObjectBoundaryRenderer(color));
//     }

    color.set();
    gl_draw_line_circle(boundary.circleApproximation().center(), boundary.circleApproximation().radius());
}

void DynamicObjectRenderer::drawVelocity(const tracker::DynamicObject& object, const GLColor& color)
{
    GLColor accelColor(200, 0, 0, 150);
    const float kVelocityLineWidth = 2.0f;

    auto motionState = object.motionState();

    glLineWidth(kVelocityLineWidth);
    glPushMatrix();
    glTranslatef(motionState.x, motionState.y, 0.0f);
    glBegin(GL_LINES);

    color.set();
    glVertex2f(0.0f, 0.0f);
    glVertex2f(motionState.xVel, motionState.yVel);

    if(uncertaintyFlags_ & kShowAcceleration)
    {
        accelColor.set();
        glVertex2f(0.0f, 0.0f);
        glVertex2f(motionState.xAccel, motionState.yAccel);
    }

    glEnd();
    glPopMatrix();
}

void DynamicObjectRenderer::drawRigidObjectState(const tracker::RigidObject& object, const GLColor& color)
{
    using msi = tracker::MotionStateIndex;

    // Draw uncertainty
    auto stateToDraw = (uncertaintyFlags_ & kShowFastState) ? object.fastMotionState() : object.slowMotionState();

    if(uncertaintyFlags_ & (kShowAccelerationUncertainty | kShowVelocityUncertainty | kShowPositionUncertainty))
    {
        Vector mean(2);
        mean[msi::xIndex] = stateToDraw[msi::xIndex];
        mean[msi::yIndex] = stateToDraw[msi::yIndex];
        Matrix cov;
        if(uncertaintyFlags_ & kShowPositionUncertainty)
        {
            cov = stateToDraw.getCovariance().submat(msi::xIndex, msi::xIndex, msi::yIndex, msi::yIndex);
        }
        else if(uncertaintyFlags_ & kShowVelocityUncertainty)
        {
            cov = stateToDraw.getCovariance().submat(msi::velXIndex, msi::velXIndex, msi::velYIndex, msi::velYIndex);
        }
        else if(uncertaintyFlags_ & kShowAccelerationUncertainty)
        {
            cov = stateToDraw.getCovariance().submat(msi::accelXIndex, msi::accelXIndex, msi::accelYIndex, msi::accelYIndex);
        }

        MultivariateGaussian uncertainty(mean, cov);
        gl_draw_gaussian_distribution(uncertainty, 1.0f, color);
    }

    // Draw velocity and acceleration estimates
    const float kVelocityLineWidth = 2.0f;

    glLineWidth(kVelocityLineWidth);
    glPushMatrix();
    glTranslatef(stateToDraw[msi::xIndex], stateToDraw[msi::yIndex], 0.0f);
    glBegin(GL_LINES);

    color.set();
    glVertex2f(0.0f, 0.0f);
    glVertex2f(stateToDraw[msi::velXIndex], stateToDraw[msi::velYIndex]);

    if(uncertaintyFlags_ & kShowAcceleration)
    {
        GLColor accelColor(200, 0, 0, 150);
        accelColor.set();
        glVertex2f(0.0f, 0.0f);
        glVertex2f(stateToDraw[msi::accelXIndex], stateToDraw[msi::accelYIndex]);
    }

    glEnd();
    glPopMatrix();
}

} // namespace ui
} // namespace vulcan


text:
/*
 * Copyright (c) Nuno Alves de Sousa 2019
 *
 * Use, modification and distribution is subject to the Boost Software License,
 * Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 */
#ifndef ADAPTIV_AUXILIARY_PARSERS_HPP
#define ADAPTIV_AUXILIARY_PARSERS_HPP

#include <adaptiv/macros.hpp>

#include <boost/spirit/home/x3.hpp>

ADAPTIV_NAMESPACE_BEGIN
ADAPTIV_UTILITY_NAMESPACE_BEGIN
ADAPTIV_INPUT_NAMESPACE_BEGIN

/// Auxiliary X3 parsers
namespace parsers::auxiliary {

namespace x3 = boost::spirit::x3;

/// End of list parser (fails because of a missing ',')
auto const eolist = x3::rule<class eolist_tag> {"missing ','"}
                  = x3::eoi;

} // namespace parsers::auxiliary

ADAPTIV_INPUT_NAMESPACE_END
ADAPTIV_UTILITY_NAMESPACE_END
ADAPTIV_NAMESPACE_END

#endif //ADAPTIV_AUXILIARY_PARSERS_HPP