<commit_before>#include <ROOT/RDataFrame.hxx>
#include <ROOT/RMakeUnique.hxx>
#include <ROOT/RSqliteDS.hxx>
#include <ROOT/TSeq.hxx>

#include <TSystem.h>

#include <gtest/gtest.h>

#include <algorithm>
#include <memory>

using namespace ROOT::RDF;

constexpr auto fileName0 = "RSqliteDS_test.sqlite";
constexpr auto query0 = "SELECT * FROM test";
constexpr auto query1 = "SELECT fint + 1, freal/1.0 as fmyreal, NULL, 'X', fblob FROM test";
constexpr auto query2 = "SELECT fint, freal, fint FROM test";
constexpr auto query3 = "SELECT fint, freal, ftext, fblob FROM test";
constexpr auto epsilon = 0.001;

TEST(RSqliteDS, Basics)
{
   auto rdf = MakeSqliteDataFrame(fileName0, query0);
   EXPECT_EQ(1, *rdf.Min("fint"));
   EXPECT_EQ(2, *rdf.Max("fint"));

   EXPECT_THROW(MakeSqliteDataFrame(fileName0, ""), std::runtime_error);
   EXPECT_THROW(MakeSqliteDataFrame("", query0), std::runtime_error);
}

TEST(RSqliteDS, Snapshot)
{
   // Use query 3 to avoid storing a void * in the root file
   auto rdf = MakeSqliteDataFrame(fileName0, query3);

   constexpr auto fname = "datasource_sqlite_snapshot.root";
   auto rdf_root = rdf.Snapshot("tree", fname);

   auto fintVec = rdf_root->Take<Long64_t>("fint");
   auto frealVec = rdf_root->Take<double>("freal");
   auto ftextVec = rdf_root->Take<std::string>("ftext");
   auto fblobVec = rdf_root->Take<std::vector<unsigned char>>("fblob");

   EXPECT_EQ(2U, fintVec->size());
   EXPECT_EQ(2U, frealVec->size());
   EXPECT_EQ(2U, ftextVec->size());
   EXPECT_EQ(2U, fblobVec->size());

   EXPECT_EQ(1, (*fintVec)[0]);
   EXPECT_EQ(2, (*fintVec)[1]);
   EXPECT_NEAR(1.0, (*frealVec)[0], epsilon);
   EXPECT_NEAR(2.0, (*frealVec)[1], epsilon);
   EXPECT_EQ("1", (*ftextVec)[0]);
   EXPECT_EQ("2", (*ftextVec)[1]);
   EXPECT_EQ(1U, (*fblobVec)[0].size());
   EXPECT_EQ('1', (*fblobVec)[0][0]);
   EXPECT_EQ(1U, (*fblobVec)[1].size());
   EXPECT_EQ('2', (*fblobVec)[1][0]);

   gSystem->Unlink(fname);
}

TEST(RSqliteDS, ColTypeNames)
{
   RSqliteDS rds(fileName0, query0);

   auto colNames = rds.GetColumnNames();
   ASSERT_EQ(5U, colNames.size());
   std::sort(colNames.begin(), colNames.end());
   EXPECT_EQ("fblob", colNames[0]);
   EXPECT_EQ("fint", colNames[1]);
   EXPECT_EQ("fnull", colNames[2]);
   EXPECT_EQ("freal", colNames[3]);
   EXPECT_EQ("ftext", colNames[4]);

   EXPECT_TRUE(rds.HasColumn("fint"));
   EXPECT_TRUE(rds.HasColumn("freal"));
   EXPECT_TRUE(rds.HasColumn("ftext"));
   EXPECT_TRUE(rds.HasColumn("fblob"));
   EXPECT_TRUE(rds.HasColumn("fnull"));
   EXPECT_FALSE(rds.HasColumn("foo"));

   EXPECT_EQ("Long64_t", rds.GetTypeName("fint"));
   EXPECT_EQ("double", rds.GetTypeName("freal"));
   EXPECT_EQ("std::string", rds.GetTypeName("ftext"));
   EXPECT_EQ("std::vector<unsigned char>", rds.GetTypeName("fblob"));
   EXPECT_EQ("void *", rds.GetTypeName("fnull"));
   EXPECT_THROW(rds.GetTypeName("foo"), std::runtime_error);
}

TEST(RSqliteDS, ExprTypeNames)
{
   RSqliteDS rds(fileName0, query1);

   EXPECT_EQ("Long64_t", rds.GetTypeName("fint + 1"));
   EXPECT_EQ("double", rds.GetTypeName("fmyreal"));
   EXPECT_EQ("void *", rds.GetTypeName("NULL"));
   EXPECT_EQ("std::string", rds.GetTypeName("'X'"));
   EXPECT_EQ("std::vector<unsigned char>", rds.GetTypeName("fblob"));
   EXPECT_THROW(rds.GetTypeName("foo"), std::runtime_error);
}

TEST(RSqliteDS, DuplicateColumns)
{
   RSqliteDS rds(fileName0, query2);
   rds.SetNSlots(1);

   EXPECT_EQ("Long64_t", rds.GetTypeName("fint"));
   EXPECT_EQ("double", rds.GetTypeName("freal"));
   auto vals = rds.GetColumnReaders<Long64_t>("fint");
   rds.Initialise();
   auto ranges = rds.GetEntryRanges();
   ASSERT_EQ(1U, ranges.size());
   EXPECT_TRUE(rds.SetEntry(0, ranges[0].first));
   auto val = **vals[0];
   EXPECT_EQ(1, val);
}

TEST(RSqliteDS, ColumnReaders)
{
   RSqliteDS rds(fileName0, query0);
   const auto nSlots = 2U;
   rds.SetNSlots(nSlots);
   auto vals = rds.GetColumnReaders<Long64_t>("fint");
   rds.Initialise();
   auto ranges = rds.GetEntryRanges();
   EXPECT_EQ(1U, ranges.size());
   for (auto i : ROOT::TSeq<unsigned>(0, nSlots)) {
      EXPECT_TRUE(rds.SetEntry(i, ranges[0].first));
      auto val = **vals[i];
      EXPECT_EQ(1, val);
   }

   EXPECT_THROW(rds.GetColumnReaders<double>("fint"), std::runtime_error);
}

TEST(RSqliteDS, GetEntryRanges)
{
   RSqliteDS rds(fileName0, query0);
   rds.Initialise();
   auto ranges = rds.GetEntryRanges();
   ASSERT_EQ(1U, ranges.size());
   EXPECT_EQ(0U, ranges[0].first);
   EXPECT_EQ(1U, ranges[0].second);
   ranges = rds.GetEntryRanges();
   ASSERT_EQ(1U, ranges.size());
   EXPECT_EQ(1U, ranges[0].first);
   EXPECT_EQ(2U, ranges[0].second);
   ranges = rds.GetEntryRanges();
   EXPECT_EQ(0U, ranges.size());

   // New event loop
   rds.Initialise();
   ranges = rds.GetEntryRanges();
   EXPECT_EQ(1U, ranges.size());
   EXPECT_EQ(0U, ranges[0].first);
   EXPECT_EQ(1U, ranges[0].second);
}

TEST(RSqliteDS, SetEntry)
{
   RSqliteDS rds(fileName0, query0);
   rds.SetNSlots(1);
   auto vint = rds.GetColumnReaders<Long64_t>("fint");
   auto vreal = rds.GetColumnReaders<double>("freal");
   auto vtext = rds.GetColumnReaders<std::string>("ftext");
   auto vblob = rds.GetColumnReaders<std::vector<unsigned char>>("fblob");
   auto vnull = rds.GetColumnReaders<void *>("fnull");

   rds.Initialise();

   rds.GetEntryRanges();
   EXPECT_TRUE(rds.SetEntry(0, 0));
   EXPECT_EQ(1, **vint[0]);
   EXPECT_NEAR(1.0, **vreal[0], epsilon);
   EXPECT_EQ("1", **vtext[0]);
   EXPECT_EQ(1U, (**vblob[0]).size());
   EXPECT_EQ('1', (**vblob[0])[0]);
   EXPECT_EQ(nullptr, **vnull[0]);

   rds.GetEntryRanges();
   EXPECT_TRUE(rds.SetEntry(0, 1));
   EXPECT_EQ(2, **vint[0]);
   EXPECT_NEAR(2.0, **vreal[0], epsilon);
   EXPECT_EQ("2", **vtext[0]);
   EXPECT_EQ(1U, (**vblob[0]).size());
   EXPECT_EQ('2', (**vblob[0])[0]);
   EXPECT_EQ(nullptr, **vnull[0]);
}

#ifdef R__USE_IMT

TEST(RSqliteDS, IMT)
{
   using Blob_t = std::vector<unsigned char>;
   const auto nSlots = 4U;
   ROOT::EnableImplicitMT(nSlots);

   auto rdf = MakeSqliteDataFrame(fileName0, query0);
   EXPECT_EQ(3, *rdf.Sum("fint"));
   EXPECT_NEAR(3.0, *rdf.Sum("freal"), epsilon);
   auto sum_text = *rdf.Reduce([](std::string a, std::string b) { return a + b; }, "ftext");
   std::sort(sum_text.begin(), sum_text.end());
   EXPECT_EQ("12", sum_text);
   auto sum_blob = *rdf.Reduce(
      [](Blob_t a, Blob_t b) {
         a.insert(a.end(), b.begin(), b.end());
         return a;
      },
      "fblob");
   std::sort(sum_blob.begin(), sum_blob.end());
   ASSERT_EQ(2U, sum_blob.size());
   EXPECT_EQ('1', sum_blob[0]);
   EXPECT_EQ('2', sum_blob[1]);
}

#endif // R__USE_IMT
<commit_msg>[DF] add unit test for reading remote files in sqlite ds<commit_after>#include <ROOT/RConfig.h>
#include <ROOT/RDataFrame.hxx>
#include <ROOT/RMakeUnique.hxx>
#include <ROOT/RSqliteDS.hxx>
#include <ROOT/TSeq.hxx>

#include <TSystem.h>

#include <gtest/gtest.h>

#include <algorithm>
#include <memory>

using namespace ROOT::RDF;

constexpr auto fileName0 = "RSqliteDS_test.sqlite";
constexpr auto url0 = "https://root.cern.ch/files/RSqliteDS_test.sqlite";
constexpr auto url1 = "https://root.cern.ch/files/RSqliteDS_test.sqlite.404";
constexpr auto query0 = "SELECT * FROM test";
constexpr auto query1 = "SELECT fint + 1, freal/1.0 as fmyreal, NULL, 'X', fblob FROM test";
constexpr auto query2 = "SELECT fint, freal, fint FROM test";
constexpr auto query3 = "SELECT fint, freal, ftext, fblob FROM test";
constexpr auto epsilon = 0.001;

TEST(RSqliteDS, Basics)
{
   auto rdf = MakeSqliteDataFrame(fileName0, query0);
   EXPECT_EQ(1, *rdf.Min("fint"));
   EXPECT_EQ(2, *rdf.Max("fint"));

   EXPECT_THROW(MakeSqliteDataFrame(fileName0, ""), std::runtime_error);
   EXPECT_THROW(MakeSqliteDataFrame("", query0), std::runtime_error);
}

TEST(RSqliteDS, Snapshot)
{
   // Use query 3 to avoid storing a void * in the root file
   auto rdf = MakeSqliteDataFrame(fileName0, query3);

   constexpr auto fname = "datasource_sqlite_snapshot.root";
   auto rdf_root = rdf.Snapshot("tree", fname);

   auto fintVec = rdf_root->Take<Long64_t>("fint");
   auto frealVec = rdf_root->Take<double>("freal");
   auto ftextVec = rdf_root->Take<std::string>("ftext");
   auto fblobVec = rdf_root->Take<std::vector<unsigned char>>("fblob");

   EXPECT_EQ(2U, fintVec->size());
   EXPECT_EQ(2U, frealVec->size());
   EXPECT_EQ(2U, ftextVec->size());
   EXPECT_EQ(2U, fblobVec->size());

   EXPECT_EQ(1, (*fintVec)[0]);
   EXPECT_EQ(2, (*fintVec)[1]);
   EXPECT_NEAR(1.0, (*frealVec)[0], epsilon);
   EXPECT_NEAR(2.0, (*frealVec)[1], epsilon);
   EXPECT_EQ("1", (*ftextVec)[0]);
   EXPECT_EQ("2", (*ftextVec)[1]);
   EXPECT_EQ(1U, (*fblobVec)[0].size());
   EXPECT_EQ('1', (*fblobVec)[0][0]);
   EXPECT_EQ(1U, (*fblobVec)[1].size());
   EXPECT_EQ('2', (*fblobVec)[1][0]);

   gSystem->Unlink(fname);
}

