text:
// <DatabaseSchema> -*- C++ -*-

#include <ctype.h>
#include <math.h>
#include <cstddef>
#include <boost/algorithm/string/trim.hpp>
#include <algorithm>
#include <istream>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>

#include "simdb/schema/Schema.hpp"
#include "simdb/schema/TableSummaries.hpp"
#include "sparta/report/db/Schema.hpp"
#include "sparta/statistics/StatisticDef.hpp"
#include "sparta/statistics/InstrumentationNode.hpp"
#include "sparta/report/DatabaseInterface.hpp"
#include "sparta/trigger/ExpressionTrigger.hpp"
#include "sparta/report/SubContainer.hpp"
#include "simdb/schema/ColumnTypedefs.hpp"
#include "sparta/simulation/RootTreeNode.hpp"
#include "sparta/utils/SpartaAssert.hpp"
#include "sparta/kernel/SpartaHandler.hpp"

//! Static initializers for SimDB-related classes
namespace sparta {
    std::unordered_set<const RootTreeNode*> DatabaseAccessor::all_simulation_accessors_;
    bool DatabaseAccessor::static_simdb_accessor_invoked_ = false;
}

namespace sparta {
namespace db {

//! Build a SimDB schema object that can hold all report artifacts
//! and StatisticInstance values for SPARTA simulators. This schema
//! can be given to a simdb::ObjectManager to instantiate a physical
//! database connection.
void buildSimulationDatabaseSchema(simdb::Schema & schema)
{
    using dt = simdb::ColumnDataType;

    //Statistics databases are comprised of run/simulation
    //metadata, and SI values stored as blobs.

    {
        //Let's start by creating the metadata table.
        schema.addTable("ReportHeader")
            .addColumn("TimeseriesID", dt::fkey_t)
                ->index()
                ->setDefaultValue(0)
            .addColumn("ReportName",   dt::string_t)
            .addColumn("StartTime",    dt::uint64_t)
                ->setDefaultValue(0)
            .addColumn("EndTime",      dt::uint64_t)
                ->setDefaultValue(-1)
            .addColumn("WarmupInsts",  dt::uint64_t)
            .addColumn("DestFile",     dt::string_t)
            .addColumn("SILocations",  dt::string_t)
            .addColumn("NumStatInsts", dt::int32_t)
            .addColumn("SIRootNodeID", dt::fkey_t);

        //Records from two or more tables may need to be linked
        //together in some way. We have this general-purpose table
        //which holds nothing but ObjectManager UUID's to help
        //accomplish this. The ObjectManager class has a getId()
        //method, and records from different tables can be linked
        //via this UUID. As an example:
        //
        //   |=======================================================|
        //   |  SimInfo                                              |
        //   | ------------------------------------------------------|
        //   |  Id        | Name    | SimulatorVersion    | ObjMgrID |
        //   | ------------------------------------------------------|
        //   |  1         | "Fiat"  |  "2.0"              | 14       |
        //   |  2         | "DVM"   |  "2.3"              | 16       |
        //   | ------------------------------------------------------|
        //
        //   |=====================================|
        //   |  ReportNodeHierarchy                |
        //   | ------------------------------------|
        //   |  Id        | Name    | ParentNodeID |
        //   | ------------------------------------|
        //   |  8         |   "top" |            0 |
        //   |  9         | "core0" |            8 |
        //   |  10        |   "rob" |            9 |
        //   | ------------------------------------|
        //
        //If we wanted to write an API which takes a report node
        //database ID (say, 10) and create a report from the SI
        //data stored in the database, we will need a quick way
        //to get from any report node ID to a row in the SimInfo
        //table. Perhaps we write our code like this:
        //
        //     1) Take the report node ID of 10 and keep running
        //        queries on the ReportNodeHierarchy table until
        //        we are at the top report node in this specific
        //        SI hierarchy. In this case, 10->9->8, and the
        //        root report node has an ID of 8.
        //     2) Say we had another table which mapped root-
        //        level report node ID's to their corresponding
        //        ObjMgrID, which looks something like this:
        //
        //   |===========================================|
        //   |  RootReportObjMgrIDs                      |
        //   | ------------------------------------------|
        //   |  Id        | RootReportNodeID  | ObjMgrID |
        //   | ------------------------------------------|
        //   |  1         |                8  |       16 |
        //   | ------------------------------------------|
        //
        //Now our API could be implemented like this:
        //
        //   void makeReportFromDatabaseNode(int node_db_id)
        //   {
        //       //Say node_db_id = 10
        //       auto root_db_id = getRootDbIdFrom(node_db_id);
        //
        //       //Now root_db_id = 8
        //       obj_mgr_id = getObjMgrIdForRootReportNode(root_db_id);
        //
        //       //Now obj_mgr_id = 16. The final pseudo-code:
        //       auto sim_info = eval_sql(
        //           "SELECT * FROM SimInfo WHERE ObjMgrID = 16");
        //
        //       std::cout << sim_info.Name << " ran with simulator version "
        //                 << sim_info.SimulatorVersion << std::endl;
        //
        //       //  " DVM ran with simulator version 2.3 "  //
        //   }
        schema.addTable("ObjectManagersInDatabase")
            .addColumn("ObjMgrID", dt::fkey_t);

        //Table for SimulationInfo. These records are linked
        //to root-level nodes in the ReportNodeHierarchy table
        //via the ObjectManager UUID they both share.
        schema.addTable("SimInfo")
            .addColumn("Name",               dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("Cmdline",            dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("WorkingDir",         dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("Exe",                dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("SimulatorVersion",   dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("SpartaVersion",        dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("Repro",              dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("Start",              dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("Other",              dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("ObjMgrID",           dt::fkey_t)
                ->setDefaultValue(0);

        //Table which describes report/subreport node hierarchy
        schema.addTable("ReportNodeHierarchy")
            .addColumn("ParentNodeID",    dt::fkey_t)
                ->index()
            .addColumn("Name",            dt::string_t)
            .addColumn("IsLeafSI",        dt::int32_t)
                ->noSummary()
                ->setDefaultValue(-1)
            .addColumn("LeftmostSIIndex", dt::int32_t)
                ->noSummary()
                ->setDefaultValue(-1);

        //Table which describes sub-statistics node hierarchies.
        //Used to serialize the basic layout of ContextCounter's
        //in a given report.
        schema.addTable("SubStatisticsNodeHierarchy")
            .addColumn("ReportNodeID",   dt::fkey_t)
                ->index()
            .addColumn("SINodeID",       dt::fkey_t)
            .addColumn("ParentSINodeID", dt::fkey_t);

        //This table is used to tell the SimDB->report code which
        //sub-statistics are "unprintable". This supports Context
        //Counter's which have special treatment in the JSON formatter
        //code. We won't have any sparta::ContextCounter<T> objects
        //available when we regenerate reports just from records
        //in a database, so this table helps mimic what the original
        //simulator's legacy json* formatters would have done during
        //simulation.
        schema.addTable("UnprintableSubStatistics")
            .addColumn("ReportNodeID", dt::fkey_t)
                ->index();

        //Table which stores all metadata that is common to all
        //report/subreport nodes
        schema.addTable("ReportNodeMetadata")
            .addColumn("Author",           dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("InfoString",       dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("StartTick",        dt::uint64_t)
                ->setDefaultValue(0)
            .addColumn("EndTick",          dt::uint64_t)
                ->setDefaultValue(-1)
            .addColumn("ReportNodeID",     dt::fkey_t)
                ->setDefaultValue(-1)
                ->index();

        //Unlike the ReportNodeMetadata table, this table stores
        //metadata that is common to all report nodes in a given
        //report/subreport hierarchy.
        schema.addTable("RootReportNodeMetadata")
            .addColumn("ReportNodeID", dt::fkey_t)
                ->indexAgainst("Name")
            .addColumn("Name",         dt::string_t)
            .addColumn("Value",        dt::string_t);

        //Table which stores all style metadata for
        //a given report/subreport
        schema.addTable("ReportStyle")
            .addColumn("StyleName",    dt::string_t)
            .addColumn("StyleValue",   dt::string_t)
            .addColumn("ReportNodeID", dt::fkey_t)
                ->index();

        //SI metadata used in report generation (all formats)
        constexpr int vs_default = static_cast<int>(
            sparta::StatisticDef::ValueSemantic::VS_INVALID);
        constexpr int vis_default = static_cast<int>(
            sparta::InstrumentationNode::VIS_NORMAL);
        constexpr int cls_default = static_cast<int>(
            sparta::InstrumentationNode::DEFAULT_CLASS);

        schema.addTable("SIMetadata")
            .addColumn("Location",             dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("Desc",                 dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("ExprString",           dt::string_t)
                ->setDefaultValue("unset")
            .addColumn("ValueSemantic",        dt::int32_t)
                ->noSummary()
                ->setDefaultValue(vs_default)
            .addColumn("Visibility",           dt::int32_t)
                ->noSummary()
                ->setDefaultValue(vis_default)
            .addColumn("Class",                dt::int32_t)
                ->noSummary()
                ->setDefaultValue(cls_default)
            .addColumn("ReportNodeID",         dt::fkey_t)
                ->setDefaultValue(-1)
                ->index();

        //Make a 1-to-1 link from all root-level report nodes
        //to the ID of the ObjectManager they came from
        schema.addTable("RootReportObjMgrIDs")
            .addColumn("RootReportNodeID", dt::fkey_t)
            .addColumn("ObjMgrID",         dt::fkey_t);

        //The above report metadata columns are for the most
        //common pieces of metadata found in statistics reports.
        //Let's use a catch-all string metadata table that any
        //generic name/value pair can go into. We don't need
        //a dedicated wrapper API around every possible metadata
        //we can think of.
        schema.addTable("StringMetadata")
            .addColumn("ReportHeaderID",       dt::fkey_t)
                ->indexAgainst("MetadataName")
            .addColumn("MetadataName",         dt::string_t)
            .addColumn("MetadataValue",        dt::string_t);

        //Create an SI hierarchy table. Say there was an SI
        //tree that looked like this (assume just 1 timeseries):
        //
        //                      top (id 1)
        //             -----------------------------
        //              |                         |
        //          foo (id 2)                bar (id 3)
        //     --------------------      --------------------
        //      |       |        |        |                |
        //    leafA   leafB    leafC    leafD            leafE
        //    (id 4)  (id 5)   (id 6)   (id 7)           (id 8)
        //
        //This SINodeHierarchy table would look like this:
        //
        //  Id     ParentNodeID     RelativeSIIndex     NodeName
        //  ----   --------------   -----------------   ----------
        //  1      0                0                   top
        //  2      1                0                   foo
        //  3      1                3                   bar
        //  4      2                0                   leafA
        //  5      2                1                   leafB
        //  6      2                2                   leafC
        //  7      3                3                   leafD
        //  8      3                4                   leafE
        //
        //The "RelativeSIIndex" column answers the question:
        //"If I traveled from this SI node to the first leaf
        //SI node I encountered in a depth-first traversal,
        //what would be that leaf SI's index?" Where leaf SI
        //indexes go from 0 to N-1, N being the number of SI's
        //in this entire report/SI hierarchy (0 is leftmost
        //SI index, N-1 is rightmost SI index).
        schema.addTable("SINodeHierarchy")
            .addColumn("TimeseriesID",          dt::fkey_t)
            .addColumn("ParentNodeID",          dt::fkey_t)
                ->indexAgainst("TimeseriesID")
            .addColumn("NodeName",              dt::string_t)
            .addColumn("RelativeSIIndex",       dt::int32_t)
                ->noSummary();

        //Clock hierarchies. Simulations will serialize the
        //hieararchy from the root clock down through any
        //children it has.
        schema.addTable("ClockHierarchy")
            .addColumn("ParentClockID", dt::fkey_t)
            .addColumn("Name",          dt::string_t)
            .addColumn("Period",        dt::uint32_t)
            .addColumn("FreqMHz",       dt::double_t)
            .addColumn("RatioToParent", dt::double_t);
    }

    {
        //Create the Timeseries table
        schema.addTable("Timeseries")
            .addColumn("ReportHeaderID", dt::fkey_t);

        //Create the TimeseriesChunk table
        schema.addTable("TimeseriesChunk")
            .addColumn("TimeseriesID", dt::fkey_t)
                ->indexAgainst({
                    "StartPS",
                    "EndPS",
                    "StartCycle",
                    "EndCycle"
                  })
            .addColumn("StartPS",    dt::uint64_t)
                ->noSummary()
            .addColumn("EndPS",      dt::uint64_t)
                ->noSummary()
            .addColumn("StartCycle", dt::uint64_t)
                ->noSummary()
            .addColumn("EndCycle",   dt::uint64_t)
                ->noSummary();

        //Create the StatInstValues table
        schema.addTable("StatInstValues")
            .addColumn("TimeseriesChunkID", dt::fkey_t)
                ->index()
            .addColumn("RawBytes",      dt::blob_t)
            .addColumn("NumPts",        dt::int32_t)
                ->noSummary()
            .addColumn("WasCompressed", dt::int32_t)
                ->noSummary()
            .addColumn("MajorOrdering", dt::int32_t)
                ->noSummary()
                ->setDefaultValue(
                      static_cast<int>(db::MajorOrdering::ROW_MAJOR));

        //Hold SI value blobs for single-update, non-
        //timeseries report formats in a separate table.
        //Reports like json_reduced and html are stored
        //in this table.
        schema.addTable("SingleUpdateStatInstValues")
            .addColumn("RootReportNodeID", dt::fkey_t)
                ->index()
                ->setDefaultValue(-1)
            .addColumn("RawBytes",      dt::blob_t)
            .addColumn("NumPts",        dt::int32_t)
                ->noSummary()
            .addColumn("WasCompressed", dt::int32_t)
                ->noSummary();
    }

    {
        //All of the tables in this section are here to support
        //post-simulation report verification against legacy report
        //files. They are only here for smoke testing, debugging
        //report-related bugs, etc. and may be removed at any point
        //in the future.

        //Maintain a mapping from report database ID to the original
        //descriptor's dest_file and format strings.
        schema.addTable("ReportVerificationMetadata")
            .addColumn("RootReportNodeID", dt::fkey_t)
            .addColumn("DestFile",         dt::string_t)
                ->index()
            .addColumn("Format",           dt::string_t);

        //High-level pass/fail results for each report in this
        //database. Also includes a key to get each reports'
        //accompanying SimInfo record. Useful information for
        //debugging failed verifications can be found in the
        //SimInfo table, such as repro commands.
        schema.addTable("ReportVerificationResults")
            .addColumn("DestFile",       dt::string_t)
            .addColumn("SimInfoID",      dt::fkey_t)
                ->indexAgainst("Passed")
            .addColumn("Passed",         dt::int32_t)
            .addColumn("IsTimeseries",   dt::int32_t)
                ->noSummary();

        //We use the SpartaTester utility class to find any differences
        //between database-produced report files and their baselines.
        //SpartaTester gives us a quick summary of file diff(s) just like
        //you would see printed to stdout while running regression tests.
        //We store those summaries in this table.
        schema.addTable("ReportVerificationFailureSummaries")
            .addColumn("ReportVerificationResultID", dt::fkey_t)
                ->index()
            .addColumn("FailureSummary", dt::string_t)
                ->setDefaultValue("unset");

        //When report verification is enabled, we may store deep copies
        //of the diff'd files when failures occur so we don't have to
        //rely on repro steps found in the SimInfo table. This is costly
        //for regression tests that result in many failed verifications,
        //but these tables are more for developer use / debugging than
        //production simulators.
        schema.addTable("ReportVerificationDeepCopyFiles")
            .addColumn("DestFile", dt::string_t)
                ->index()
            .addColumn("Expected", dt::string_t)
            .addColumn("Actual",   dt::string_t);
    }
}

//! Configure the default TableSummaries object for SPARTA simulation
//! databases. This will provide default implementations for common
//! summary calculations like min/max/average, and possibly others.
void configureDatabaseTableSummaries(simdb::TableSummaries & config)
{
    config.define("min",
                  [](const std::vector<double> & vals) -> double {
                      if (vals.empty()) {
                          return NAN;
                      }
                      return *std::min_element(vals.begin(), vals.end());
                  })
          .define("max",
                  [](const std::vector<double> & vals) -> double {
                      if (vals.empty()) {
                          return NAN;
                      }
                      return *std::max_element(vals.begin(), vals.end());
                  })
          .define("avg",
                  [](const std::vector<double> & vals) -> double {
                      if (vals.empty()) {
                          return NAN;
                      }
                      size_t n = 0;
                      double mean = 0;
                      for (auto val : vals) {
                          const double delta = (val - mean);
                          mean += delta / ++n;
                      }
                      return mean;
                  });
}

} // namespace db

DatabaseAccessor::AccessTrigger::AccessTrigger(
    DatabaseAccessor * db_accessor,
    const std::string & db_namespace,
    const std::string & start_expr,
    const std::string & stop_expr,
    RootTreeNode * rtn,
    std::shared_ptr<SubContainer> & sub_container)
{
    if (!start_expr.empty() || !stop_expr.empty()) {
        sparta_assert(!db_namespace.empty());
        sparta_assert(rtn != nullptr);
    }

    db_accessor_ = db_accessor;
    db_namespace_ = db_namespace;

    if (!start_expr.empty()) {
        const std::string trig_name = "GrantAccess_" + db_namespace;
        auto handler = CREATE_SPARTA_HANDLER(
            DatabaseAccessor::AccessTrigger, grantAccess_);

        start_ = std::make_shared<trigger::ExpressionTrigger>(
            trig_name,
            handler,
            start_expr,
            rtn->getSearchScope(),
            sub_container);
    }

    if (!stop_expr.empty()) {
        const std::string trig_name = "RevokeAccess_" + db_namespace;
        auto handler = CREATE_SPARTA_HANDLER(
            DatabaseAccessor::AccessTrigger, revokeAccess_);

        stop_ = std::make_shared<trigger::ExpressionTrigger>(
            trig_name,
            handler,
            stop_expr,
            rtn->getSearchScope(),
            sub_container);
    }
}

void DatabaseAccessor::setAccessOptsFromFile_(
    const std::string & opt_file)
{
    if (!sub_container_) {
        sub_container_ = std::make_shared<SubContainer>();
    }

    std::ifstream fin(opt_file);
    if (!fin) {
        return;
    }

    struct NamespaceAccess {
        void beginNewNamespace(const std::string & line) {
            components_.clear();
            start_trig_expr_.clear();
            stop_trig_expr_.clear();
            is_parsing_components_ = false;

            auto sep = line.find(":");
            ns_name_ = line.substr(0, sep);
            boost::trim(ns_name_);
            std::transform(ns_name_.begin(), ns_name_.end(),
                           ns_name_.begin(), ::tolower);
        }

        const std::string & getNamespaceName() const {
            return ns_name_;
        }

        void beginComponents() {
            is_parsing_components_ = true;
        }

        bool isParsingComponents() const {
            return is_parsing_components_;
        }

        void addComponent(const std::string & component) {
            components_.emplace_back(component);
        }

        const std::vector<std::string> & getComponents() const {
            return components_;
        }

        void setStartTrigExpr(const std::string & expr) {
            start_trig_expr_ = expr;
        }

        void setStopTrigExpr(const std::string & expr) {
            stop_trig_expr_ = expr;
        }

        const std::string & getStartTrigExpr() const {
            return start_trig_expr_;
        }

        const std::string & getStopTrigExpr() const {
            return stop_trig_expr_;
        }

    private:
        std::string ns_name_;
        std::vector<std::string> components_;
        std::string start_trig_expr_;
        std::string stop_trig_expr_;
        bool is_parsing_components_ = false;
    };

    auto is_namespace = [](const std::string & line) {
        if (line.find("components:") != std::string::npos) {
            return false;
        }
        if (line.find("start:") != std::string::npos) {
            return false;
        }
        if (line.find("stop:") != std::string::npos) {
            return false;
        }
        return line.find(":") != std::string::npos;
    };

    auto is_component = [](const std::string & line) {
        std::string line_(line);
        boost::trim(line_);
        return line_ == "components:";
    };

    auto is_start_trig = [](const std::string & line) {
        std::string line_(line);
        boost::trim(line_);
        return line_.find("start:") == 0;
    };

    auto is_stop_trig = [](const std::string & line) {
        std::string line_(line);
        boost::trim(line_);
        return line_.find("stop:") == 0;
    };

    NamespaceAccess accessor;
    std::vector<NamespaceAccess> finalized_accessors;
    for (std::string line; std::getline(fin, line); ) {
        if (is_namespace(line)) {
            finalized_accessors.emplace_back(accessor);
            accessor.beginNewNamespace(line);
        } else if (is_component(line)) {
            accessor.beginComponents();
        } else if (is_start_trig(line)) {
            accessor.setStartTrigExpr(line.substr(line.find(":") + 1));
        } else if (is_stop_trig(line)) {
            accessor.setStopTrigExpr(line.substr(line.find(":") + 1));
        } else if (accessor.isParsingComponents()) {
            accessor.addComponent(line);
        }
    }
    finalized_accessors.emplace_back(accessor);

    for (const auto & access : finalized_accessors) {
        if (!access.getNamespaceName().empty()) {
            access_triggers_.emplace_back(new AccessTrigger(
                this,
                access.getNamespaceName(),
                access.getStartTrigExpr(),
                access.getStopTrigExpr(),
                root_,
                sub_container_));
        }

        for (const auto & comp : access.getComponents()) {
            enableComponentAtLocation_(access.getNamespaceName(), comp);
        }
    }
}

} // namespace sparta

max_stars_repo_name: knute-sifive/map

max_issues_repo_name: knute-sifive/map

max_forks_repo_name: knute-sifive/map


text:
#include <cmdstan/stansummary_helper.hpp>
#include <test/utility.hpp>
#include <stan/io/ends_with.hpp>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <gtest/gtest.h>
#include <CLI11/CLI11.hpp>

using cmdstan::test::count_matches;
using cmdstan::test::get_path_separator;
using cmdstan::test::run_command;
using cmdstan::test::run_command_output;

TEST(CommandStansummary, next_index_1d) {
  std::vector<int> dims(1);
  std::vector<int> index(1, 1);
  dims[0] = 100;

  ASSERT_EQ(1U, index.size());
  EXPECT_EQ(1, index[0]);
  for (int n = 1; n <= 100; n++) {
    if (n == 1)
      continue;
    next_index(index, dims);
    ASSERT_EQ(1U, index.size());
    EXPECT_EQ(n, index[0]);
  }

  index[0] = 100;
  EXPECT_THROW(next_index(index, dims), std::domain_error);

  index[0] = 1000;
  EXPECT_THROW(next_index(index, dims), std::domain_error);
}

TEST(CommandStansummary, next_index_2d) {
  std::vector<int> dims(2);
  std::vector<int> index(2, 1);
  dims[0] = 100;
  dims[1] = 3;

  ASSERT_EQ(2U, index.size());
  EXPECT_EQ(1, index[0]);
  EXPECT_EQ(1, index[1]);
  for (int i = 1; i <= 100; i++)
    for (int j = 1; j <= 3; j++) {
      if (i == 1 && j == 1)
        continue;
      next_index(index, dims);
      ASSERT_EQ(2U, index.size());
      EXPECT_EQ(i, index[0]);
      EXPECT_EQ(j, index[1]);
    }

  index[0] = 100;
  index[1] = 3;
  EXPECT_THROW(next_index(index, dims), std::domain_error);

  index[0] = 1000;
  index[1] = 1;
  EXPECT_THROW(next_index(index, dims), std::domain_error);

  index[0] = 10;
  index[1] = 4;
  EXPECT_NO_THROW(next_index(index, dims))
      << "this will correct the index and set the next element to (11,1)";
  EXPECT_EQ(11, index[0]);
  EXPECT_EQ(1, index[1]);
}

TEST(CommandStansummary, matrix_index_1d) {
  std::vector<int> dims(1);
  std::vector<int> index(1, 1);
  dims[0] = 100;

  EXPECT_EQ(0, matrix_index(index, dims));

  index[0] = 50;
  EXPECT_EQ(49, matrix_index(index, dims));

  index[0] = 100;
  EXPECT_EQ(99, matrix_index(index, dims));

  index[0] = 0;
  EXPECT_THROW(matrix_index(index, dims), std::domain_error);

  index[0] = 101;
  EXPECT_THROW(matrix_index(index, dims), std::domain_error);
}

TEST(CommandStansummary, matrix_index_2d) {
  std::vector<int> dims(2);
  std::vector<int> index(2, 1);
  dims[0] = 100;
  dims[1] = 3;

  EXPECT_EQ(0, matrix_index(index, dims));

  index[0] = 50;
  index[1] = 1;
  EXPECT_EQ(49, matrix_index(index, dims));

  index[0] = 100;
  index[1] = 1;
  EXPECT_EQ(99, matrix_index(index, dims));

  index[0] = 1;
  index[1] = 2;
  EXPECT_EQ(100, matrix_index(index, dims));

  index[0] = 1;
  index[1] = 3;
  EXPECT_EQ(200, matrix_index(index, dims));

  index[0] = 100;
  index[1] = 3;
  EXPECT_EQ(299, matrix_index(index, dims));

  index[0] = 1;
  index[1] = 0;
  EXPECT_THROW(matrix_index(index, dims), std::domain_error);

  index[0] = 0;
  index[1] = 1;
  EXPECT_THROW(matrix_index(index, dims), std::domain_error);

  index[0] = 101;
  index[1] = 1;
  EXPECT_THROW(matrix_index(index, dims), std::domain_error);

  index[0] = 1;
  index[1] = 4;
  EXPECT_THROW(matrix_index(index, dims), std::domain_error);
}

TEST(CommandStansummary, header_tests) {
  std::string expect
      = "      Mean  MCSE StdDev     10%      50%       90%      N_Eff     "
        "N_Eff/s        R_hat\n";
  std::string expect_csv
      = "name,Mean,MCSE,StdDev,10%,50%,90%,N_Eff,N_Eff/s,R_hat\n";
  std::vector<std::string> pcts;
  pcts.push_back("10");
  pcts.push_back("50");
  pcts.push_back("90");
  Eigen::VectorXd probs = percentiles_to_probs(pcts);
  EXPECT_FLOAT_EQ(probs[0], 0.1);
  EXPECT_FLOAT_EQ(probs[1], 0.5);
  EXPECT_FLOAT_EQ(probs[2], 0.9);

  std::vector<std::string> header = get_header(pcts);
  EXPECT_EQ(header.size(), pcts.size() + 6);
  EXPECT_EQ(header[0], "Mean");
  EXPECT_EQ(header[2], "StdDev");
  EXPECT_EQ(header[4], "50%");
  EXPECT_EQ(header[6], "N_Eff");
  EXPECT_EQ(header[8], "R_hat");

  Eigen::VectorXi column_widths(header.size());
  for (size_t i = 0, w = 5; i < header.size(); ++i, ++w) {
    column_widths[i] = w;
  }
  std::stringstream ss;
  write_header(header, column_widths, 4, false, &ss);
  EXPECT_EQ(expect, ss.str());
  ss.str(std::string());
  write_header(header, column_widths, 24, true, &ss);
  EXPECT_EQ(expect_csv, ss.str());
}

TEST(CommandStansummary, param_tests) {
  std::string path_separator;
  path_separator.push_back(get_path_separator());

  std::vector<std::string> pcts;
  pcts.push_back("10");
  pcts.push_back("50");
  pcts.push_back("90");
  Eigen::VectorXd probs = percentiles_to_probs(pcts);

  // bernoulli model:  6 sampler params, ("lp__", is model param)
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";
  std::vector<std::string> filenames;
  filenames.push_back(csv_file);
  stan::io::stan_csv_metadata metadata;
  Eigen::VectorXd warmup_times(filenames.size());
  Eigen::VectorXd sampling_times(filenames.size());
  Eigen::VectorXi thin(filenames.size());
  stan::mcmc::chains<> chains = parse_csv_files(
      filenames, metadata, warmup_times, sampling_times, thin, &std::cout);
  EXPECT_EQ(chains.num_chains(), 1);
  EXPECT_EQ(chains.num_params(), 8);

  size_t max_name_length = 0;
  size_t num_sampler_params = -1;  // don't count name 'lp__'
  for (int i = 0; i < chains.num_params(); ++i) {
    if (chains.param_name(i).length() > max_name_length)
      max_name_length = chains.param_name(i).length();
    if (stan::io::ends_with("__", chains.param_name(i)))
      num_sampler_params++;
  }
  EXPECT_EQ(num_sampler_params, 6);

  size_t model_params_offset = num_sampler_params + 1;
  size_t num_model_params = chains.num_params() - model_params_offset;
  EXPECT_EQ(num_model_params, 1);

  Eigen::MatrixXd model_params(num_model_params, 9);
  get_stats(chains, warmup_times, sampling_times, probs, model_params_offset,
            model_params);

  double mean_theta = model_params(0, 0);
  EXPECT_TRUE(mean_theta > 0.25);
  EXPECT_TRUE(mean_theta < 0.27);
  double rhat_theta = model_params(0, 8);
  EXPECT_TRUE(rhat_theta > 0.999);
  EXPECT_TRUE(rhat_theta < 1.01);
}

// good csv file, no draws
TEST(CommandStansummary, functional_test__issue_342) {
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "matrix_output.csv";
  run_command_output out = run_command(command + " " + csv_file);
  ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error";
}

// good csv file, variational inference
TEST(CommandStansummary, variational_inference) {
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator
                         + "variational_inference_output.csv";
  run_command_output out = run_command(command + " " + csv_file);
  ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error";
}

TEST(CommandStansummary, no_args) {
  std::string expected_message = "Usage: stansummary";
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  run_command_output out = run_command(command);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";
}

TEST(CommandStansummary, bad_input_files) {
  std::string expected_message = "File does not exist";
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "no_such_file";
  run_command_output out = run_command(command + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";
}

TEST(CommandStansummary, bad_csv_file_arg) {
  std::string expected_message = "Cannot save to csv_filename";
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";
  std::string arg_csv_file = "--csv_filename " + path_separator + "bin"
                             + path_separator + "hi_mom.csv";

  run_command_output out
      = run_command(command + " " + arg_csv_file + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";
}

TEST(CommandStansummary, bad_sig_figs_arg) {
  std::string expected_message = "--sig_figs: Value -1 not in range";
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";
  std::string arg_sig_figs = "--sig_figs -1";

  run_command_output out
      = run_command(command + " " + arg_sig_figs + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";

  arg_sig_figs = "--sig_figs 101";
  expected_message = "--sig_figs: Value 101 not in range";
  out = run_command(command + " " + arg_sig_figs + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";
}

TEST(CommandStansummary, bad_autocorr_arg) {
  std::string expected_message = "--autocorr: Number less or equal to 0";
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";
  std::string arg_autocorr = "--autocorr -1";

  run_command_output out
      = run_command(command + " " + arg_autocorr + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";

  arg_autocorr = "--autocorr 0";
  out = run_command(command + " " + arg_autocorr + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";

  expected_message = "not a valid chain id";
  arg_autocorr = "--autocorr 2";
  out = run_command(command + " " + arg_autocorr + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";
}

TEST(CommandStansummary, bad_percentiles_arg) {
  std::string expected_message = "Option --percentiles";
  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";

  std::string arg_percentiles = "--percentiles -1";
  run_command_output out
      = run_command(command + " " + arg_percentiles + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";

  arg_percentiles = "--percentiles \"0,100\"";
  out = run_command(command + " " + arg_percentiles + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";

  arg_percentiles = "--percentiles \"2,30,5\"";
  out = run_command(command + " " + arg_percentiles + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, expected_message));
  ASSERT_TRUE(out.hasError)
      << "\"" << out.command << "\" failed to quit with an error";

  arg_percentiles = "--percentiles \"2,50,95\"";
  out = run_command(command + " " + arg_percentiles + " " + csv_file);
  ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error";
}

TEST(CommandStansummary, check_console_output) {
  std::string lp
      = "lp__            -7.3  3.7e-02     0.77   -9.1  -7.0  -6.8      443    "
        "19275      1.0";
  std::string theta
      = "theta           0.26  6.1e-03     0.12  0.079  0.25  0.47      384    "
        "16683     1.00";
  std::string accept_stat
      = "accept_stat__   0.90  4.6e-03  1.5e-01   0.57  0.96   1.0  1.0e+03  "
        "4.5e+04  1.0e+00";
  std::string energy
      = "energy__         7.8  5.1e-02  1.0e+00    6.8   7.5   9.9  4.1e+02  "
        "1.8e+04  1.0e+00";

  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";

  run_command_output out = run_command(command + " " + csv_file);
  EXPECT_TRUE(boost::algorithm::contains(out.output, lp));
  EXPECT_TRUE(boost::algorithm::contains(out.output, theta));
  EXPECT_TRUE(boost::algorithm::contains(out.output, accept_stat));
  EXPECT_TRUE(boost::algorithm::contains(out.output, energy));
  ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error";
}

TEST(CommandStansummary, check_csv_output) {
  std::string csv_header
      = "name,Mean,MCSE,StdDev,5%,50%,95%,N_Eff,N_Eff/s,R_hat";
  std::string lp
      = "\"lp__\",-7.2719,0.0365168,0.768874,-9.05757,-6.96978,-6.75008,443."
        "328,19275.1,1.00037";
  std::string energy
      = "\"energy__\""
        ",7.78428,0.0508815,1.0314,6.80383,7.46839,9.88601,410."
        "898,17865.1,1.00075";
  std::string theta
      = "\"theta\",0.256552,0.00610844,0.119654,0.0786292,0.24996,0.470263,383."
        "704,16682.8,0.999309";

  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";

  std::string target_csv_file = "src" + path_separator + "test" + path_separator
                                + "interface" + path_separator
                                + "example_output" + path_separator
                                + "tmp_test_target_csv_file.csv";
  std::string arg_csv_file = "--csv_filename=" + target_csv_file;

  run_command_output out
      = run_command(command + " " + arg_csv_file + " " + csv_file);
  ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error";

  std::ifstream target_stream(target_csv_file.c_str());
  if (!target_stream.is_open())
    FAIL();
  std::string line;
  std::getline(target_stream, line);
  EXPECT_EQ(csv_header, line);
  std::getline(target_stream, line);
  EXPECT_EQ(lp, line);
  std::getline(target_stream, line);  // accept_stat
  std::getline(target_stream, line);  // stepsize
  std::getline(target_stream, line);  // treedepth
  std::getline(target_stream, line);  // n_leapfrog
  std::getline(target_stream, line);  // divergent
  std::getline(target_stream, line);  // energy
  EXPECT_EQ(energy, line);
  std::getline(target_stream, line);
  EXPECT_EQ(theta, line);
  target_stream.close();
  int return_code = std::remove(target_csv_file.c_str());
  if (return_code != 0)
    FAIL();
}

TEST(CommandStansummary, check_csv_output_sig_figs) {
  std::string csv_header
      = "name,Mean,MCSE,StdDev,5%,50%,95%,N_Eff,N_Eff/s,R_hat";
  std::string lp = "\"lp__\",-7.3,0.037,0.77,-9.1,-7,-6.8,4.4e+02,1.9e+04,1";
  std::string energy = "\"energy__\",7.8,0.051,1,6.8,7.5,9.9,4.1e+02,1.8e+04,1";
  std::string theta
      = "\"theta\",0.26,0.0061,0.12,0.079,0.25,0.47,3.8e+02,1.7e+04,1";

  std::string path_separator;
  path_separator.push_back(get_path_separator());
  std::string command = "bin" + path_separator + "stansummary";
  std::string csv_file = "src" + path_separator + "test" + path_separator
                         + "interface" + path_separator + "example_output"
                         + path_separator + "bernoulli_chain_1.csv";

  std::string target_csv_file = "src" + path_separator + "test" + path_separator
                                + "interface" + path_separator
                                + "example_output" + path_separator
                                + "tmp_test_target_csv_file.csv";
  std::string arg_csv_file = "--csv_filename " + target_csv_file;
  std::string arg_sig_figs = "--sig_figs 2";

  run_command_output out = run_command(command + " " + arg_csv_file + " "
                                       + arg_sig_figs + " " + csv_file);
  ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error";

  std::ifstream target_stream(target_csv_file.c_str());
  if (!target_stream.is_open())
    FAIL();
  std::string line;
  std::getline(target_stream, line);
  EXPECT_EQ(csv_header, line);
  std::getline(target_stream, line);
  EXPECT_EQ(lp, line);
  std::getline(target_stream, line);  // accept_stat
  std::getline(target_stream, line);  // stepsize
  std::getline(target_stream, line);  // treedepth
  std::getline(target_stream, line);  // n_leapfrog
  std::getline(target_stream, line);  // divergent
  std::getline(target_stream, line);  // energy
  EXPECT_EQ(energy, line);
  std::getline(target_stream, line);
  EXPECT_EQ(theta, line);
  target_stream.close();
  int return_code = std::remove(target_csv_file.c_str());
  if (return_code != 0)
    FAIL();
}

ext: cpp

max_stars_repo_name: jtimonen/cmdstan

max_issues_repo_name: jtimonen/cmdstan

max_forks_repo_name: jtimonen/cmdstan


text:
#pragma once
#include <string>
#include <Eigen/Dense>
#include <opencv2/opencv.hpp>
#include "NeuronScene.hpp"
#include "../render/Render.hpp"
#include "../render/camera/OrthographicCamera.hpp"

constexpr auto title = "neuron-sdf-viewer";
constexpr auto width = 620;
constexpr auto height = 480;

class NeuronViewer
{
public:
    NeuronViewer() : scene(), camera(-width / 2, width / 2, height / 2, -height / 2, 0.5, 2000), render(width, height){};

    void load(std::string model) { scene.load(model); };

    void build_bvh() { scene.build_bvh(); };

    void render_image() { render.draw(scene, camera); };

    void show_image()
    {
        auto &colorBuffer = render.get_frame_buffer();
        cv::Mat img(height, width, CV_8UC3, colorBuffer.data());
        cv::imshow(title, img);
        cv::waitKey(0);
    };

private:
    NeuronScene scene;

    OrthographicCamera camera;

    Render render;
};

ext: hpp


text:
//  Copyright (c) 2007-2014 Hartmut Kaiser
//
//  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)

/// \file parallel/algorithms/for_each.hpp

#if !defined(HPX_PARALLEL_DETAIL_FOR_EACH_MAY_29_2014_0932PM)
#define HPX_PARALLEL_DETAIL_FOR_EACH_MAY_29_2014_0932PM

#include <hpx/hpx_fwd.hpp>
#include <hpx/traits/segmented_iterator_traits.hpp>
#include <hpx/util/void_guard.hpp>
#include <hpx/util/move.hpp>

#include <hpx/parallel/config/inline_namespace.hpp>
#include <hpx/parallel/execution_policy.hpp>
#include <hpx/parallel/algorithms/detail/algorithm_result.hpp>
#include <hpx/parallel/algorithms/detail/dispatch.hpp>
#include <hpx/parallel/algorithms/detail/is_negative.hpp>
#include <hpx/parallel/util/foreach_partitioner.hpp>
#include <hpx/parallel/util/loop.hpp>

#include <algorithm>
#include <iterator>
#include <type_traits>

#include <boost/static_assert.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/is_same.hpp>

namespace hpx { namespace parallel { HPX_INLINE_NAMESPACE(v1)
{
    ///////////////////////////////////////////////////////////////////////////
    // for_each_n
    namespace detail
    {
        /// \cond NOINTERNAL
        template <typename Iter>
        struct for_each_n : public detail::algorithm<for_each_n<Iter>, Iter>
        {
            for_each_n()
              : for_each_n::algorithm("for_each_n")
            {}

            template <typename ExPolicy, typename F>
            static Iter
            sequential(ExPolicy const&, Iter first, std::size_t count, F && f)
            {
                return util::loop_n(first, count,
                    [f](Iter const& curr)
                    {
                        f(*curr);
                    });
            }

            template <typename ExPolicy, typename F>
            static typename detail::algorithm_result<ExPolicy, Iter>::type
            parallel(ExPolicy const& policy, Iter first, std::size_t count,
                F && f)
            {
                if (count != 0)
                {
                    return util::foreach_n_partitioner<ExPolicy>::call(
                        policy, first, count,
                        [f](Iter part_begin, std::size_t part_size)
                        {
                            util::loop_n(part_begin, part_size,
                                [&f](Iter const& curr)
                                {
                                    f(*curr);
                                });
                        });
                }

                return detail::algorithm_result<ExPolicy, Iter>::get(
                    std::move(first));
            }
        };
        /// \endcond
    }

    /// Applies \a f to the result of dereferencing every iterator in the range
    /// [first, first + count), starting from first and proceeding to
    /// first + count - 1.
    ///
    /// \note   Complexity: Applies \a f exactly \a count times.
    ///
    /// If \a f returns a result, the result is ignored.
    ///
    /// If the type of \a first satisfies the requirements of a mutable
    /// iterator, \a f may apply non-constant functions through the
    /// dereferenced iterator.
    ///
    /// Unlike its sequential form, the parallel overload of
    /// \a for_each does not return a copy of its \a Function parameter,
    /// since parallelization may not permit efficient state
    /// accumulation.
    ///
    /// \tparam ExPolicy    The type of the execution policy to use (deduced).
    ///                     It describes the manner in which the execution
    ///                     of the algorithm may be parallelized and the manner
    ///                     in which it applies user-provided function objects.
    /// \tparam InIter      The type of the source iterators used (deduced).
    ///                     This iterator type must meet the requirements of an
    ///                     input iterator.
    /// \tparam Size        The type of the argument specifying the number of
    ///                     elements to apply \a f to.
    /// \tparam F           The type of the function/function object to use
    ///                     (deduced). Unlike its sequential form, the parallel
    ///                     overload of \a for_each requires \a F to meet the
    ///                     requirements of \a CopyConstructible.
    ///
    /// \param policy       The execution policy to use for the scheduling of
    ///                     the iterations.
    /// \param first        Refers to the beginning of the sequence of elements
    ///                     the algorithm will be applied to.
    /// \param count        Refers to the number of elements starting at
    ///                     \a first the algorithm will be applied to.
    /// \param f            Specifies the function (or function object) which
    ///                     will be invoked for each of the elements in the
    ///                     sequence specified by [first, last).
    ///                     The signature of this predicate
    ///                     should be equivalent to:
    ///                     \code
    ///                     <ignored> pred(const Type &a);
    ///                     \endcode \n
    ///                     The signature does not need to have const&. The
    ///                     type \a Type must be such that an object of
    ///                     type \a InIter can be dereferenced and then
    ///                     implicitly converted to Type.
    ///
    /// The application of function objects in parallel algorithm
    /// invoked with an execution policy object of type
    /// \a sequential_execution_policy execute in sequential order in the
    /// calling thread.
    ///
    /// The application of function objects in parallel algorithm
    /// invoked with an execution policy object of type
    /// \a parallel_execution_policy or \a parallel_task_execution_policy are
    /// permitted to execute in an unordered fashion in unspecified
    /// threads, and indeterminately sequenced within each thread.
    ///
    /// \returns  The \a for_each_n algorithm returns a
    ///           \a hpx::future<InIter> if the execution policy is of
    ///           type
    ///           \a sequential_task_execution_policy or
    ///           \a parallel_task_execution_policy and returns \a InIter
    ///           otherwise.
    ///           It returns \a first + \a count for non-negative values of
    ///           \a count and \a first for negative values.
    ///
    template <typename ExPolicy, typename InIter, typename Size, typename F>
    inline typename boost::enable_if<
        is_execution_policy<ExPolicy>,
        typename detail::algorithm_result<ExPolicy, InIter>::type
    >::type
    for_each_n(ExPolicy && policy, InIter first, Size count, F && f)
    {
        typedef typename std::iterator_traits<InIter>::iterator_category
            iterator_category;

        BOOST_STATIC_ASSERT_MSG(
            (boost::is_base_of<std::input_iterator_tag, iterator_category>::value),
            "Requires at least input iterator.");

        // if count is representing a negative value, we do nothing
        if (detail::is_negative<Size>::call(count))
        {
            return detail::algorithm_result<ExPolicy, InIter>::get(
                std::move(first));
        }

        typedef typename boost::mpl::or_<
            is_sequential_execution_policy<ExPolicy>,
            boost::is_same<std::input_iterator_tag, iterator_category>
        >::type is_seq;

        return detail::for_each_n<InIter>().call(
            std::forward<ExPolicy>(policy), is_seq(),
            first, std::size_t(count), std::forward<F>(f));
    }

    ///////////////////////////////////////////////////////////////////////////
    // for_each
    namespace detail
    {
        /// \cond NOINTERNAL
        struct for_each : public detail::algorithm<for_each>
        {
            for_each()
              : for_each::algorithm("for_each")
            {}

            template <typename ExPolicy, typename InIter, typename F>
            static hpx::util::unused_type
            sequential(ExPolicy const&, InIter first, InIter last, F && f)
            {
                std::for_each(first, last, std::forward<F>(f));
                return hpx::util::unused;
            }

            template <typename ExPolicy, typename FwdIter, typename F>
            static typename detail::algorithm_result<ExPolicy>::type
            parallel(ExPolicy const& policy, FwdIter first, FwdIter last, F && f)
            {
                typedef
                    typename detail::algorithm_result<ExPolicy>::type
                result_type;

                return hpx::util::void_guard<result_type>(),
                    detail::for_each_n<FwdIter>().call(
                        policy, boost::mpl::false_(),
                        first, std::distance(first, last), std::forward<F>(f));
            }
        };

        ///////////////////////////////////////////////////////////////////////
        // non-segmented implementation
        template <typename ExPolicy, typename InIter, typename F>
        inline typename detail::algorithm_result<ExPolicy>::type
        for_each_(ExPolicy && policy, InIter first, InIter last, F && f,
            std::false_type)
        {
            typedef typename std::iterator_traits<InIter>::iterator_category
                iterator_category;

            typedef typename boost::mpl::or_<
                parallel::is_sequential_execution_policy<ExPolicy>,
                boost::is_same<std::input_iterator_tag, iterator_category>
            >::type is_seq;

            if (first == last)
                return detail::algorithm_result<ExPolicy>::get();

            return for_each().call(
                std::forward<ExPolicy>(policy), is_seq(),
                first, last, std::forward<F>(f));
        }

        // forward declare the segmented version of this algorithm
        template <typename ExPolicy, typename SegIter, typename F>
        inline typename detail::algorithm_result<ExPolicy>::type
        for_each_(ExPolicy && policy, SegIter first, SegIter last, F && f,
            std::true_type);

        /// \endcond
    }

    /// Applies \a f to the result of dereferencing every iterator in the
    /// range [first, last).
    ///
    /// \note   Complexity: Applies \a f exactly \a last - \a first times.
    ///
    /// If \a f returns a result, the result is ignored.
    ///
    /// If the type of \a first satisfies the requirements of a mutable
    /// iterator, \a f may apply non-constant functions through the
    /// dereferenced iterator.
    ///
    /// Unlike its sequential form, the parallel overload of
    /// \a for_each does not return a copy of its \a Function parameter,
    /// since parallelization may not permit efficient state
    /// accumulation.
    ///
    /// \tparam ExPolicy    The type of the execution policy to use (deduced).
    ///                     It describes the manner in which the execution
    ///                     of the algorithm may be parallelized and the manner
    ///                     in which it applies user-provided function objects.
    /// \tparam InIter      The type of the source iterators used (deduced).
    ///                     This iterator type must meet the requirements of an
    ///                     input iterator.
    /// \tparam F           The type of the function/function object to use
    ///                     (deduced). Unlike its sequential form, the parallel
    ///                     overload of \a for_each requires \a F to meet the
    ///                     requirements of \a CopyConstructible.
    ///
    /// \param policy       The execution policy to use for the scheduling of
    ///                     the iterations.
    /// \param first        Refers to the beginning of the sequence of elements
    ///                     the algorithm will be applied to.
    /// \param last         Refers to the end of the sequence of elements the
    ///                     algorithm will be applied to.
    /// \param f            Specifies the function (or function object) which
    ///                     will be invoked for each of the elements in the
    ///                     sequence specified by [first, last).
    ///                     The signature of this predicate
    ///                     should be equivalent to:
    ///                     \code
    ///                     <ignored> pred(const Type &a);
    ///                     \endcode \n
    ///                     The signature does not need to have const&. The
    ///                     type \a Type must be such that an object of
    ///                     type \a InIter can be dereferenced and then
    ///                     implicitly converted to Type.
    ///
    /// The application of function objects in parallel algorithm
    /// invoked with an execution policy object of type
    /// \a sequential_execution_policy execute in sequential order in the
    /// calling thread.
    ///
    /// The application of function objects in parallel algorithm
    /// invoked with an execution policy object of type
    /// \a parallel_execution_policy or \a parallel_task_execution_policy are
    /// permitted to execute in an unordered fashion in unspecified
    /// threads, and indeterminately sequenced within each thread.
    ///
    /// \returns  The \a for_each algorithm returns a \a hpx::future<void> if the
    ///           execution policy is of type
    ///           \a sequential_task_execution_policy or
    ///           \a parallel_task_execution_policy and
    ///           returns \a void otherwise.
    ///
    template <typename ExPolicy, typename InIter, typename F>
    inline typename boost::enable_if<
        is_execution_policy<ExPolicy>,
        typename detail::algorithm_result<ExPolicy, void>::type
    >::type
    for_each(ExPolicy && policy, InIter first, InIter last, F && f)
    {
        typedef typename std::iterator_traits<InIter>::iterator_category
            iterator_category;

        BOOST_STATIC_ASSERT_MSG(
            (boost::is_base_of<std::input_iterator_tag, iterator_category>::value),
            "Requires at least input iterator.");

        typedef hpx::traits::segmented_iterator_traits<InIter> iterator_traits;
        typedef typename iterator_traits::is_segmented_iterator is_segmented;

        return detail::for_each_(
            std::forward<ExPolicy>(policy), first, last,
            std::forward<F>(f), is_segmented());
    }
}}}

#endif

max_stars_repo_name: akemp/hpx

max_issues_repo_name: akemp/hpx

max_forks_repo_name: akemp/hpx


text:
//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================

#include "smtk/mesh/Collection.h"
#include "smtk/mesh/Handle.h"
#include "smtk/mesh/Manager.h"

#include "smtk/mesh/testing/cxx/helpers.h"

//force to use filesystem version 3
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>
using namespace boost::filesystem;

namespace
{

inline smtk::mesh::Handle to_handle(::moab::EntityType type,
                                    ::moab::EntityID id)
{
  const std::size_t id_width = (8*sizeof(smtk::mesh::Handle)-4);
  if (type > ::moab::MBMAXTYPE)
    {
    return smtk::mesh::Handle();
    }
  return (((smtk::mesh::Handle)type) << id_width)|id;
}

//----------------------------------------------------------------------------
void verify_empty_handle()
{
  smtk::mesh::HandleRange range;

  //convert empty handle to json
  cJSON* json = smtk::mesh::to_json(range);

  //verify that the json has no children, since the range is empty
  test( (json->child == NULL), "empty handle range json form should be empty" );

  //convert back to a handle
  smtk::mesh::HandleRange result = smtk::mesh::from_json(json);

  test( result == range, "empty handle didn't serialize properly");
}

//----------------------------------------------------------------------------
void verify_meshset_handle()
{
  smtk::mesh::Handle first = to_handle(::moab::MBENTITYSET, 1);
  smtk::mesh::Handle second = to_handle(::moab::MBENTITYSET, 1024);

  //make range have 1024 meshes
  smtk::mesh::HandleRange range;
  range.insert(first,second);

  test( range.size() == 1024, "verify range has proper length");
  test( range.all_of_type( ::moab::MBENTITYSET) == true, "verify range is all mesh sets");

  //now verify that it converts to json properly
  cJSON* json = smtk::mesh::to_json(range);

  //verify that the json has no children, since the range is empty
  test( (json->child != NULL), "meshset handle json form should have a child node" );

  //convert back to a handle
  smtk::mesh::HandleRange result = smtk::mesh::from_json(json);
  test( result == range, "meshset handle didn't serialize properly");
}

//----------------------------------------------------------------------------
void verify_single_cell_type_handle()
{
  smtk::mesh::Handle first = to_handle(::moab::MBHEX, 1);
  smtk::mesh::Handle second = to_handle(::moab::MBHEX, 450);

  //make range have 1024 meshes
  smtk::mesh::HandleRange range;
  range.insert(first,second);

  //now verify that it converts to json properly
  cJSON* json = smtk::mesh::to_json(range);

  //verify that the json has no children, since the range is empty
  test( (json->child != NULL), "meshset handle json form should have a child node" );

  //convert back to a handle
  smtk::mesh::HandleRange result = smtk::mesh::from_json(json);
  test( result == range, "single cell set handle didn't serialize properly");
}

//----------------------------------------------------------------------------
void verify_mixed_handle()
{
  smtk::mesh::Handle first = to_handle(::moab::MBENTITYSET, 1);
  smtk::mesh::Handle second = to_handle(::moab::MBENTITYSET, 45);

  smtk::mesh::Handle third = to_handle(::moab::MBENTITYSET, 100);
  smtk::mesh::Handle fourth = to_handle(::moab::MBENTITYSET, 450);

  smtk::mesh::Handle fifth = to_handle(::moab::MBHEX, 1);
  smtk::mesh::Handle sixth = to_handle(::moab::MBHEX, 450);

  //make range have 1024 meshes
  smtk::mesh::HandleRange range;
  range.insert(first,second);
  range.insert(third,fourth);
  range.insert(fifth,sixth);

  //now verify that it converts to json properly
  cJSON* json = smtk::mesh::to_json(range);

  //verify that the json has no children, since the range is empty
  test( (json->child != NULL), "meshset handle json form should have a child node" );

  //convert back to a handle
  smtk::mesh::HandleRange result = smtk::mesh::from_json(json);
  test( result == range, "mixed cell set handle didn't serialize properly");
}

//----------------------------------------------------------------------------
void verify_large_number_of_values_handle()
{
  smtk::mesh::Handle first = to_handle(::moab::MBENTITYSET, 1);
  smtk::mesh::Handle second = to_handle(::moab::MBENTITYSET, 2048);

  smtk::mesh::Handle third = to_handle(::moab::MBHEX, 0);
  smtk::mesh::Handle fourth = to_handle(::moab::MBHEX, 4194303);

  smtk::mesh::Handle fifth = to_handle(::moab::MBHEX, 0);
  smtk::mesh::Handle sixth = to_handle(::moab::MBHEX, 8388607);

  //make range have 1024 meshes
  smtk::mesh::HandleRange range;
  range.insert(first,second);
  range.insert(third,fourth);
  range.insert(fifth,sixth);

  //now verify that it converts to json properly
  cJSON* json = smtk::mesh::to_json(range);

  //verify that the json has no children, since the range is empty
  test( (json->child != NULL), "meshset handle json form should have a child node" );

  //convert back to a handle
  smtk::mesh::HandleRange result = smtk::mesh::from_json(json);
  test( result == range, "mixed cell set handle didn't serialize properly");
}

}

//----------------------------------------------------------------------------
int UnitTestReadWriteHandles(int, char** const)
{
  verify_empty_handle();

  verify_meshset_handle();
  verify_single_cell_type_handle();
  verify_mixed_handle();

  verify_large_number_of_values_handle();
  return 0;
}

ext: cxx

max_stars_repo_name: yumin/SMTK

max_issues_repo_name: yumin/SMTK

max_forks_repo_name: yumin/SMTK


text:
// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
#define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1
#endif

#include "main.hxx"

#include <memory>

#include <boost/numeric/conversion/cast.hpp>

#if HAVE_DUNE_GRID
#include <dune/grid/yaspgrid.hh>
#endif

#include <dune/geometry/quadraturerules.hh>

#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/functions/flattop.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/fvector.hh>

#include "functions.hh"

#if HAVE_DUNE_GRID

using namespace Dune;
using namespace Stuff;

template <class G>
class FlatTopFunctionType
{
  typedef typename G::template Codim<0>::Entity E;
  typedef typename G::ctype D;
  static const size_t d = G::dimension;
  typedef double R;
  static const size_t r  = 1;
  static const size_t rC = 1;

public:
  typedef Functions::FlatTop<E, D, d, R, r, rC> value;
}; // struct FlatTopFunctionType

template <class DimDomain>
class FlatTopFunctionTest
    : public FunctionTest<
          typename FlatTopFunctionType<YaspGrid<DimDomain::value,
                                                EquidistantOffsetCoordinates<double, DimDomain::value>>>::value>
{
protected:
  typedef YaspGrid<DimDomain::value, EquidistantOffsetCoordinates<double, DimDomain::value>> GridType;
  typedef typename FlatTopFunctionType<GridType>::value FunctionType;

  static std::shared_ptr<GridType> create_grid() { return Stuff::Grid::Providers::Cube<GridType>(0, 3, 12).grid_ptr(); }

  template <class P, class V, class L, class R, class D, class E>
  static void check(const P& point, const V& value, const L& left, const R& right, const D& delta, const E& top_value)
  {
    if (Common::FloatCmp::lt(point, left - delta) || Common::FloatCmp::gt(point, right + delta)) {
      // outside
      EXPECT_EQ(0.0, value) << point;
    } else if (Common::FloatCmp::ge(point, left + delta) && Common::FloatCmp::le(point, right - delta)) {
      // inside
      EXPECT_EQ(top_value, value) << point;
    } else {
      // boundary layer
      if (top_value > 0.0) {
        EXPECT_GE(top_value, value) << point[0];
        EXPECT_LE(0.0, value) << point[0];
      } else {
        EXPECT_LE(top_value, value) << point[0];
        EXPECT_GE(0.0, value) << point[0];
      }
    }
  } // ... check(...)
};  // class FlatTopFunctionTest

typedef testing::Types<Int<1>, Int<2>, Int<3>> DimDomains;

TYPED_TEST_CASE(FlatTopFunctionTest, DimDomains);
TYPED_TEST(FlatTopFunctionTest, static_interface_check) { this->static_interface_check(); }
TYPED_TEST(FlatTopFunctionTest, static_create_check) { this->static_create_check(); }
TYPED_TEST(FlatTopFunctionTest, dynamic_interface_check)
{
  this->dynamic_interface_check(*(TestFixture::FunctionType::create()), *(this->create_grid()));
}
TYPED_TEST(FlatTopFunctionTest, evaluate_check)
{
  auto grid_ptr = this->create_grid();
  typedef DSC::FieldVector<double, TypeParam::value> DomainType;
  const DomainType left(1);
  const DomainType right(2);
  const DomainType delta(1e-6);
  const double value = 20;
  typename TestFixture::FunctionType func(left, right, delta, value, "bar");
  func.visualize(grid_ptr->leafGridView(), "dim_" + DSC::toString(int(TypeParam::value)));
  for (const auto& entity : Stuff::Common::entityRange(grid_ptr->leafGridView())) {
    const auto local_func  = func.local_function(entity);
    const auto& quadrature = QuadratureRules<double, TypeParam::value>::rule(
        entity.type(), boost::numeric_cast<int>(local_func->order() + 2));
    for (const auto& element : quadrature) {
      const auto& local_point = element.position();
      const auto point        = entity.geometry().global(local_point);
      const auto val = local_func->evaluate(local_point);
      this->check(point, val, left, right, delta, value);
    }
  }
}

#else // HAVE_DUNE_GRID

// no-compile placeholders to mark disabled tests in test-binary output
TEST(DISABLED_FlatTopFunctionTest, static_interface_check) {}
TEST(DISABLED_FlatTopFunctionTest, static_create_check) {}
TEST(DISABLED_FlatTopFunctionTest, dynamic_interface_check) {}
TEST(DISABLED_FlatTopFunctionTest, copy_check) {}
TEST(DISABLED_FlatTopFunctionTest, evaluate_check) {}

#endif // HAVE_DUNE_GRID

ext: cc

max_stars_repo_name: ftalbrecht/dune-stuff-simplified

max_issues_repo_name: ftalbrecht/dune-stuff-simplified

max_forks_repo_name: ftalbrecht/dune-stuff-simplified


text:
//
// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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 NUDB_DETAIL_MUTEX_HPP
#define NUDB_DETAIL_MUTEX_HPP

#include <boost/thread/lock_types.hpp>
#include <boost/thread/shared_mutex.hpp>

namespace nudb {
namespace detail {

using shared_lock_type =
    boost::shared_lock<boost::shared_mutex>;

using unique_lock_type =
    boost::unique_lock<boost::shared_mutex>;

} // detail
} // nudb

#endif


text:
//
//  Copyright (C) 2018-2021 Susan H. Leung and other RDKit contributors
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#include "AcidBaseCatalogUtils.h"
#include <RDGeneral/BadFileException.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
#include <fstream>
#include <string>

namespace RDKit {
namespace {

std::pair<ROMol*, ROMol*>* getPair(const std::string& name,
                                   const std::string& acid_smarts,
                                   const std::string& base_smarts) {
  ROMol* acid(SmartsToMol(acid_smarts));
  if (!acid) {
    throw ValueErrorException("Failed parsing acid SMARTS: " + acid_smarts);
  }
  ROMol* base(SmartsToMol(base_smarts));
  if (!base) {
    delete acid;
    throw ValueErrorException("Failed parsing base SMARTS: " + base_smarts);
  }

  acid->setProp(common_properties::_Name, name);
  base->setProp(common_properties::_Name, name);

  return new std::pair<ROMol*, ROMol*>(acid, base);
}
std::pair<ROMol*, ROMol*>* getPair(std::string tmpStr) {
  // Remove whitespace
  boost::trim(tmpStr);

  if (tmpStr.length() == 0 || tmpStr.substr(0, 2) == "//") {
    // empty or comment line
    return nullptr;
  }

  boost::char_separator<char> tabSep("\t");
  tokenizer tokens(tmpStr, tabSep);
  tokenizer::iterator token = tokens.begin();

  // name of the functional groups
  std::string name = *token;
  boost::erase_all(name, " ");
  ++token;

  // grab the acid:
  std::string acid_smarts = *token;
  boost::erase_all(acid_smarts, " ");
  ++token;

  // grab the base:
  std::string base_smarts = *token;
  boost::erase_all(base_smarts, " ");
  ++token;

  return getPair(name, acid_smarts, base_smarts);
}
}  // namespace

namespace MolStandardize {

std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> readPairs(std::string fileName) {
  std::ifstream inStream(fileName.c_str());
  if ((!inStream) || (inStream.bad())) {
    std::ostringstream errout;
    errout << "Bad input file " << fileName;
    throw BadFileException(errout.str());
  }
  std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> mol_pairs =
      readPairs(inStream);
  return mol_pairs;
}

std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> readPairs(std::istream& inStream,
                                                         int nToRead) {
  std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> pairs;
  pairs.clear();
  if (inStream.bad()) {
    throw BadFileException("Bad stream contents.");
  }
  const int MAX_LINE_LEN = 512;
  char inLine[MAX_LINE_LEN];
  std::string tmpstr;
  int nRead = 0;
  while (!inStream.eof() && !inStream.fail() &&
         (nToRead < 0 || nRead < nToRead)) {
    inStream.getline(inLine, MAX_LINE_LEN, '\n');
    tmpstr = inLine;
    // parse the molpair on this line (if there is one)
    std::shared_ptr<std::pair<ROMol*, ROMol*>> mol_pair(getPair(tmpstr));
    if (mol_pair != nullptr) {
      pairs.emplace_back(ROMOL_SPTR(mol_pair->first),
                         ROMOL_SPTR(mol_pair->second));
      nRead++;
    }
  }
  return pairs;
}

std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> readPairs(
    const std::vector<std::tuple<std::string, std::string, std::string>>&
        data) {
  std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> pairs;
  for (const auto& tpl : data) {
    std::shared_ptr<std::pair<ROMol*, ROMol*>> mol_pair(
        getPair(std::get<0>(tpl), std::get<1>(tpl), std::get<2>(tpl)));
    pairs.emplace_back(ROMOL_SPTR(mol_pair->first),
                       ROMOL_SPTR(mol_pair->second));
  }
  return pairs;
}
}  // namespace MolStandardize
}  // namespace RDKit

max_stars_repo_name: kazuyaujihara/rdkit

max_issues_repo_name: kazuyaujihara/rdkit

max_forks_repo_name: bp-kelley/rdkit


text:
// Copyright 2021 Apex.AI, Inc.
//
// 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 <gnss_conversion_nodes/gnss_conversion_node.hpp>

#include <common/types.hpp>
#include <rclcpp_components/register_node_macro.hpp>
#include <sensor_msgs/msg/nav_sat_fix.hpp>

#include <Eigen/Core>

#include <limits>
#include <string>
#include <vector>

namespace
{
static constexpr auto kDefaultHistorySize = 10;
static constexpr auto kHistorySizeTag = "history_size";
static constexpr auto kOutputTopic = "ecef_position";
static constexpr auto kGnssFixInputTopic = "wgs84_position";
static constexpr auto kFrameIdTag = "output_frame_id";
static constexpr auto kChildFrameIdTag = "child_frame_id";
static constexpr auto kDefaultChildFrameIdTag = "base_link";
static constexpr auto kOverrideCovarianceTag = "override_variances";
static constexpr auto kDefaultFrameId = "earth";
static constexpr auto kDefaultLoggingInterval = 1000;  // Milliseconds.

using autoware_auto_msgs::msg::RelativePositionWithCovarianceStamped;

}  // namespace

namespace autoware
{
namespace gnss_conversion_nodes
{

GnssConversionNode::GnssConversionNode(const rclcpp::NodeOptions & options)
:  Node("gnss_conversion_nodes", options),
  m_wgs84_to_ecef_convertor{
    GeographicLib::Constants::WGS84_a(),
    GeographicLib::Constants::WGS84_f()}
{
  const auto history_size{declare_parameter(kHistorySizeTag, kDefaultHistorySize)};
  if (history_size <= 0) {throw std::domain_error("History size must be positive.");}
  m_frame_id = declare_parameter(kFrameIdTag, kDefaultFrameId);
  m_child_frame_id = declare_parameter(kChildFrameIdTag, kDefaultChildFrameIdTag);
  const auto qos = rclcpp::QoS{static_cast<std::size_t>(history_size)};

  m_publisher = create_publisher<RelativePositionWithCovarianceStamped>(kOutputTopic, qos);
  m_gnss_nav_fix_subscription = create_subscription<sensor_msgs::msg::NavSatFix>(
    kGnssFixInputTopic, qos,
    std::bind(&GnssConversionNode::nav_sat_fix_callback, this, std::placeholders::_1));
  m_override_variances_diagonal =
    declare_parameter(kOverrideCovarianceTag, std::vector<common::types::float64_t>{});
  if (m_override_variances_diagonal.size() != 3UL) {
    throw std::runtime_error("Override covariance must have exactly 3 entries.");
  }
}

void GnssConversionNode::nav_sat_fix_callback(
  const sensor_msgs::msg::NavSatFix::ConstSharedPtr msg) const
{
  if (msg->status.status == msg->status.STATUS_NO_FIX) {
    RCLCPP_WARN_THROTTLE(
      get_logger(),
      m_steady_clock,
      kDefaultLoggingInterval,
      "GNSS has no fix, so nothing is published.");
    return;
  }
  RelativePositionWithCovarianceStamped out_msg{};
  out_msg.header.stamp = msg->header.stamp;
  out_msg.header.frame_id = m_frame_id;
  out_msg.child_frame_id = m_child_frame_id;
  m_wgs84_to_ecef_convertor.Forward(
    msg->latitude, msg->longitude, msg->altitude,
    out_msg.position.x, out_msg.position.y, out_msg.position.z);
  if (!m_override_variances_diagonal.empty()) {
    const Eigen::Vector3d variances_diagonal{
      Eigen::Map<const Eigen::Vector3d>{m_override_variances_diagonal.data()}};
    const auto override_covariance = variances_diagonal.array().square().matrix().asDiagonal();
    out_msg.covariance.resize(static_cast<std::size_t>(override_covariance.size()));
    auto pose_covariance = Eigen::Map<Eigen::Matrix3d>{&out_msg.covariance.front()};
    pose_covariance.topLeftCorner(
      override_covariance.rows(), override_covariance.cols()) = override_covariance;
  }
  m_publisher->publish(out_msg);
}

}  // namespace gnss_conversion_nodes
}  // namespace autoware

RCLCPP_COMPONENTS_REGISTER_NODE(autoware::gnss_conversion_nodes::GnssConversionNode)


text:
/*
 * open_ggcm_test.cpp
 *
 *  Created on: Sep 23, 2009
 *      Author: dberrios
 */

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <ccmc/OpenGGCM.h>
#include <ccmc/Interpolator.h>
#include <string>

using namespace std;
using namespace ccmc;

/**
 * open_ggcm <inputfile> variable x y z
 */
int main (int argc, char * argv[])
{
	if (argc != 6)
	{
		cout << "open_ggcm <inputfile> variable x y z" << endl;
		exit(1);
	}

	string filename = argv[1];
	string variable = argv[2];
	float x = boost::lexical_cast<float>(argv[3]);
	float y = boost::lexical_cast<float>(argv[4]);
	float z = boost::lexical_cast<float>(argv[5]);
	OpenGGCM open_ggcm;
	open_ggcm.open(filename);
	open_ggcm.loadVariable(variable);

	Interpolator * interpolator = open_ggcm.createNewInterpolator();
	float value = interpolator->interpolate(variable, x, y, z);
	delete interpolator;

	string units = open_ggcm.getNativeUnit(variable);

	cout << "interpolated value: " << value << " " << units << endl;
	open_ggcm.close();

}

max_stars_repo_name: alexanderbock/Kameleon-Converter

max_issues_repo_name: alexanderbock/Kameleon-Converter

max_forks_repo_name: alexanderbock/Kameleon-Converter


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 *************************************************************/

// MARKER(update_precomp.py): Generated on 2006-07-11 15:52:42.937361

#ifdef PRECOMPILED_HEADERS
#include <sal/config.h>
#include "scitems.hxx"

#include <algorithm>
#include <assert.h>
#include <deque>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <iosfwd>
#include <limits.h>
#include <limits>
#include <list>
#include <math.h>
#include <memory>
#include <new>
#include <cfloat>

#include <boost/bind.hpp>

#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b3dpolygon.hxx>
#include <basegfx/polygon/b3dpolypolygon.hxx>
#include <com/sun/star/uno/Any.h>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Type.hxx>
#include <cppu/macros.hxx>
#include <cppuhelper/weakref.hxx>
#include <cstddef>
#include <cwchar>
#include <float.h>
#include <functional>
#include <com/sun/star/awt/Point.hdl>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/awt/Size.hdl>
#include <com/sun/star/awt/Size.hpp>
#include <com/sun/star/beans/PropertyVetoException.hdl>
#include <com/sun/star/beans/PropertyVetoException.hpp>
#include <com/sun/star/container/ElementExistException.hdl>
#include <com/sun/star/container/ElementExistException.hpp>
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <com/sun/star/container/XElementAccess.hdl>
#include <com/sun/star/container/XElementAccess.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/datatransfer/DataFlavor.hdl>
#include <com/sun/star/datatransfer/dnd/DragGestureEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DragSourceDragEvent.hdl>
#include <com/sun/star/datatransfer/dnd/DragSourceDragEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DragSourceDropEvent.hdl>
#include <com/sun/star/datatransfer/dnd/DragSourceEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEnterEvent.hdl>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEnterEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEvent.hdl>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDropEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetEvent.hdl>
#include <com/sun/star/datatransfer/dnd/DropTargetEvent.hpp>
#include <com/sun/star/datatransfer/dnd/XDragGestureListener.hdl>
#include <com/sun/star/datatransfer/dnd/XDragGestureListener.hpp>
#include <com/sun/star/datatransfer/dnd/XDragSource.hdl>
#include <com/sun/star/datatransfer/dnd/XDragSource.hpp>
#include <com/sun/star/datatransfer/dnd/XDragSourceContext.hdl>
#include <com/sun/star/datatransfer/dnd/XDragSourceContext.hpp>
#include <com/sun/star/datatransfer/dnd/XDragSourceListener.hdl>
#include <com/sun/star/datatransfer/dnd/XDragSourceListener.hpp>
#include <com/sun/star/datatransfer/dnd/XDropTargetDragContext.hpp>
#include <com/sun/star/datatransfer/dnd/XDropTargetListener.hdl>
#include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp>
#include <com/sun/star/datatransfer/UnsupportedFlavorException.hdl>
#include <com/sun/star/datatransfer/XTransferable.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/embed/InvalidStorageException.hpp>
#include <com/sun/star/embed/StorageWrappedTargetException.hdl>
#include <com/sun/star/embed/StorageWrappedTargetException.hpp>
#include <com/sun/star/embed/XStorage.hdl>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/io/BufferSizeExceededException.hpp>
#include <com/sun/star/io/IOException.hdl>
#include <com/sun/star/io/NotConnectedException.hdl>
#include <com/sun/star/io/NotConnectedException.hpp>
#include <com/sun/star/io/XInputStream.hdl>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hdl>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XStream.hdl>
#include <com/sun/star/lang/EventObject.hdl>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hdl>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XEventListener.hpp>
#include <com/sun/star/packages/NoEncryptionException.hdl>
#include <com/sun/star/packages/NoEncryptionException.hpp>
#include <com/sun/star/packages/WrongPasswordException.hdl>
#include <com/sun/star/packages/WrongPasswordException.hpp>
#include <com/sun/star/uno/Exception.hdl>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/uno/RuntimeException.hdl>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/XAdapter.hdl>
#include <com/sun/star/uno/XAdapter.hpp>
#include <com/sun/star/uno/XInterface.hdl>
#include <com/sun/star/uno/XReference.hdl>
#include <com/sun/star/uno/XReference.hpp>
#include <com/sun/star/uno/XWeak.hpp>
#include <osl/endian.h>
#include <osl/interlck.h>
#include <osl/mutex.hxx>
#include <rtl/alloc.h>
#include <rtl/random.h>
#include <rtl/string.h>
#include <rtl/ustrbuf.h>
#include <rtl/ustring.h>
#include <sal/mathconf.h>
#include <sal/types.h>
#include <sax/fshelper.hxx>
#include <sot/exchange.hxx>
#include <sot/factory.hxx>
#include <sot/storage.hxx>
#include <svl/brdcst.hxx>
#include <svl/cenumitm.hxx>
#include <svl/cintitem.hxx>
#include <unotools/fltrcfg.hxx>
#include <svl/intitem.hxx>
#include <svl/listener.hxx>
#include <svl/lstner.hxx>
#include <unotools/pathoptions.hxx>
#include <svl/solar.hrc>
#include <unotools/useroptions.hxx>
#include <editeng/editobj.hxx>
#include <editeng/eeitem.hxx>
#include <svx/fmglob.hxx>
#include <editeng/outlobj.hxx>
#include <svx/sdangitm.hxx>
#include <svx/sderitm.hxx>
#include <svx/sdmetitm.hxx>
#include <svx/sdooitm.hxx>
#include <svx/sdprcitm.hxx>
#include <svx/sdrmasterpagedescriptor.hxx>
#include <svx/sdrpageuser.hxx>
#include <svx/sdtaitm.hxx>
#include <svx/svdglue.hxx>
#include <svx/svdlayer.hxx>
#include <svx/svdoattr.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdpool.hxx>
#include <svx/svdtrans.hxx>
#include <svx/svdtypes.hxx>
#include <svx/unoapi.hxx>
#include <svx/volume3d.hxx>
#include <svx/xcolit.hxx>
#include <svx/xenum.hxx>
#include <svx/xfillit0.hxx>
#include <svx/xflasit.hxx>
#include <svx/xlineit0.hxx>
#include <svx/xlnasit.hxx>
#include <svx/xtextit0.hxx>
#include <tools/date.hxx>
#include <tools/datetime.hxx>
#include <tools/errcode.hxx>
#include <tools/errinf.hxx>
#include <tools/gen.hxx>
#include <tools/globname.hxx>
#include <tools/list.hxx>
#include <tools/rc.hxx>
#include <tools/rtti.hxx>
#include <tools/solar.h>
#include <tools/string.hxx>
#include <tools/toolsdllapi.h>
#include <tools/weakbase.h>
#include <tools/weakbase.hxx>
#include <typeinfo>
#include <typelib/typeclass.h>
#include <typelib/typedescription.h>
#include <typelib/uik.h>
#include <uno/any2.h>
#include <uno/lbnames.h>
#include <uno/sequence2.h>
#include <unotools/streamwrap.hxx>
#include <unotools/ucbstreamhelper.hxx>

#include <vcl/apptypes.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/dllapi.h>
#include <vcl/dndhelp.hxx>
#include <vcl/edit.hxx>
#include <vcl/field.hxx>
#include <tools/fldunit.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/inputctx.hxx>
#include <vcl/jobset.hxx>
#include <vcl/mapmod.hxx>
#include <vcl/menu.hxx>
#include <vcl/pointr.hxx>
#include <vcl/print.hxx>
#include <vcl/prntypes.hxx>
#include <vcl/ptrstyle.hxx>
#include <vcl/region.hxx>
#include <vcl/salnativewidgets.hxx>
#include <vcl/spinfld.hxx>
#include <vcl/sv.h>
#include <vcl/svapp.hxx>
#include <vcl/vclevent.hxx>
#include <vcl/window.hxx>
#include <tools/wintypes.hxx>
#include <vos/macros.hxx>
#include <vos/object.hxx>
#include <vos/types.hxx>
#include <wchar.h>

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS
  @copyright 2016 J.T. Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_SIGN_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_SIGN_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-ieee
    Function object implementing sign capabilities

    Returns the sign of x. i.e. -1, 0 or 1, according
    x is less than @ref Zero, @ref Zero or greater than @ref Zero.

    For floating,  the sign of @ref Nan is @ref Nan

    @par Semantic:

    @code
    T r = sign(x);
    @endcode

    is similar to:

    @code
    T r = (x > 0) ? T(1) : ((x < 0) ? T(-1) : ((x == 0) ? 0 : Nan<T>()));
    @endcode

    @see signnz, is_negative, is_positive,  bitofsign

  **/
  const boost::dispatch::functor<tag::sign_> sign = {};
} }
#endif

#include <boost/simd/function/scalar/sign.hpp>
#include <boost/simd/function/simd/sign.hpp>

#endif