TEST(RSqliteDS, ColTypeNames)
{
   RSqliteDS rds(fileName0, query0);

   auto colNames = rds.GetColumnNames();
   ASSERT_EQ(5U, colNames.size());
   std::sort(colNames.begin(), colNames.end());
   EXPECT_EQ("fblob", colNames[0]);
   EXPECT_EQ("fint", colNames[1]);
   EXPECT_EQ("fnull", colNames[2]);
   EXPECT_EQ("freal", colNames[3]);
   EXPECT_EQ("ftext", colNames[4]);

   EXPECT_TRUE(rds.HasColumn("fint"));
   EXPECT_TRUE(rds.HasColumn("freal"));
   EXPECT_TRUE(rds.HasColumn("ftext"));
   EXPECT_TRUE(rds.HasColumn("fblob"));
   EXPECT_TRUE(rds.HasColumn("fnull"));
   EXPECT_FALSE(rds.HasColumn("foo"));

   EXPECT_EQ("Long64_t", rds.GetTypeName("fint"));
   EXPECT_EQ("double", rds.GetTypeName("freal"));
   EXPECT_EQ("std::string", rds.GetTypeName("ftext"));
   EXPECT_EQ("std::vector<unsigned char>", rds.GetTypeName("fblob"));
   EXPECT_EQ("void *", rds.GetTypeName("fnull"));
   EXPECT_THROW(rds.GetTypeName("foo"), std::runtime_error);
}

TEST(RSqliteDS, ExprTypeNames)
{
   RSqliteDS rds(fileName0, query1);

   EXPECT_EQ("Long64_t", rds.GetTypeName("fint + 1"));
   EXPECT_EQ("double", rds.GetTypeName("fmyreal"));
   EXPECT_EQ("void *", rds.GetTypeName("NULL"));
   EXPECT_EQ("std::string", rds.GetTypeName("'X'"));
   EXPECT_EQ("std::vector<unsigned char>", rds.GetTypeName("fblob"));
   EXPECT_THROW(rds.GetTypeName("foo"), std::runtime_error);
}

TEST(RSqliteDS, DuplicateColumns)
{
   RSqliteDS rds(fileName0, query2);
   rds.SetNSlots(1);

   EXPECT_EQ("Long64_t", rds.GetTypeName("fint"));
   EXPECT_EQ("double", rds.GetTypeName("freal"));
   auto vals = rds.GetColumnReaders<Long64_t>("fint");
   rds.Initialise();
   auto ranges = rds.GetEntryRanges();
   ASSERT_EQ(1U, ranges.size());
   EXPECT_TRUE(rds.SetEntry(0, ranges[0].first));
   auto val = **vals[0];
   EXPECT_EQ(1, val);
}

TEST(RSqliteDS, ColumnReaders)
{
   RSqliteDS rds(fileName0, query0);
   const auto nSlots = 2U;
   rds.SetNSlots(nSlots);
   auto vals = rds.GetColumnReaders<Long64_t>("fint");
   rds.Initialise();
   auto ranges = rds.GetEntryRanges();
   EXPECT_EQ(1U, ranges.size());
   for (auto i : ROOT::TSeq<unsigned>(0, nSlots)) {
      EXPECT_TRUE(rds.SetEntry(i, ranges[0].first));
      auto val = **vals[i];
      EXPECT_EQ(1, val);
   }

   EXPECT_THROW(rds.GetColumnReaders<double>("fint"), std::runtime_error);
}

TEST(RSqliteDS, GetEntryRanges)
{
   RSqliteDS rds(fileName0, query0);
   rds.Initialise();
   auto ranges = rds.GetEntryRanges();
   ASSERT_EQ(1U, ranges.size());
   EXPECT_EQ(0U, ranges[0].first);
   EXPECT_EQ(1U, ranges[0].second);
   ranges = rds.GetEntryRanges();
   ASSERT_EQ(1U, ranges.size());
   EXPECT_EQ(1U, ranges[0].first);
   EXPECT_EQ(2U, ranges[0].second);
   ranges = rds.GetEntryRanges();
   EXPECT_EQ(0U, ranges.size());

   // New event loop
   rds.Initialise();
   ranges = rds.GetEntryRanges();
   EXPECT_EQ(1U, ranges.size());
   EXPECT_EQ(0U, ranges[0].first);
   EXPECT_EQ(1U, ranges[0].second);
}

TEST(RSqliteDS, SetEntry)
{
   RSqliteDS rds(fileName0, query0);
   rds.SetNSlots(1);
   auto vint = rds.GetColumnReaders<Long64_t>("fint");
   auto vreal = rds.GetColumnReaders<double>("freal");
   auto vtext = rds.GetColumnReaders<std::string>("ftext");
   auto vblob = rds.GetColumnReaders<std::vector<unsigned char>>("fblob");
   auto vnull = rds.GetColumnReaders<void *>("fnull");

   rds.Initialise();

   rds.GetEntryRanges();
   EXPECT_TRUE(rds.SetEntry(0, 0));
   EXPECT_EQ(1, **vint[0]);
   EXPECT_NEAR(1.0, **vreal[0], epsilon);
   EXPECT_EQ("1", **vtext[0]);
   EXPECT_EQ(1U, (**vblob[0]).size());
   EXPECT_EQ('1', (**vblob[0])[0]);
   EXPECT_EQ(nullptr, **vnull[0]);

   rds.GetEntryRanges();
   EXPECT_TRUE(rds.SetEntry(0, 1));
   EXPECT_EQ(2, **vint[0]);
   EXPECT_NEAR(2.0, **vreal[0], epsilon);
   EXPECT_EQ("2", **vtext[0]);
   EXPECT_EQ(1U, (**vblob[0]).size());
   EXPECT_EQ('2', (**vblob[0])[0]);
   EXPECT_EQ(nullptr, **vnull[0]);
}

#ifdef R__USE_IMT

TEST(RSqliteDS, IMT)
{
   using Blob_t = std::vector<unsigned char>;
   const auto nSlots = 4U;
   ROOT::EnableImplicitMT(nSlots);

   auto rdf = MakeSqliteDataFrame(fileName0, query0);
   EXPECT_EQ(3, *rdf.Sum("fint"));
   EXPECT_NEAR(3.0, *rdf.Sum("freal"), epsilon);
   auto sum_text = *rdf.Reduce([](std::string a, std::string b) { return a + b; }, "ftext");
   std::sort(sum_text.begin(), sum_text.end());
   EXPECT_EQ("12", sum_text);
   auto sum_blob = *rdf.Reduce(
      [](Blob_t a, Blob_t b) {
         a.insert(a.end(), b.begin(), b.end());
         return a;
      },
      "fblob");
   std::sort(sum_blob.begin(), sum_blob.end());

   ROOT::DisableImplicitMT();

   ASSERT_EQ(2U, sum_blob.size());
   EXPECT_EQ('1', sum_blob[0]);
   EXPECT_EQ('2', sum_blob[1]);
}

#endif // R__USE_IMT

TEST(RSqliteDS, Davix)
{
#ifdef R__HAS_DAVIX
   auto rdf = MakeSqliteDataFrame(url0, query0);
   EXPECT_EQ(1, *rdf.Min("fint"));
   EXPECT_EQ(2, *rdf.Max("fint"));

   EXPECT_THROW(MakeSqliteDataFrame(url1, query0), std::runtime_error);
#else
   EXPECT_THROW(MakeSqliteDataFrame(url0, query0), std::runtime_error);
#endif
}
<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Rainer Gericke
// =============================================================================
//
// LMTV 2.5t chassis subsystem.
//
// =============================================================================

#include "chrono/assets/ChTriangleMeshShape.h"
#include "chrono/utils/ChUtilsInputOutput.h"

#include "chrono_vehicle/ChVehicleModelData.h"

#include "chrono_models/vehicle/mtv/LMTV_Chassis.h"

namespace chrono {
namespace vehicle {
namespace mtv {

// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const double LMTV_Chassis::m_mass = 3796;
// const ChVector<> LMTV_Chassis::m_inertiaXX(222.8, 944.1, 1053.5);
const ChVector<> LMTV_Chassis::m_inertiaXX(3.1721e3, 5.1645e3, 4.4865e3);
const ChVector<> LMTV_Chassis::m_inertiaXY(0, -0.4154e3, 0);
const ChVector<> LMTV_Chassis::m_COM_loc(-0.7079, 0, 0.6790);
const ChCoordsys<> LMTV_Chassis::m_driverCsys(ChVector<>(0.4, 0.7, 1.18), ChQuaternion<>(1, 0, 0, 0));

const double LMTV_Chassis::m_rear_mass = 1788.333;
const ChVector<> LMTV_Chassis::m_rear_inertiaXX(2.3677e3, 2.3766e3, 3.2246e3);
const ChVector<> LMTV_Chassis::m_rear_inertiaXY(0, -0.0915e3, 0);
const ChVector<> LMTV_Chassis::m_rear_COM_loc(-3.1765, 0, 0.8799);

const ChVector<> LMTV_Chassis::m_torsion_joint_pos(-1.748, 0, 0.466);
const double LMTV_Chassis::m_torsion_stiffness = 7085;  // 7.085;

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
LMTV_Chassis::LMTV_Chassis(const std::string& name, bool fixed, ChassisCollisionType chassis_collision_type)
    : ChTorsionChassis(name, fixed) {
    m_inertia(0, 0) = m_inertiaXX.x();
    m_inertia(1, 1) = m_inertiaXX.y();
    m_inertia(2, 2) = m_inertiaXX.z();

    m_inertia(0, 1) = m_inertiaXY.x();
    m_inertia(0, 2) = m_inertiaXY.y();
    m_inertia(1, 2) = m_inertiaXY.z();
    m_inertia(1, 0) = m_inertiaXY.x();
    m_inertia(2, 0) = m_inertiaXY.y();
    m_inertia(2, 1) = m_inertiaXY.z();

    m_rear_inertia(0, 0) = m_rear_inertiaXX.x();
    m_rear_inertia(1, 1) = m_rear_inertiaXX.y();
    m_rear_inertia(2, 2) = m_rear_inertiaXX.z();

    m_rear_inertia(0, 1) = m_rear_inertiaXY.x();
    m_rear_inertia(0, 2) = m_rear_inertiaXY.y();
    m_rear_inertia(1, 2) = m_rear_inertiaXY.z();
    m_rear_inertia(1, 0) = m_rear_inertiaXY.x();
    m_rear_inertia(2, 0) = m_rear_inertiaXY.y();
    m_rear_inertia(2, 1) = m_rear_inertiaXY.z();

    //// TODO:
    //// A more appropriate contact shape from primitives
    //// Add collision shapes for rear body

    double widthFrame = 0.905;
    double heightFrame = 0.2;
    double lx_front = 1.0 - m_torsion_joint_pos.x();
    ChVector<> frontBoxPos((1.0 + m_torsion_joint_pos.x()) / 2, 0, m_torsion_joint_pos.z());
    BoxShape boxFront(frontBoxPos, ChQuaternion<>(1, 0, 0, 0), ChVector<>(lx_front, widthFrame, heightFrame));

    double lx_rear = m_torsion_joint_pos.x() + 4.9;
    ChVector<> rearBoxPos((-4.9 + m_torsion_joint_pos.x()) / 2, 0, m_torsion_joint_pos.z());
    BoxShape boxRear(rearBoxPos, ChQuaternion<>(1, 0, 0, 0), ChVector<>(lx_rear, widthFrame, heightFrame));

    m_has_primitives = true;
    m_vis_boxes.push_back(boxFront);

    m_has_rear_primitives = true;
    m_rear_vis_boxes.push_back(boxRear);

    m_has_mesh = true;
    m_vis_mesh_file = "mtv/meshes/m1078_front.obj";

    m_has_rear_mesh = true;
    m_vis_rear_mesh_file = "mtv/meshes/m1078_rear.obj";

    m_has_collision = (chassis_collision_type != ChassisCollisionType::NONE);
    switch (chassis_collision_type) {
        case ChassisCollisionType::MESH:
            // For now, fall back to using primitive collision shapes
        case ChassisCollisionType::PRIMITIVES:
            boxFront.m_matID = 0;
            boxRear.m_matID = 0;
            m_coll_boxes.push_back(boxFront);
            break;
        default:
            break;
    }
}

void LMTV_Chassis::CreateContactMaterials(ChContactMethod contact_method) {
    // Create the contact materials.
    // In this model, we use a single material with default properties.
    MaterialInfo minfo;
    m_materials.push_back(minfo.CreateMaterial(contact_method));
}

}  // namespace mtv
}  // end namespace vehicle
}  // end namespace chrono
<commit_msg>Ajust mass and inertia data for the LMTV<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Rainer Gericke
// =============================================================================
//
// LMTV 2.5t chassis subsystem.
//
// =============================================================================

#include "chrono/assets/ChTriangleMeshShape.h"
#include "chrono/utils/ChUtilsInputOutput.h"

#include "chrono_vehicle/ChVehicleModelData.h"

#include "chrono_models/vehicle/mtv/LMTV_Chassis.h"

namespace chrono {
namespace vehicle {
namespace mtv {

// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const double LMTV_Chassis::m_mass = 3946;
// const ChVector<> LMTV_Chassis::m_inertiaXX(222.8, 944.1, 1053.5);
const ChVector<> LMTV_Chassis::m_inertiaXX(3.2282e3, 5.2323e3, 4.4980e3);
const ChVector<> LMTV_Chassis::m_inertiaXY(0, -0.4027e3, 0);
const ChVector<> LMTV_Chassis::m_COM_loc(-0.6972, 0, 0.6672);
const ChCoordsys<> LMTV_Chassis::m_driverCsys(ChVector<>(0.4, 0.7, 1.18), ChQuaternion<>(1, 0, 0, 0));

const double LMTV_Chassis::m_rear_mass = 1938.333;
const ChVector<> LMTV_Chassis::m_rear_inertiaXX(2.4461e3, 2.4605e3, 3.2300e3);
const ChVector<> LMTV_Chassis::m_rear_inertiaXY(0, -0.1055e3, 0);
const ChVector<> LMTV_Chassis::m_rear_COM_loc(-3.1919, 0, 0.8404);

const ChVector<> LMTV_Chassis::m_torsion_joint_pos(-3.1919, 0, 0.8404);
const double LMTV_Chassis::m_torsion_stiffness = 7085;  // 7.085;

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
LMTV_Chassis::LMTV_Chassis(const std::string& name, bool fixed, ChassisCollisionType chassis_collision_type)
    : ChTorsionChassis(name, fixed) {
    m_inertia(0, 0) = m_inertiaXX.x();
    m_inertia(1, 1) = m_inertiaXX.y();
    m_inertia(2, 2) = m_inertiaXX.z();

    m_inertia(0, 1) = m_inertiaXY.x();
    m_inertia(0, 2) = m_inertiaXY.y();
    m_inertia(1, 2) = m_inertiaXY.z();
    m_inertia(1, 0) = m_inertiaXY.x();
    m_inertia(2, 0) = m_inertiaXY.y();
    m_inertia(2, 1) = m_inertiaXY.z();

    m_rear_inertia(0, 0) = m_rear_inertiaXX.x();
    m_rear_inertia(1, 1) = m_rear_inertiaXX.y();
    m_rear_inertia(2, 2) = m_rear_inertiaXX.z();

    m_rear_inertia(0, 1) = m_rear_inertiaXY.x();
    m_rear_inertia(0, 2) = m_rear_inertiaXY.y();
    m_rear_inertia(1, 2) = m_rear_inertiaXY.z();
    m_rear_inertia(1, 0) = m_rear_inertiaXY.x();
    m_rear_inertia(2, 0) = m_rear_inertiaXY.y();
    m_rear_inertia(2, 1) = m_rear_inertiaXY.z();

    //// TODO:
    //// A more appropriate contact shape from primitives
    //// Add collision shapes for rear body

    double widthFrame = 0.905;
    double heightFrame = 0.2;
    double lx_front = 1.0 - m_torsion_joint_pos.x();
    ChVector<> frontBoxPos((1.0 + m_torsion_joint_pos.x()) / 2, 0, m_torsion_joint_pos.z());
    BoxShape boxFront(frontBoxPos, ChQuaternion<>(1, 0, 0, 0), ChVector<>(lx_front, widthFrame, heightFrame));

    double lx_rear = m_torsion_joint_pos.x() + 4.9;
    ChVector<> rearBoxPos((-4.9 + m_torsion_joint_pos.x()) / 2, 0, m_torsion_joint_pos.z());
    BoxShape boxRear(rearBoxPos, ChQuaternion<>(1, 0, 0, 0), ChVector<>(lx_rear, widthFrame, heightFrame));

    m_has_primitives = true;
    m_vis_boxes.push_back(boxFront);

    m_has_rear_primitives = true;
    m_rear_vis_boxes.push_back(boxRear);

    m_has_mesh = true;
    m_vis_mesh_file = "mtv/meshes/m1078_front.obj";

    m_has_rear_mesh = true;
    m_vis_rear_mesh_file = "mtv/meshes/m1078_rear.obj";

    m_has_collision = (chassis_collision_type != ChassisCollisionType::NONE);
    switch (chassis_collision_type) {
        case ChassisCollisionType::MESH:
            // For now, fall back to using primitive collision shapes
        case ChassisCollisionType::PRIMITIVES:
            boxFront.m_matID = 0;
            boxRear.m_matID = 0;
            m_coll_boxes.push_back(boxFront);
            break;
        default:
            break;
    }
}

void LMTV_Chassis::CreateContactMaterials(ChContactMethod contact_method) {
    // Create the contact materials.
    // In this model, we use a single material with default properties.
    MaterialInfo minfo;
    m_materials.push_back(minfo.CreateMaterial(contact_method));
}

}  // namespace mtv
}  // end namespace vehicle
}  // end namespace chrono
<|endoftext|>


<commit_before>/**
 * PANDA 3D SOFTWARE
 * Copyright (c) Carnegie Mellon University.  All rights reserved.
 *
 * All use of this software is subject to the terms of the revised BSD
 * license.  You should have received a copy of this license along
 * with this source code in a file named "LICENSE."
 *
 * @file inputDeviceManager.cxx
 * @author rdb
 * @date 2015-12-09
 */

#include "inputDeviceManager.h"
#include "ioKitInputDeviceManager.h"
#include "linuxInputDeviceManager.h"
#include "winInputDeviceManager.h"
#include "throw_event.h"

InputDeviceManager *InputDeviceManager::_global_ptr = nullptr;

/**
 * Initializes the input device manager by scanning which devices are currently
 * connected and setting up any platform-dependent structures necessary for
 * listening for future device connect events.
 */
InputDeviceManager::
InputDeviceManager() : _lock("InputDeviceManager") {
}

/**
 * Creates the global input manager.
 */
void InputDeviceManager::
make_global_ptr() {
#ifdef _WIN32
  _global_ptr = new WinInputDeviceManager;
#elif defined(__APPLE__)
  _global_ptr = new IOKitInputDeviceManager;
#elif defined(PHAVE_LINUX_INPUT_H)
  _global_ptr = new LinuxInputDeviceManager;
#else
  _global_ptr = new InputDeviceManager;
#endif
}

/**
 * Description: Returns all currently connected devices.
 */
InputDeviceSet InputDeviceManager::
get_devices() const {
  InputDeviceSet devices;
  LightMutexHolder holder(_lock);

  for (size_t i = 0; i < _connected_devices.size(); ++i) {
    InputDevice *device = _connected_devices[i];
    devices.add_device(device);
  }

  return devices;
}

/**
 * Description: Returns all currently connected devices of the given device class.
 */
InputDeviceSet InputDeviceManager::
get_devices(InputDevice::DeviceClass device_class) const {
  InputDeviceSet devices;
  LightMutexHolder holder(_lock);

  for (size_t i = 0; i < _connected_devices.size(); ++i) {
    InputDevice *device = _connected_devices[i];
    if (device->get_device_class() == device_class) {
      devices.add_device(device);
    }
  }

  return devices;
}

/**
 * Called when a new device has been discovered.  This may also be used to
 * register virtual devices.
 *
 * This causes a connect-device event to be thrown.
 */
void InputDeviceManager::
add_device(InputDevice *device) {
  {
    LightMutexHolder holder(_lock);
    _connected_devices.add_device(device);

#ifdef PHAVE_LINUX_INPUT_H
    // If we had added it pending activity on the device, remove it
    // from the list of inactive devices.
    _inactive_devices.remove_device(device);
#endif
  }
  throw_event("connect-device", device);
}

/**
 * Called when a device has been removed, or when a device should otherwise no
 * longer be tracked.
 *
 * This causes a disconnect-device event to be thrown.
 */
void InputDeviceManager::
remove_device(InputDevice *device) {
  {
    LightMutexHolder holder(_lock);
    _connected_devices.remove_device(device);
  }

  throw_event("disconnect-device", device);
}

/**
 * Polls the system to see if there are any new devices.  In some
 * implementations this is a no-op.
 */
void InputDeviceManager::
update() {
}
<commit_msg>device: ensure libputil is initialized before scanning devices<commit_after>/**
 * PANDA 3D SOFTWARE
 * Copyright (c) Carnegie Mellon University.  All rights reserved.
 *
 * All use of this software is subject to the terms of the revised BSD
 * license.  You should have received a copy of this license along
 * with this source code in a file named "LICENSE."
 *
 * @file inputDeviceManager.cxx
 * @author rdb
 * @date 2015-12-09
 */

#include "inputDeviceManager.h"
#include "ioKitInputDeviceManager.h"
#include "linuxInputDeviceManager.h"
#include "winInputDeviceManager.h"
#include "throw_event.h"

InputDeviceManager *InputDeviceManager::_global_ptr = nullptr;

/**
 * Initializes the input device manager by scanning which devices are currently
 * connected and setting up any platform-dependent structures necessary for
 * listening for future device connect events.
 */
InputDeviceManager::
InputDeviceManager() : _lock("InputDeviceManager") {
}

/**
 * Creates the global input manager.
 */
void InputDeviceManager::
make_global_ptr() {
  init_libputil();

#ifdef _WIN32
  _global_ptr = new WinInputDeviceManager;
#elif defined(__APPLE__)
  _global_ptr = new IOKitInputDeviceManager;
#elif defined(PHAVE_LINUX_INPUT_H)
  _global_ptr = new LinuxInputDeviceManager;
#else
  _global_ptr = new InputDeviceManager;
#endif
}

/**
 * Description: Returns all currently connected devices.
 */
InputDeviceSet InputDeviceManager::
get_devices() const {
  InputDeviceSet devices;
  LightMutexHolder holder(_lock);

  for (size_t i = 0; i < _connected_devices.size(); ++i) {
    InputDevice *device = _connected_devices[i];
    devices.add_device(device);
  }

  return devices;
}

/**
 * Description: Returns all currently connected devices of the given device class.
 */
InputDeviceSet InputDeviceManager::
get_devices(InputDevice::DeviceClass device_class) const {
  InputDeviceSet devices;
  LightMutexHolder holder(_lock);

  for (size_t i = 0; i < _connected_devices.size(); ++i) {
    InputDevice *device = _connected_devices[i];
    if (device->get_device_class() == device_class) {
      devices.add_device(device);
    }
  }

  return devices;
}

/**
 * Called when a new device has been discovered.  This may also be used to
 * register virtual devices.
 *
 * This causes a connect-device event to be thrown.
 */
void InputDeviceManager::
add_device(InputDevice *device) {
  {
    LightMutexHolder holder(_lock);
    _connected_devices.add_device(device);

#ifdef PHAVE_LINUX_INPUT_H
    // If we had added it pending activity on the device, remove it
    // from the list of inactive devices.
    _inactive_devices.remove_device(device);
#endif
  }
  throw_event("connect-device", device);
}

/**
 * Called when a device has been removed, or when a device should otherwise no
 * longer be tracked.
 *
 * This causes a disconnect-device event to be thrown.
 */
void InputDeviceManager::
remove_device(InputDevice *device) {
  {
    LightMutexHolder holder(_lock);
    _connected_devices.remove_device(device);
  }

  throw_event("disconnect-device", device);
}

/**
 * Polls the system to see if there are any new devices.  In some
 * implementations this is a no-op.
 */
void InputDeviceManager::
update() {
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: viewobjectcontactofunocontrol.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SVX_SDR_CONTACT_VIEWOBJECTCONTACTOFUNOCONTROL_HXX
#define SVX_SDR_CONTACT_VIEWOBJECTCONTACTOFUNOCONTROL_HXX

#include <svx/sdr/contact/viewobjectcontactofsdrobj.hxx>

/** === begin UNO includes === **/
#include <com/sun/star/uno/Reference.hxx>
/** === end UNO includes === **/
#include <rtl/ref.hxx>
#include <svx/svxdllapi.h>

class OutputDevice;
class Window;
class SdrUnoObj;
namespace com { namespace sun { namespace star {
    namespace awt {
        class XControl;
        class XControlContainer;
    }
} } }

//........................................................................
namespace sdr { namespace contact {
//........................................................................

    class ViewContactOfUnoControl;
    class ObjectContactOfPageView;
    //====================================================================
    //= ViewObjectContactOfUnoControl
    //====================================================================
    class ViewObjectContactOfUnoControl_Impl;
    class SVX_DLLPRIVATE ViewObjectContactOfUnoControl : public ViewObjectContactOfSdrObj
    {
    protected:
        ::rtl::Reference< ViewObjectContactOfUnoControl_Impl >    m_pImpl;

    public:
        ViewObjectContactOfUnoControl( ObjectContact& _rObjectContact, ViewContactOfUnoControl& _rViewContact );

        /// determines whether an XControl already exists, and is currently visible
        bool    isControlVisible() const;

        /// returns the ->XControl instance belonging to the instance, creates it if necessary
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >
                getControl();

        /** retrieves a temporary XControl instance, whose parent is the given device
            @seealso SdrUnoObj::GetTemporaryControlForWindow
        */
        static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >
            getTemporaryControlForWindow(
                const Window& _rWindow,
                ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& _inout_ControlContainer,
                const SdrUnoObj& _rUnoObject
            );

        /// ensures that the control belonging to this instances has a given visibility
        void    ensureControlVisibility( bool _bVisible ) const;

        /** sets the design/alive mode of the control
        */
        void    setControlDesignMode( bool _bDesignMode ) const;

        /** callback from impl class to react on changes of properties form the XControlModel
        */
        void propertyChange();

        /** React on changes of the object of this ViewContact
        */
        virtual void ActionChanged();

        /** to be called when any aspect of the control which requires view updates changed
        */
        struct ImplAccess { friend class ViewObjectContactOfUnoControl_Impl; friend class ViewObjectContactOfUnoControl; private: ImplAccess() { } };
        void onControlChangedOrModified( ImplAccess ) { impl_onControlChangedOrModified(); }

    protected:
        ViewObjectContactOfUnoControl( ObjectContact& _rObjectContact, ViewContactOfUnoControl& _rViewContact );
        ~ViewObjectContactOfUnoControl();

        // support for Primitive2D
        virtual drawinglayer::primitive2d::Primitive2DSequence createPrimitive2DSequence(const DisplayInfo& rDisplayInfo) const;

        /// to be called when any aspect of the control which requires view updates changed
        void impl_onControlChangedOrModified();

    private:
        ViewObjectContactOfUnoControl();                                                  // never implemented
        ViewObjectContactOfUnoControl( const ViewObjectContactOfUnoControl& );              // never implemented
        ViewObjectContactOfUnoControl& operator=( const ViewObjectContactOfUnoControl& );   // never implemented
    };

    //====================================================================
    //= UnoControlPrintOrPreviewContact
    //====================================================================
    class SVX_DLLPRIVATE UnoControlPrintOrPreviewContact : public ViewObjectContactOfUnoControl
    {
    public:
        UnoControlPrintOrPreviewContact( ObjectContactOfPageView& _rObjectContact, ViewContactOfUnoControl& _rViewContact );
        ~UnoControlPrintOrPreviewContact();

    private:
        UnoControlPrintOrPreviewContact();                                                 // never implemented
        UnoControlPrintOrPreviewContact( const UnoControlPrintOrPreviewContact& );            // never implemented
        UnoControlPrintOrPreviewContact& operator=( const UnoControlPrintOrPreviewContact& ); // never implemented

        virtual drawinglayer::primitive2d::Primitive2DSequence createPrimitive2DSequence(const DisplayInfo& rDisplayInfo ) const;
    };

//........................................................................
} } // namespace sdr::contact
//........................................................................

#endif // SVX_SDR_CONTACT_VIEWOBJECTCONTACTOFUNOCONTROL_HXX

<commit_msg>make constructor public<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: viewobjectcontactofunocontrol.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SVX_SDR_CONTACT_VIEWOBJECTCONTACTOFUNOCONTROL_HXX
#define SVX_SDR_CONTACT_VIEWOBJECTCONTACTOFUNOCONTROL_HXX

#include <svx/sdr/contact/viewobjectcontactofsdrobj.hxx>

/** === begin UNO includes === **/
#include <com/sun/star/uno/Reference.hxx>
/** === end UNO includes === **/
#include <rtl/ref.hxx>
#include <svx/svxdllapi.h>

class OutputDevice;
class Window;
class SdrUnoObj;
namespace com { namespace sun { namespace star {
    namespace awt {
        class XControl;
        class XControlContainer;
    }
} } }

//........................................................................
namespace sdr { namespace contact {
//........................................................................

    class ViewContactOfUnoControl;
    class ObjectContactOfPageView;
    //====================================================================
    //= ViewObjectContactOfUnoControl
    //====================================================================
    class ViewObjectContactOfUnoControl_Impl;
    class SVX_DLLPRIVATE ViewObjectContactOfUnoControl : public ViewObjectContactOfSdrObj
    {
    protected:
        ::rtl::Reference< ViewObjectContactOfUnoControl_Impl >    m_pImpl;

    public:
        ViewObjectContactOfUnoControl( ObjectContact& _rObjectContact, ViewContactOfUnoControl& _rViewContact );
        /// determines whether an XControl already exists, and is currently visible
        bool    isControlVisible() const;

        /// returns the ->XControl instance belonging to the instance, creates it if necessary
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >
                getControl();

        /** retrieves a temporary XControl instance, whose parent is the given device
            @seealso SdrUnoObj::GetTemporaryControlForWindow
        */
        static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >
            getTemporaryControlForWindow(
                const Window& _rWindow,
                ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& _inout_ControlContainer,
                const SdrUnoObj& _rUnoObject
            );

        /// ensures that the control belonging to this instances has a given visibility
        void    ensureControlVisibility( bool _bVisible ) const;

        /** sets the design/alive mode of the control
        */
        void    setControlDesignMode( bool _bDesignMode ) const;

        /** callback from impl class to react on changes of properties form the XControlModel
        */
        void propertyChange();

        /** React on changes of the object of this ViewContact
        */
        virtual void ActionChanged();

        /** to be called when any aspect of the control which requires view updates changed
        */
        struct ImplAccess { friend class ViewObjectContactOfUnoControl_Impl; friend class ViewObjectContactOfUnoControl; private: ImplAccess() { } };
        void onControlChangedOrModified( ImplAccess ) { impl_onControlChangedOrModified(); }

    protected:
        ~ViewObjectContactOfUnoControl();

        // support for Primitive2D
        virtual drawinglayer::primitive2d::Primitive2DSequence createPrimitive2DSequence(const DisplayInfo& rDisplayInfo) const;

        /// to be called when any aspect of the control which requires view updates changed
        void impl_onControlChangedOrModified();

    private:
        ViewObjectContactOfUnoControl();                                                  // never implemented
        ViewObjectContactOfUnoControl( const ViewObjectContactOfUnoControl& );              // never implemented
        ViewObjectContactOfUnoControl& operator=( const ViewObjectContactOfUnoControl& );   // never implemented
    };

    //====================================================================
    //= UnoControlPrintOrPreviewContact
    //====================================================================
    class SVX_DLLPRIVATE UnoControlPrintOrPreviewContact : public ViewObjectContactOfUnoControl
    {
    public:
        UnoControlPrintOrPreviewContact( ObjectContactOfPageView& _rObjectContact, ViewContactOfUnoControl& _rViewContact );
        ~UnoControlPrintOrPreviewContact();

    private:
        UnoControlPrintOrPreviewContact();                                                 // never implemented
        UnoControlPrintOrPreviewContact( const UnoControlPrintOrPreviewContact& );            // never implemented
        UnoControlPrintOrPreviewContact& operator=( const UnoControlPrintOrPreviewContact& ); // never implemented

        virtual drawinglayer::primitive2d::Primitive2DSequence createPrimitive2DSequence(const DisplayInfo& rDisplayInfo ) const;
    };

//........................................................................
} } // namespace sdr::contact
//........................................................................

#endif // SVX_SDR_CONTACT_VIEWOBJECTCONTACTOFUNOCONTROL_HXX

<|endoftext|>


<commit_before>#include "TrajReader.h"
#include <array>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

// need to store the file object here
static std::ifstream trajectory_file;

static union bigint {
	char buf[sizeof(int64_t)];
	int64_t bi;
} ubi;

static union double_ {
	char buf[sizeof(double)];
	double d;
} ud;

static union int_ {
	char buf[sizeof(int)];
	int i;
} ui;

extern "C" {
	bool openfile(char * s, int *n) {
		std::string filename(s, *n);
		trajectory_file.open(filename.c_str(), std::ios::binary);
		return trajectory_file.is_open();
	}

	bool frameheader(int *timestep, int *n, double *box_lo, double *box_hi) {
		if(!trajectory_file.is_open()) {
			return false;
		}

		trajectory_file.read(ubi.buf, sizeof(int64_t));
		if(trajectory_file.fail()) {
			return false;
		}
		*timestep = ubi.bi;

		trajectory_file.read(ubi.buf, sizeof(int64_t));
		if(trajectory_file.fail()) {
			return false;
		}
		*n = ubi.bi;

		trajectory_file.read(ui.buf, sizeof(int));
		if(trajectory_file.fail()) {
			return false;
		}
		if (ui.i != 0) {
			//we don't support triclinic files!
			std::cerr << "Can't use triclinic boxes!" << std::endl;
			return false;
		}

		for (int j = 0; j < 2; ++j) {
			for (int i = 0; i < 3; ++i) {
				trajectory_file.read(ui.buf, sizeof(int));
				if(trajectory_file.fail()) {
					return false;
				}

				if (ui.i != 0) {
					std::cerr << "Detected non periodic"
						<< " boundary!" << std::endl;
					return false;
				}
			}
		}

		std::array<double, 6> box;
		for (int i = 0; i < 6; ++i) {
			trajectory_file.read(ud.buf, sizeof(double));
			if (trajectory_file.fail()) {
				return false;
			}
			box[i] = ud.d;
		}

		box_lo[0] = box[0];
		box_lo[1] = box[2];
		box_lo[2] = box[4];
		box_hi[0] = box[1];
		box_hi[1] = box[3];
		box_hi[2] = box[5];

		return true;
	}

	bool framebody(int *n, double *x, double *v, double *f) {
		trajectory_file.read(ui.buf, sizeof(int));
		if (trajectory_file.fail()) {
			return false;
		}

		unsigned int num_fields = static_cast<unsigned int>(ui.i);
		if (num_fields != 10) {
			std::cerr << "Trajectory files contains more than 10"
				<< " fields! Can't deal with this." << std::endl;
			return false;
		}

		trajectory_file.read(ui.buf, sizeof(int));
		if(trajectory_file.fail()) {
			return false;
		}
		int nprocs = ui.i;

		int running = 0;

		for (int i = 0; i < nprocs; ++i) {
			trajectory_file.read(ui.buf, sizeof(int));
			if (trajectory_file.fail()) {
				return false;
			}
			int bufsize = ui.i; //number of doubles that follow
			if (bufsize % num_fields != 0) {
				// the number of atoms in this block is
				// bufsize/num_fields. if this isn't an integer,
				// something has gone badly wrong
				std::cerr << "Non integer number of atoms"
					<< " reported!" << std::endl;
				return true;
			}
			int atoms_in_block = bufsize / num_fields;
			//the vector controls a contiguous memory chunk of size
			//bufsize*sizeof(double)
			std::vector<double_> buffer;
			buffer.resize(bufsize);
			trajectory_file.read(buffer.data()->buf, bufsize*sizeof(double));
			//now unpack this buffer
			for (int j = 0; j < atoms_in_block; ++j) {
				//we know the fields are:
				//ID X Y Z VX VY VZ FX FY FZ
				// = buffer[j*num_fields + k].d;
				double rx = buffer[j*num_fields+1].d;
				double ry = buffer[j*num_fields+2].d;
				double rz = buffer[j*num_fields+3].d;
				double vx = buffer[j*num_fields+4].d;
				double vy = buffer[j*num_fields+5].d;
				double vz = buffer[j*num_fields+6].d;
				double fx = buffer[j*num_fields+7].d;
				double fy = buffer[j*num_fields+8].d;
				double fz = buffer[j*num_fields+9].d;
#ifdef TARGET_FORTRAN
				x[running] = rx;
				x[(*n)+running] = ry;
				x[2*(*n)+running] = rz;
				v[running] = vx;
				v[(*n)+running] = vy;
				v[2*(*n)+running] = vz;
				f[running] = fx;
				f[(*n)+running] = fy;
				f[2*(*n)+running] = fz;
#elif TARGET_C
#endif
				running++;
			}
		}
		return true;
	}
}
<commit_msg>Corrected small C/FORTRAN interoperation error<commit_after>#include "TrajReader.h"
#include <array>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

// need to store the file object here
static std::ifstream trajectory_file;

static union bigint {
	char buf[sizeof(int64_t)];
	int64_t bi;
} ubi;

static union double_ {
	char buf[sizeof(double)];
	double d;
} ud;

static union int_ {
	char buf[sizeof(int)];
	int i;
} ui;

extern "C" {
	bool openfile(char * s, int *n) {
		std::string filename(s, *n);
		trajectory_file.open(filename.c_str(), std::ios::binary);
		return trajectory_file.is_open();
	}

	bool frameheader(int *timestep, int *n, double *box_lo, double *box_hi) {
		if(!trajectory_file.is_open()) {
			return false;
		}

		trajectory_file.read(ubi.buf, sizeof(int64_t));
		if(trajectory_file.fail()) {
			return false;
		}
		*timestep = ubi.bi;

		trajectory_file.read(ubi.buf, sizeof(int64_t));
		if(trajectory_file.fail()) {
			return false;
		}
		*n = ubi.bi;

		trajectory_file.read(ui.buf, sizeof(int));
		if(trajectory_file.fail()) {
			return false;
		}
		if (ui.i != 0) {
			//we don't support triclinic files!
			std::cerr << "Can't use triclinic boxes!" << std::endl;
			return false;
		}

		for (int j = 0; j < 2; ++j) {
			for (int i = 0; i < 3; ++i) {
				trajectory_file.read(ui.buf, sizeof(int));
				if(trajectory_file.fail()) {
					return false;
				}

				if (ui.i != 0) {
					std::cerr << "Detected non periodic"
						<< " boundary!" << std::endl;
					return false;
				}
			}
		}

		std::array<double, 6> box;
		for (int i = 0; i < 6; ++i) {
			trajectory_file.read(ud.buf, sizeof(double));
			if (trajectory_file.fail()) {
				return false;
			}
			box[i] = ud.d;
		}

		box_lo[0] = box[0];
		box_lo[1] = box[2];
		box_lo[2] = box[4];
		box_hi[0] = box[1];
		box_hi[1] = box[3];
		box_hi[2] = box[5];

		return true;
	}

	bool framebody(int *n, double *x, double *v, double *f) {
		trajectory_file.read(ui.buf, sizeof(int));
		if (trajectory_file.fail()) {
			return false;
		}

		unsigned int num_fields = static_cast<unsigned int>(ui.i);
		if (num_fields != 10) {
			std::cerr << "Trajectory files contains more than 10"
				<< " fields! Can't deal with this." << std::endl;
			return false;
		}

		trajectory_file.read(ui.buf, sizeof(int));
		if(trajectory_file.fail()) {
			return false;
		}
		int nprocs = ui.i;

		int running = 0;

		for (int i = 0; i < nprocs; ++i) {
			trajectory_file.read(ui.buf, sizeof(int));
			if (trajectory_file.fail()) {
				return false;
			}
			int bufsize = ui.i; //number of doubles that follow
			if (bufsize % num_fields != 0) {
				// the number of atoms in this block is
				// bufsize/num_fields. if this isn't an integer,
				// something has gone badly wrong
				std::cerr << "Non integer number of atoms"
					<< " reported!" << std::endl;
				return true;
			}
			int atoms_in_block = bufsize / num_fields;
			//the vector controls a contiguous memory chunk of size
			//bufsize*sizeof(double)
			std::vector<double_> buffer;
			buffer.resize(bufsize);
			trajectory_file.read(buffer.data()->buf, bufsize*sizeof(double));
			//now unpack this buffer
			for (int j = 0; j < atoms_in_block; ++j) {
				//we know the fields are:
				//ID X Y Z VX VY VZ FX FY FZ
				// = buffer[j*num_fields + k].d;
				double rx = buffer[j*num_fields+1].d;
				double ry = buffer[j*num_fields+2].d;
				double rz = buffer[j*num_fields+3].d;
				double vx = buffer[j*num_fields+4].d;
				double vy = buffer[j*num_fields+5].d;
				double vz = buffer[j*num_fields+6].d;
				double fx = buffer[j*num_fields+7].d;
				double fy = buffer[j*num_fields+8].d;
				double fz = buffer[j*num_fields+9].d;
				//C and FORTRAN handle arrays differently
#ifdef TARGET_FORTRAN
				x[running] = rx;
				x[(*n)+running] = ry;
				x[2*(*n)+running] = rz;
				v[running] = vx;
				v[(*n)+running] = vy;
				v[2*(*n)+running] = vz;
				f[running] = fx;
				f[(*n)+running] = fy;
				f[2*(*n)+running] = fz;
#elif TARGET_C
				x[3*running] = rx;
				x[3*running+1] = ry;
				x[3*running+2] = rz;
				v[3*running] = vx;
				v[3*running+1] = vy;
				v[3*running+2] = vz;
				f[3*running] = fx;
				f[3*running+1] = fy;
				f[3*running+2] = fz;
#endif
				running++;
			}
		}
		return true;
	}
}
<|endoftext|>


<commit_before>#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/poisson.h>
#include <pcl/io/vtk_io.h>

typedef pcl::Normal Normal;
//typedef pcl::PointXYZ PointType;
//typedef pcl::PointNormal PointTypeN;
typedef pcl::PointXYZRGB PointType;
typedef pcl::PointXYZRGBNormal PointTypeN;

int main(int argc, char *argv[])
{
    pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2 ());
    pcl::PCLPointCloud2::Ptr cloud_filtered (new pcl::PCLPointCloud2 ());

    // Fill in the cloud data
    pcl::PCDReader reader;
    if (argc < 1){
    reader.read ("pointcloud-ascii.pcd", *cloud);
    }
    else reader.read(argv[1], *cloud);

    std::cerr << "PointCloud before filtering: " << cloud->width * cloud->height
       << " data points (" << pcl::getFieldsList (*cloud) << ")." << std::endl;

    // Create the filtering object
    pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
    sor.setInputCloud (cloud);
    sor.setLeafSize (0.01f, 0.01f, 0.01f);
    sor.filter (*cloud_filtered);

    std::cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height
       << " data points (" << pcl::getFieldsList (*cloud_filtered) << ")." << std::endl;

    pcl::PCDWriter writer;
    writer.write ("pointcloud-ascii-downsampled.pcd", *cloud_filtered,
         Eigen::Vector4f::Zero (), Eigen::Quaternionf::Identity (), false);

    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud2 (new pcl::PointCloud<pcl::PointXYZRGB>);
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered2 (new pcl::PointCloud<pcl::PointXYZRGB>);

    // Fill in the cloud data
    // Replace the path below with the path where you saved your file
    reader.read<pcl::PointXYZRGB> ("pointcloud-ascii-downsampled.pcd", *cloud2);

    std::cerr << "Cloud before filtering: " << std::endl;
    std::cerr << *cloud2 << std::endl;

    // Create the filtering object
    pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor2;
    sor2.setInputCloud (cloud2);
    sor2.setMeanK (50);
    sor2.setStddevMulThresh (1.0);
    sor2.filter (*cloud_filtered2);

    std::cerr << "Cloud after filtering: " << std::endl;
    std::cerr << *cloud_filtered2 << std::endl;

    writer.write<pcl::PointXYZRGB> ("pointcloud-ascii-downsampled-inliers.pcd", *cloud_filtered2, false);

    sor2.setNegative (true);
    sor2.filter (*cloud_filtered2);
    writer.write<pcl::PointXYZRGB> ("pointcloud-ascii-downsampled-outliers.pcd", *cloud_filtered2, false);

    // Load input file into a PointCloud<T> with an appropriate type
    pcl::PointCloud<PointType>::Ptr cloud3 (new pcl::PointCloud<PointType>);
    pcl::PCLPointCloud2 cloud_blob;
    pcl::io::loadPCDFile ("pointcloud-ascii-downsampled-inliers.pcd", cloud_blob);
    //pcl::io::loadPCDFile ("bun0.pcd", cloud_blob);
    pcl::fromPCLPointCloud2 (cloud_blob, *cloud3);
    //* the data should be available in cloud
    std::cout << "cloud loaded " << std::endl;
    std::cout << cloud3->size() << std::endl;

    // Normal estimation*
    pcl::NormalEstimation<PointType, Normal> normEst;
    pcl::PointCloud<Normal>::Ptr normals (new pcl::PointCloud<Normal>);
    pcl::search::KdTree<PointType>::Ptr tree (new pcl::search::KdTree<PointType>);
    tree->setInputCloud (cloud3);
    normEst.setInputCloud (cloud3);
    normEst.setSearchMethod (tree);
    normEst.setKSearch (20);
    normEst.compute (*normals);
    //* normals should not contain the point normals + surface curvatures

    // Concatenate the XYZ and normal fields*
    pcl::PointCloud<PointTypeN>::Ptr cloud_with_normals (new pcl::PointCloud<PointTypeN>);
    pcl::concatenateFields (*cloud3, *normals, *cloud_with_normals);
    //* cloud_with_normals = cloud + normals

    // Create search tree*
    pcl::search::KdTree<PointTypeN>::Ptr tree2 (new pcl::search::KdTree<PointTypeN>);
    tree2->setInputCloud (cloud_with_normals);

    // Initialize objects
    pcl::Poisson<PointTypeN> poissn;
    pcl::PolygonMesh triangles;

    std::cout << cloud_with_normals->size() << std::endl;

    poissn.setInputCloud(cloud_with_normals);
    poissn.setSearchMethod(tree2);
    poissn.reconstruct (triangles);
    poissn.setOutputPolygons(false);

    pcl::io::saveVTKFile ("mesh-dnevna.vtk", triangles);
    return 0;
}
<commit_msg>changed codding style<commit_after>#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/poisson.h>
#include <pcl/io/vtk_io.h>

typedef pcl::Normal Normal;
//typedef pcl::PointXYZ PointType;
//typedef pcl::PointNormal PointTypeN;
typedef pcl::PointXYZRGB PointType;
typedef pcl::PointXYZRGBNormal PointTypeN;

int main(int argc, char *argv[])
{
    pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2());
    pcl::PCLPointCloud2::Ptr cloud_filtered (new pcl::PCLPointCloud2());

    // Fill in the cloud data
    pcl::PCDReader reader;
    if (argc < 1){
    reader.read ("pointcloud-ascii.pcd", *cloud);
    }
    else reader.read(argv[1], *cloud);

    std::cout << "PointCloud before filtering: " << cloud->width *
        cloud->height << " data points (" << pcl::getFieldsList (*cloud)
        << ")." << std::endl;

    // Create the filtering object
    pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
    sor.setInputCloud (cloud);
    sor.setLeafSize (0.01f, 0.01f, 0.01f);
    sor.filter (*cloud_filtered);

    std::cout << "PointCloud after filtering: " <<
            cloud_filtered->width * cloud_filtered->height
            << " data points (" << pcl::getFieldsList (*cloud_filtered)
            << ")." << std::endl;

    pcl::PCDWriter writer;
    writer.write ("pointcloud-ascii-downsampled.pcd", *cloud_filtered,
            Eigen::Vector4f::Zero(), Eigen::Quaternionf::Identity(),
            false);

    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud2 (new
            pcl::PointCloud<pcl::PointXYZRGB>);
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered2 (new
            pcl::PointCloud<pcl::PointXYZRGB>);

    // Fill in the cloud data
    // Replace the path below with the path where you saved your file
    reader.read<pcl::PointXYZRGB> ("pointcloud-ascii-downsampled.pcd",
            *cloud2);

    std::cerr << "Cloud before filtering: " << std::endl;
    std::cerr << *cloud2 << std::endl;

    // Create the filtering object
    pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor2;
    sor2.setInputCloud (cloud2);
    sor2.setMeanK (50);
    sor2.setStddevMulThresh (1.0);
    sor2.filter (*cloud_filtered2);

    std::cout << "Cloud after filtering: " << std::endl;
    std::cout << *cloud_filtered2 << std::endl;

    writer.write<pcl::PointXYZRGB>
        ("pointcloud-ascii-downsampled-inliers.pcd", *cloud_filtered2,
         false);

    sor2.setNegative (true);
    sor2.filter (*cloud_filtered2);
    writer.write<pcl::PointXYZRGB>
        ("pointcloud-ascii-downsampled-outliers.pcd", *cloud_filtered2,
         false);

    // Load input file into a PointCloud<T> with an appropriate type
    pcl::PointCloud<PointType>::Ptr cloud3 (new
            pcl::PointCloud<PointType>);
    pcl::PCLPointCloud2 cloud_blob;
    pcl::io::loadPCDFile ("pointcloud-ascii-downsampled-inliers.pcd",
            cloud_blob);
    //pcl::io::loadPCDFile ("bun0.pcd", cloud_blob);
    pcl::fromPCLPointCloud2 (cloud_blob, *cloud3);
    //* the data should be available in cloud
    std::cout << "cloud loaded " << std::endl;
    std::cout << cloud3->size() << std::endl;

    // Normal estimation*
    pcl::NormalEstimation<PointType, Normal> normEst;
    pcl::PointCloud<Normal>::Ptr normals (new pcl::PointCloud<Normal>);
    pcl::search::KdTree<PointType>::Ptr tree (new
            pcl::search::KdTree<PointType>);
    tree->setInputCloud (cloud3);
    normEst.setInputCloud (cloud3);
    normEst.setSearchMethod (tree);
    normEst.setKSearch (20);
    normEst.compute (*normals);
    //* normals should not contain the point normals + surface
    //curvatures

    // Concatenate the XYZ and normal fields*
    pcl::PointCloud<PointTypeN>::Ptr cloud_with_normals (new
            pcl::PointCloud<PointTypeN>);
    pcl::concatenateFields (*cloud3, *normals, *cloud_with_normals);
    //* cloud_with_normals = cloud + normals

    // Create search tree*
    pcl::search::KdTree<PointTypeN>::Ptr tree2 (new
            pcl::search::KdTree<PointTypeN>);
    tree2->setInputCloud (cloud_with_normals);

    // Initialize objects
    pcl::Poisson<PointTypeN> poissn;
    pcl::PolygonMesh triangles;

    std::cout << cloud_with_normals->size() << std::endl;

    poissn.setInputCloud(cloud_with_normals);
    poissn.setSearchMethod(tree2);
    poissn.reconstruct (triangles);
    poissn.setOutputPolygons(false);

    pcl::io::saveVTKFile ("mesh-dnevna.vtk", triangles);
    return 0;
}
<|endoftext|>


<commit_before>#include <gfx/opengl/glew.hpp>
#include <window/sdl_window.hpp>
#include <stlw/format.hpp>
#include <stlw/result.hpp>
#include <stlw/type_ctors.hpp>
#include <stlw/type_macros.hpp>

namespace window
{

// std::string error = SDL_GetError();
// if (error != "") {
// ostream << "SLD Error : " << error << std::endl;
// SDL_ClearError();
//}

stlw::result<stlw::empty_type, std::string>
sdl_library::init()
{
  // (from the docs) The requested attributes should be set before creating an
  // OpenGL window
  auto const set_attribute = [](auto const attribute,
                                auto const value) -> stlw::result<stlw::empty_type, std::string> {
    bool const set_attribute_suceeded = SDL_GL_SetAttribute(attribute, value);
    if (!set_attribute_suceeded) {
      auto const fmt = fmt::format("Setting attribute '{}' failed, error is '{}'\n",
                                   std::to_string(attribute), SDL_GetError());
      return stlw::make_error(fmt);
    }
    return stlw::make_empty();
  };

  // Use OpenGL 3.1 core
  DO_TRY(auto _, set_attribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3));
  DO_TRY(auto __, set_attribute(SDL_GL_CONTEXT_MINOR_VERSION, 1));
  DO_TRY(auto ___, set_attribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE));

  // Turn on double buffering with a 24bit Z buffer.
  // You may need to change this to 16 or 32 for your system
  DO_TRY(auto ____, set_attribute(SDL_GL_DOUBLEBUFFER, 1));

  // Use v-sync
  SDL_GL_SetSwapInterval(1);

  // Initialize video subsystem
  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    // Display error message
    auto const error = fmt::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
    return stlw::make_error(error);
  }
  return stlw::make_empty();
}

void
sdl_library::destroy()
{
  if (SDL_WasInit(SDL_INIT_EVERYTHING)) {
    SDL_Quit();
  }
}

stlw::result<sdl_window, std::string>
sdl_library::make_window(int const height, int const width)
{
  // Hidden dependency between the ordering here, so all the logic exists in one
  // place.
  //
  // * The OpenGL context MUST be initialized before the call to glewInit()
  // takes place.
  // This is because there is a hidden dependency on glew, it expects an OpenGL
  // context to be
  // initialized. The glew library knows how to find the OpenGL context in
  // memory without any
  // reference, so it's a bit like magic.
  //
  // NOTE: We don't have to do anything to shutdown glew, the processing closing
  // will handle it (by design).

  // First, create the SDL window.
  auto const title = "Hello World!";
  auto const flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  int const x = SDL_WINDOWPOS_CENTERED;
  int const y = SDL_WINDOWPOS_CENTERED;
  auto raw = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width,
                              height, flags);
  if (nullptr == raw) {
    auto const error = fmt::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
    return stlw::make_error(error);
  }
  window_ptr window_ptr{raw, &SDL_DestroyWindow};

  // Second, create the graphics context.
  auto gl_context = SDL_GL_CreateContext(window_ptr.get());
  if (nullptr == gl_context) {
    // Display error message
    auto const error =
        fmt::format("OpenGL context could not be created! SDL Error: {}\n", SDL_GetError());
    return stlw::make_error(error);
  }
  // Make the window the current one
  SDL_GL_MakeCurrent(window_ptr.get(), gl_context);

  // make sdl capture the input device
  // http://gamedev.stackexchange.com/questions/33519/trap-mouse-in-sdl
  {
    int const code = SDL_SetRelativeMouseMode(SDL_TRUE);
    if (code == -1) {
      return stlw::make_error("Mouse relative mode not supported.");
    }
    else if (code != 0) {
      return stlw::make_error(fmt::sprintf("Error setting mouse relative mode '%s'", SDL_GetError()));
    }
  }

  // Third, initialize GLEW.
  glewExperimental = GL_TRUE;
  auto const glew_status = glewInit();
  if (GLEW_OK != glew_status) {
    auto const error =
        fmt::format("GLEW could not initialize! GLEW error: {}\n", glewGetErrorString(glew_status));
    return stlw::make_error(error);
  }
  return sdl_window{std::move(window_ptr), gl_context};
}

} // ns window
<commit_msg>Move the window to the bottom right corner.<commit_after>#include <gfx/opengl/glew.hpp>
#include <window/sdl_window.hpp>
#include <stlw/format.hpp>
#include <stlw/result.hpp>
#include <stlw/type_ctors.hpp>
#include <stlw/type_macros.hpp>

namespace window
{

// std::string error = SDL_GetError();
// if (error != "") {
// ostream << "SLD Error : " << error << std::endl;
// SDL_ClearError();
//}

stlw::result<stlw::empty_type, std::string>
sdl_library::init()
{
  // (from the docs) The requested attributes should be set before creating an
  // OpenGL window
  auto const set_attribute = [](auto const attribute,
                                auto const value) -> stlw::result<stlw::empty_type, std::string> {
    bool const set_attribute_suceeded = SDL_GL_SetAttribute(attribute, value);
    if (!set_attribute_suceeded) {
      auto const fmt = fmt::format("Setting attribute '{}' failed, error is '{}'\n",
                                   std::to_string(attribute), SDL_GetError());
      return stlw::make_error(fmt);
    }
    return stlw::make_empty();
  };

  // Use OpenGL 3.1 core
  DO_TRY(auto _, set_attribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3));
  DO_TRY(auto __, set_attribute(SDL_GL_CONTEXT_MINOR_VERSION, 1));
  DO_TRY(auto ___, set_attribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE));

  // Turn on double buffering with a 24bit Z buffer.
  // You may need to change this to 16 or 32 for your system
  DO_TRY(auto ____, set_attribute(SDL_GL_DOUBLEBUFFER, 1));

  // Use v-sync
  SDL_GL_SetSwapInterval(1);

  // Initialize video subsystem
  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    // Display error message
    auto const error = fmt::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
    return stlw::make_error(error);
  }
  return stlw::make_empty();
}

void
sdl_library::destroy()
{
  if (SDL_WasInit(SDL_INIT_EVERYTHING)) {
    SDL_Quit();
  }
}

stlw::result<sdl_window, std::string>
sdl_library::make_window(int const height, int const width)
{
  // Hidden dependency between the ordering here, so all the logic exists in one
  // place.
  //
  // * The OpenGL context MUST be initialized before the call to glewInit()
  // takes place.
  // This is because there is a hidden dependency on glew, it expects an OpenGL
  // context to be
  // initialized. The glew library knows how to find the OpenGL context in
  // memory without any
  // reference, so it's a bit like magic.
  //
  // NOTE: We don't have to do anything to shutdown glew, the processing closing
  // will handle it (by design).

  // First, create the SDL window.
  auto const title = "Hello World!";
  auto const flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  int const x = SDL_WINDOWPOS_CENTERED;
  int const y = SDL_WINDOWPOS_CENTERED;
  auto raw = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width,
                              height, flags);
  if (nullptr == raw) {
    auto const error = fmt::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
    return stlw::make_error(error);
  }
  window_ptr window_ptr{raw, &SDL_DestroyWindow};

  // Second, create the graphics context.
  auto gl_context = SDL_GL_CreateContext(window_ptr.get());
  if (nullptr == gl_context) {
    // Display error message
    auto const error =
        fmt::format("OpenGL context could not be created! SDL Error: {}\n", SDL_GetError());
    return stlw::make_error(error);
  }
  // Make the window the current one
  SDL_GL_MakeCurrent(window_ptr.get(), gl_context);

  // make sdl capture the input device
  // http://gamedev.stackexchange.com/questions/33519/trap-mouse-in-sdl
  {
    int const code = SDL_SetRelativeMouseMode(SDL_TRUE);
    if (code == -1) {
      return stlw::make_error("Mouse relative mode not supported.");
    }
    else if (code != 0) {
      return stlw::make_error(fmt::sprintf("Error setting mouse relative mode '%s'", SDL_GetError()));
    }
  }

  // set window initially to rhs
  {
    SDL_DisplayMode dmode;
    SDL_GetDesktopDisplayMode(0, &dmode);

    auto const h = dmode.h;
    auto const w = dmode.w;
    SDL_SetWindowPosition(window_ptr.get(), w / 2, h / 2);
  }

  // Third, initialize GLEW.
  glewExperimental = GL_TRUE;
  auto const glew_status = glewInit();
  if (GLEW_OK != glew_status) {
    auto const error =
        fmt::format("GLEW could not initialize! GLEW error: {}\n", glewGetErrorString(glew_status));
    return stlw::make_error(error);
  }
  return sdl_window{std::move(window_ptr), gl_context};
}

} // ns window
<|endoftext|>


<commit_before>
#include "cmath" // For isnan(), when it's defined

#include "diff_system.h"
#include "equation_systems.h"
#include "libmesh_logging.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"
#include "dof_map.h"

NewtonSolver::NewtonSolver (sys_type& s)
  : Parent(s),
    require_residual_reduction(true),
    minsteplength(1e-5),
    linear_tolerance_multiplier(1e-3),
    linear_solver(LinearSolver<Number>::build())
{
}

NewtonSolver::~NewtonSolver ()
{
}

void NewtonSolver::reinit()
{
  Parent::reinit();

  linear_solver->clear();
}

void NewtonSolver::solve()
{
  START_LOG("solve()", "NewtonSolver");

  NumericVector<Number> &solution = *(_system.solution);
  NumericVector<Number> &newton_iterate =
    _system.get_vector("_nonlinear_solution");
  newton_iterate.close();
  solution.close();

  solution = newton_iterate;
  _system.get_dof_map().enforce_constraints_exactly(_system);
  newton_iterate = solution;

  NumericVector<Number> &rhs = *(_system.rhs);

  SparseMatrix<Number> &matrix = *(_system.matrix);

  // Prepare to take incomplete steps
  Real last_residual=0.;

  // Set starting linear tolerance
  Real current_linear_tolerance = initial_linear_tolerance;

  // Now we begin the nonlinear loop
  for (unsigned int l=0; l<max_nonlinear_iterations; ++l)
    {
      if (!quiet)
        std::cout << "Assembling System" << std::endl;

      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, true);
      RESTART_LOG("solve()", "NewtonSolver");
      rhs.close();
      Real current_residual = rhs.l2_norm();
      last_residual = current_residual;

// isnan() isn't standard C++ yet
#ifdef isnan
      if (isnan(current_residual))
        {
          std::cout << "  Nonlinear solver DIVERGED at step " << l
                    << " with norm Not-a-Number"
                    << std::endl;
          error();
          continue;
        }
#endif // isnan

      max_residual_norm = std::max (current_residual,
                                    max_residual_norm);

      // Compute the l2 norm of the whole solution
      Real norm_total = newton_iterate.l2_norm();

      max_solution_norm = std::max(max_solution_norm, norm_total);

      if (!quiet)
        std::cout << "Nonlinear Residual: "
                  << current_residual << std::endl;

      // Make sure our linear tolerance is low enough
      current_linear_tolerance = std::min (current_linear_tolerance,
        current_residual * linear_tolerance_multiplier);

      // But don't let it be zero
      if (current_linear_tolerance == 0.)
        {
          current_linear_tolerance = TOLERANCE * TOLERANCE;
        }

      // At this point newton_iterate is the current guess, and
      // solution is now about to become the NEGATIVE of the next
      // Newton step.

      // Our best initial guess for the solution is zero!
      solution.zero();

      if (!quiet)
        std::cout << "Linear solve starting" << std::endl;

      PAUSE_LOG("solve()", "NewtonSolver");
      // Solve the linear system.  Two cases:
      const std::pair<unsigned int, Real> rval =
        (_system.have_matrix("Preconditioner")) ?
      // 1.) User-supplied preconditioner
        linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
                              solution, rhs, current_linear_tolerance,
                              max_linear_iterations) :
      // 2.) Use system matrix for the preconditioner
        linear_solver->solve (matrix, solution, rhs,
                              current_linear_tolerance,
                              max_linear_iterations);
      // We may need to localize a parallel solution
      _system.update ();
      RESTART_LOG("solve()", "NewtonSolver");
      // The linear solver may not have fit our constraints exactly
      _system.get_dof_map().enforce_constraints_exactly(_system);

      const unsigned int linear_steps = rval.first;
      assert(linear_steps <= max_linear_iterations);
      const bool linear_solve_finished =
        !(linear_steps == max_linear_iterations);

      if (!quiet)
        std::cout << "Linear solve finished, step " << linear_steps
                  << ", residual " << rval.second
                  << ", tolerance " << current_linear_tolerance
                  << std::endl;

      // Compute the l2 norm of the nonlinear update
      Real norm_delta = solution.l2_norm();

      if (!quiet)
        std::cout << "Trying full Newton step" << std::endl;
      // Take a full Newton step
      newton_iterate.add (-1., solution);
      newton_iterate.close();

      // Check residual with full Newton step
      Real steplength = 1.;
      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, false);
      RESTART_LOG("solve()", "NewtonSolver");

      rhs.close();
      current_residual = rhs.l2_norm();

      // backtrack if necessary
      if (require_residual_reduction)
        {
          // but don't fiddle around if we've already converged
          if (test_convergence(current_residual, norm_delta,
                               linear_solve_finished))
            {
              if (!quiet)
		print_convergence(l, current_residual, norm_delta,
                                  linear_solve_finished);
              break;
            }

          while (current_residual > last_residual)
            {
              // Reduce step size to 1/2, 1/4, etc.
              steplength /= 2.;
              norm_delta /= 2.;
              if (!quiet)
                std::cout << "Shrinking Newton step to "
                          << steplength << std::endl;
              newton_iterate.add (steplength, solution);
              newton_iterate.close();

              // Check residual with fractional Newton step
              PAUSE_LOG("solve()", "NewtonSolver");
              _system.assembly (true, false);
              RESTART_LOG("solve()", "NewtonSolver");

              rhs.close();
              current_residual = rhs.l2_norm();
              if (!quiet)
                std::cout << "Current Residual: "
                          << current_residual << std::endl;

              if (steplength/2. < minsteplength &&
                  current_residual > last_residual)
                {
                  std::cout << "Inexact Newton step FAILED at step "
                            << l << std::endl;

                  error();
                }
            }
        }

      // Compute the l2 norm of the whole solution
      norm_total = newton_iterate.l2_norm();

      max_solution_norm = std::max(max_solution_norm, norm_total);

      // Print out information for the
      // nonlinear iterations.
      if (!quiet)
        std::cout << "  Nonlinear step: |du|/|u| = "
                  << norm_delta / norm_total
                  << ", |du| = " << norm_delta
                  << std::endl;

      // Terminate the solution iteration if the difference between
      // this iteration and the last is sufficiently small.
      if (!quiet)
        print_convergence(l, current_residual,
                          norm_delta / steplength,
                          linear_solve_finished);
      if (test_convergence(current_residual, norm_delta / steplength,
                           linear_solve_finished))
        {
          break;
        }
      if (l >= max_nonlinear_iterations - 1)
        {
          std::cout << "  Nonlinear solver FAILED TO CONVERGE by step " << l
                    << " with norm " << norm_total
                    << std::endl;
          error();
          continue;
        }
    } // end nonlinear loop

  // Copy the final nonlinear iterate into the current_solution,
  // for other libMesh functions that expect it

  solution = newton_iterate;
  solution.close();

  // The linear solver may not have fit our constraints exactly
  _system.get_dof_map().enforce_constraints_exactly(_system);
  newton_iterate = solution;
  solution.close();

  // We may need to localize a parallel solution
  _system.update ();

  STOP_LOG("solve()", "NewtonSolver");
}

bool NewtonSolver::test_convergence(Real current_residual,
                                    Real step_norm,
                                    bool linear_solve_finished)
{
  // We haven't converged unless we pass a convergence test
  bool has_converged = false;

  // Is our absolute residual low enough?
  if (current_residual < absolute_residual_tolerance)
    has_converged = true;

  // Is our relative residual low enough?
  if ((current_residual / max_residual_norm) <
      relative_residual_tolerance)
    has_converged = true;

  // For incomplete linear solves, it's not safe to test step sizes
  if (!linear_solve_finished)
    return has_converged;

  // Is our absolute Newton step size small enough?
  if (step_norm < absolute_step_tolerance)
    has_converged = true;

  // Is our relative Newton step size small enough?
  if (step_norm / max_solution_norm <
      relative_step_tolerance)
    has_converged = true;

  return has_converged;
}

void NewtonSolver::print_convergence(unsigned int step_num,
                                     Real current_residual,
                                     Real step_norm,
                                     bool linear_solve_finished)
{
  // Is our absolute residual low enough?
  if (current_residual < absolute_residual_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", residual " << current_residual
                << std::endl;
    }
  else if (absolute_residual_tolerance)
    {
      std::cout << "  Nonlinear solver current_residual "
                << current_residual << " > "
                << (absolute_residual_tolerance) << std::endl;
    }

  // Is our relative residual low enough?
  if ((current_residual / max_residual_norm) <
      relative_residual_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", residual reduction "
                << current_residual / max_residual_norm
                << " < " << relative_residual_tolerance
                << std::endl;
    }
  else if (relative_residual_tolerance)
    {
      if (!quiet)
        std::cout << "  Nonlinear solver relative residual "
                  << (current_residual / max_residual_norm)
                  << " > " << relative_residual_tolerance
                  << std::endl;
    }

  // For incomplete linear solves, it's not safe to test step sizes
  if (!linear_solve_finished)
    return;

  // Is our absolute Newton step size small enough?
  if (step_norm < absolute_step_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", absolute step size "
                << step_norm
                << " < " << absolute_step_tolerance
                << std::endl;
    }
  else if (absolute_step_tolerance)
    {
      std::cout << "  Nonlinear solver absolute step size "
                << step_norm
                << " > " << absolute_step_tolerance
                << std::endl;
    }

  // Is our relative Newton step size small enough?
  if (step_norm / max_solution_norm <
      relative_step_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", relative step size "
                << (step_norm / max_solution_norm)
                << " < " << relative_step_tolerance
                << std::endl;
    }
  else if (relative_step_tolerance)
    {
      std::cout << "  Nonlinear solver relative step size "
                << (step_norm / max_solution_norm)
                << " > " << relative_step_tolerance
                << std::endl;
    }
}
<commit_msg>Obey continue_after_max_iterations option<commit_after>
#include "cmath" // For isnan(), when it's defined

#include "diff_system.h"
#include "equation_systems.h"
#include "libmesh_logging.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"
#include "dof_map.h"

NewtonSolver::NewtonSolver (sys_type& s)
  : Parent(s),
    require_residual_reduction(true),
    minsteplength(1e-5),
    linear_tolerance_multiplier(1e-3),
    linear_solver(LinearSolver<Number>::build())
{
}

NewtonSolver::~NewtonSolver ()
{
}

void NewtonSolver::reinit()
{
  Parent::reinit();

  linear_solver->clear();
}

void NewtonSolver::solve()
{
  START_LOG("solve()", "NewtonSolver");

  NumericVector<Number> &solution = *(_system.solution);
  NumericVector<Number> &newton_iterate =
    _system.get_vector("_nonlinear_solution");
  newton_iterate.close();
  solution.close();

  solution = newton_iterate;
  _system.get_dof_map().enforce_constraints_exactly(_system);
  newton_iterate = solution;

  NumericVector<Number> &rhs = *(_system.rhs);

  SparseMatrix<Number> &matrix = *(_system.matrix);

  // Prepare to take incomplete steps
  Real last_residual=0.;

  // Set starting linear tolerance
  Real current_linear_tolerance = initial_linear_tolerance;

  // Now we begin the nonlinear loop
  for (unsigned int l=0; l<max_nonlinear_iterations; ++l)
    {
      if (!quiet)
        std::cout << "Assembling System" << std::endl;

      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, true);
      RESTART_LOG("solve()", "NewtonSolver");
      rhs.close();
      Real current_residual = rhs.l2_norm();
      last_residual = current_residual;

// isnan() isn't standard C++ yet
#ifdef isnan
      if (isnan(current_residual))
        {
          std::cout << "  Nonlinear solver DIVERGED at step " << l
                    << " with norm Not-a-Number"
                    << std::endl;
          error();
          continue;
        }
#endif // isnan

      max_residual_norm = std::max (current_residual,
                                    max_residual_norm);

      // Compute the l2 norm of the whole solution
      Real norm_total = newton_iterate.l2_norm();

      max_solution_norm = std::max(max_solution_norm, norm_total);

      if (!quiet)
        std::cout << "Nonlinear Residual: "
                  << current_residual << std::endl;

      // Make sure our linear tolerance is low enough
      current_linear_tolerance = std::min (current_linear_tolerance,
        current_residual * linear_tolerance_multiplier);

      // But don't let it be zero
      if (current_linear_tolerance == 0.)
        {
          current_linear_tolerance = TOLERANCE * TOLERANCE;
        }

      // At this point newton_iterate is the current guess, and
      // solution is now about to become the NEGATIVE of the next
      // Newton step.

      // Our best initial guess for the solution is zero!
      solution.zero();

      if (!quiet)
        std::cout << "Linear solve starting" << std::endl;

      PAUSE_LOG("solve()", "NewtonSolver");
      // Solve the linear system.  Two cases:
      const std::pair<unsigned int, Real> rval =
        (_system.have_matrix("Preconditioner")) ?
      // 1.) User-supplied preconditioner
        linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
                              solution, rhs, current_linear_tolerance,
                              max_linear_iterations) :
      // 2.) Use system matrix for the preconditioner
        linear_solver->solve (matrix, solution, rhs,
                              current_linear_tolerance,
                              max_linear_iterations);
      // We may need to localize a parallel solution
      _system.update ();
      RESTART_LOG("solve()", "NewtonSolver");
      // The linear solver may not have fit our constraints exactly
      _system.get_dof_map().enforce_constraints_exactly(_system);

      const unsigned int linear_steps = rval.first;
      assert(linear_steps <= max_linear_iterations);
      const bool linear_solve_finished =
        !(linear_steps == max_linear_iterations);

      if (!quiet)
        std::cout << "Linear solve finished, step " << linear_steps
                  << ", residual " << rval.second
                  << ", tolerance " << current_linear_tolerance
                  << std::endl;

      // Compute the l2 norm of the nonlinear update
      Real norm_delta = solution.l2_norm();

      if (!quiet)
        std::cout << "Trying full Newton step" << std::endl;
      // Take a full Newton step
      newton_iterate.add (-1., solution);
      newton_iterate.close();

      // Check residual with full Newton step
      Real steplength = 1.;
      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, false);
      RESTART_LOG("solve()", "NewtonSolver");

      rhs.close();
      current_residual = rhs.l2_norm();

      // backtrack if necessary
      if (require_residual_reduction)
        {
          // but don't fiddle around if we've already converged
          if (test_convergence(current_residual, norm_delta,
                               linear_solve_finished))
            {
              if (!quiet)
		print_convergence(l, current_residual, norm_delta,
                                  linear_solve_finished);
              break;
            }

          while (current_residual > last_residual)
            {
              // Reduce step size to 1/2, 1/4, etc.
              steplength /= 2.;
              norm_delta /= 2.;
              if (!quiet)
                std::cout << "Shrinking Newton step to "
                          << steplength << std::endl;
              newton_iterate.add (steplength, solution);
              newton_iterate.close();

              // Check residual with fractional Newton step
              PAUSE_LOG("solve()", "NewtonSolver");
              _system.assembly (true, false);
              RESTART_LOG("solve()", "NewtonSolver");

              rhs.close();
              current_residual = rhs.l2_norm();
              if (!quiet)
                std::cout << "Current Residual: "
                          << current_residual << std::endl;

              if (steplength/2. < minsteplength &&
                  current_residual > last_residual)
                {
                  std::cout << "Inexact Newton step FAILED at step "
                            << l << std::endl;

                  error();
                }
            }
        }

      // Compute the l2 norm of the whole solution
      norm_total = newton_iterate.l2_norm();

      max_solution_norm = std::max(max_solution_norm, norm_total);

      // Print out information for the
      // nonlinear iterations.
      if (!quiet)
        std::cout << "  Nonlinear step: |du|/|u| = "
                  << norm_delta / norm_total
                  << ", |du| = " << norm_delta
                  << std::endl;

      // Terminate the solution iteration if the difference between
      // this iteration and the last is sufficiently small.
      if (!quiet)
        print_convergence(l, current_residual,
                          norm_delta / steplength,
                          linear_solve_finished);
      if (test_convergence(current_residual, norm_delta / steplength,
                           linear_solve_finished))
        {
          break;
        }
      if (l >= max_nonlinear_iterations - 1)
        {
          std::cout << "  Nonlinear solver FAILED TO CONVERGE by step " << l
                    << " with norm " << norm_total
                    << std::endl;
          if (continue_after_max_iterations)
            std::cout << "  Continuing anyway..." << std::endl;
          else
            error();
          continue;
        }
    } // end nonlinear loop

  // Copy the final nonlinear iterate into the current_solution,
  // for other libMesh functions that expect it

  solution = newton_iterate;
  solution.close();

  // The linear solver may not have fit our constraints exactly
  _system.get_dof_map().enforce_constraints_exactly(_system);
  newton_iterate = solution;
  solution.close();

  // We may need to localize a parallel solution
  _system.update ();

  STOP_LOG("solve()", "NewtonSolver");
}

bool NewtonSolver::test_convergence(Real current_residual,
                                    Real step_norm,
                                    bool linear_solve_finished)
{
  // We haven't converged unless we pass a convergence test
  bool has_converged = false;

  // Is our absolute residual low enough?
  if (current_residual < absolute_residual_tolerance)
    has_converged = true;

  // Is our relative residual low enough?
  if ((current_residual / max_residual_norm) <
      relative_residual_tolerance)
    has_converged = true;

  // For incomplete linear solves, it's not safe to test step sizes
  if (!linear_solve_finished)
    return has_converged;

  // Is our absolute Newton step size small enough?
  if (step_norm < absolute_step_tolerance)
    has_converged = true;

  // Is our relative Newton step size small enough?
  if (step_norm / max_solution_norm <
      relative_step_tolerance)
    has_converged = true;

  return has_converged;
}

void NewtonSolver::print_convergence(unsigned int step_num,
                                     Real current_residual,
                                     Real step_norm,
                                     bool linear_solve_finished)
{
  // Is our absolute residual low enough?
  if (current_residual < absolute_residual_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", residual " << current_residual
                << std::endl;
    }
  else if (absolute_residual_tolerance)
    {
      std::cout << "  Nonlinear solver current_residual "
                << current_residual << " > "
                << (absolute_residual_tolerance) << std::endl;
    }

  // Is our relative residual low enough?
  if ((current_residual / max_residual_norm) <
      relative_residual_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", residual reduction "
                << current_residual / max_residual_norm
                << " < " << relative_residual_tolerance
                << std::endl;
    }
  else if (relative_residual_tolerance)
    {
      if (!quiet)
        std::cout << "  Nonlinear solver relative residual "
                  << (current_residual / max_residual_norm)
                  << " > " << relative_residual_tolerance
                  << std::endl;
    }

  // For incomplete linear solves, it's not safe to test step sizes
  if (!linear_solve_finished)
    return;

  // Is our absolute Newton step size small enough?
  if (step_norm < absolute_step_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", absolute step size "
                << step_norm
                << " < " << absolute_step_tolerance
                << std::endl;
    }
  else if (absolute_step_tolerance)
    {
      std::cout << "  Nonlinear solver absolute step size "
                << step_norm
                << " > " << absolute_step_tolerance
                << std::endl;
    }

  // Is our relative Newton step size small enough?
  if (step_norm / max_solution_norm <
      relative_step_tolerance)
    {
      std::cout << "  Nonlinear solver converged, step " << step_num
                << ", relative step size "
                << (step_norm / max_solution_norm)
                << " < " << relative_step_tolerance
                << std::endl;
    }
  else if (relative_step_tolerance)
    {
      std::cout << "  Nonlinear solver relative step size "
                << (step_norm / max_solution_norm)
                << " > " << relative_step_tolerance
                << std::endl;
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 Open Source Robotics Foundation, 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 <fstream>
#include <math.h>

#include "rclcpp/rclcpp.hpp"

#include "rttest/utils.h"

#include "pendulum_msgs/msg/joint_command.hpp"

// Non real-time safe node for publishing a user-specified pendulum setpoint exactly once

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);

  double command = M_PI / 2;
  if (argc < 2) {
    fprintf(stderr,
      "Command argument not specified. Setting command to 90 degrees (PI/2 radians).\n");
  } else {
    command = atof(argv[1]);
  }

  auto teleop_node = rclcpp::node::Node::make_shared("pendulum_teleop");

  rmw_qos_profile_t qos_profile = rmw_qos_profile_default;
  qos_profile.durability = RMW_QOS_POLICY_TRANSIENT_LOCAL_DURABILITY;
  qos_profile.reliability = RMW_QOS_POLICY_RELIABLE;

  auto pub = teleop_node->create_publisher<pendulum_msgs::msg::JointCommand>(
    "pendulum_setpoint", qos_profile);

  auto msg = std::make_shared<pendulum_msgs::msg::JointCommand>();
  msg->position = command;

  rclcpp::sleep_for(500_ms);
  pub->publish(msg);
  rclcpp::spin_some(teleop_node);
  std::cout << "Teleop node exited." << std::endl;
}
<commit_msg>use <cmath> since it's cpp<commit_after>// Copyright 2015 Open Source Robotics Foundation, 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 <cmath>
#include <fstream>

#include "rclcpp/rclcpp.hpp"

#include "rttest/utils.h"

#include "pendulum_msgs/msg/joint_command.hpp"

// Non real-time safe node for publishing a user-specified pendulum setpoint exactly once

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);

  double command = M_PI / 2;
  if (argc < 2) {
    fprintf(stderr,
      "Command argument not specified. Setting command to 90 degrees (PI/2 radians).\n");
  } else {
    command = atof(argv[1]);
  }

  auto teleop_node = rclcpp::node::Node::make_shared("pendulum_teleop");

  rmw_qos_profile_t qos_profile = rmw_qos_profile_default;
  qos_profile.durability = RMW_QOS_POLICY_TRANSIENT_LOCAL_DURABILITY;
  qos_profile.reliability = RMW_QOS_POLICY_RELIABLE;

  auto pub = teleop_node->create_publisher<pendulum_msgs::msg::JointCommand>(
    "pendulum_setpoint", qos_profile);

  auto msg = std::make_shared<pendulum_msgs::msg::JointCommand>();
  msg->position = command;

  rclcpp::sleep_for(500_ms);
  pub->publish(msg);
  rclcpp::spin_some(teleop_node);
  std::cout << "Teleop node exited." << std::endl;
}
<|endoftext|>