<commit_before>#include <QString>
#include <QtTest>
#include <Arangodbdriver.h>
#include <QueryBuilder.h>
#include <QBSelect.h>

class QueriesTest : public QObject
{
        Q_OBJECT

    public:
        QueriesTest();
        ~QueriesTest();

    private Q_SLOTS:
        void initTestCase();
        void cleanupTestCase();

        void testGetAllDocuments();
        void testLoadMoreResults();
        void testGetDocByWhere();
        void testGetMultipleDocsByWhere();
        void testGetAllDocumentsFromTwoCollections();

    private:
        arangodb::Arangodbdriver driver;
        arangodb::QueryBuilder qb;
        arangodb::Collection * tempCollection = Q_NULLPTR;
        arangodb::Collection * temp2Collection = Q_NULLPTR;
};

QueriesTest::QueriesTest()
{
    tempCollection = driver.createCollection("temp");
    tempCollection->save();

    temp2Collection = driver.createCollection("temp2");
    temp2Collection->save();

    driver.waitUntilFinished(tempCollection, temp2Collection);

    arangodb::Document * doc1 = tempCollection->createDocument();
    doc1->set("test", true);
    arangodb::Document * doc2 = tempCollection->createDocument();
    doc2->set("test", false);
    arangodb::Document * doc3 = tempCollection->createDocument();
    doc3->set("test", true);

    doc1->save();
    doc2->save();
    doc3->save();

    driver.waitUntilFinished(doc1, doc2, doc3);
}

QueriesTest::~QueriesTest()
{
    tempCollection->deleteAll();
    tempCollection->waitUntilDeleted();

    temp2Collection->deleteAll();
    temp2Collection->waitUntilDeleted();
}

void QueriesTest::initTestCase()
{
}

void QueriesTest::cleanupTestCase()
{
}

void QueriesTest::testGetAllDocuments()
{
    auto select = qb.createSelect(QStringLiteral("test"));

    QCOMPARE(select->collections().first(), QStringLiteral("test"));
    QCOMPARE(select->batchSize(), 15);
    QCOMPARE(select->isCounting(), false);

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->count(), 4);
}

void QueriesTest::testLoadMoreResults()
{
    auto select = qb.createSelect(QStringLiteral("test"), 2);

    QCOMPARE(select->collections().first(), QStringLiteral("test"));
    QCOMPARE(select->batchSize(), 2);
    QCOMPARE(select->isCounting(), false);

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), true);
    QCOMPARE(cursor->count(), 2);

    cursor->getMoreData();
    cursor->waitForResult();

    QCOMPARE(cursor->hasErrorOccurred(), false);
    QCOMPARE(cursor->hasMore(), false);
    QCOMPARE(cursor->count(), 4);
}

void QueriesTest::testGetDocByWhere()
{
    auto select = qb.createSelect(QStringLiteral("test"), 2);

    QCOMPARE(select->collections().first(), QStringLiteral("test"));
    QCOMPARE(select->batchSize(), 2);
    QCOMPARE(select->isCounting(), false);

    select->setWhere(QStringLiteral("name"), QStringLiteral("ll"));

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), false);
    QCOMPARE(cursor->count(), 1);
}

void QueriesTest::testGetMultipleDocsByWhere()
{
    auto select = qb.createSelect(QStringLiteral("webuser"), 2);

    QCOMPARE(select->collections().first(), QStringLiteral("webuser"));
    QCOMPARE(select->batchSize(), 2);
    QCOMPARE(select->isCounting(), false);

    QStringList vars;
    vars << "saeschdivara" << "root";
    select->setWhere(QStringLiteral("username"), vars);

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), false);
    QCOMPARE(cursor->count(), 1);
}

void QueriesTest::testGetAllDocumentsFromTwoCollections()
{
    auto select = qb.createSelect(tempCollection->name(), 2);
}

QTEST_MAIN(QueriesTest)

#include "tst_QueriesTest.moc"
<commit_msg>Added testGetAllDocumentsFromTwoCollections<commit_after>#include <QString>
#include <QtTest>
#include <Arangodbdriver.h>
#include <QueryBuilder.h>
#include <QBSelect.h>

class QueriesTest : public QObject
{
        Q_OBJECT

    public:
        QueriesTest();
        ~QueriesTest();

    private Q_SLOTS:
        void initTestCase();
        void cleanupTestCase();

        void testGetAllDocuments();
        void testLoadMoreResults();
        void testGetDocByWhere();
        void testGetMultipleDocsByWhere();
        void testGetAllDocumentsFromTwoCollections();

    private:
        arangodb::Arangodbdriver driver;
        arangodb::QueryBuilder qb;
        arangodb::Collection * tempCollection = Q_NULLPTR;
        arangodb::Collection * temp2Collection = Q_NULLPTR;
};

QueriesTest::QueriesTest()
{
    tempCollection = driver.createCollection("temp");
    tempCollection->save();

    temp2Collection = driver.createCollection("temp2");
    temp2Collection->save();

    driver.waitUntilFinished(tempCollection, temp2Collection);

    arangodb::Document * doc1 = tempCollection->createDocument();
    doc1->set("test", true);
    arangodb::Document * doc2 = tempCollection->createDocument();
    doc2->set("test", false);
    arangodb::Document * doc3 = tempCollection->createDocument();
    doc3->set("test", true);

    doc1->save();
    doc2->save();
    doc3->save();

    driver.waitUntilFinished(doc1, doc2, doc3);

    arangodb::Document * doc4 = temp2Collection->createDocument();
    doc4->set("con", doc1->docID());
    arangodb::Document * doc5 = temp2Collection->createDocument();
    doc5->set("con", doc2->docID());

    doc4->save();
    doc5->save();

    driver.waitUntilFinished(doc4, doc5);
}

QueriesTest::~QueriesTest()
{
    tempCollection->deleteAll();
    tempCollection->waitUntilDeleted();

    temp2Collection->deleteAll();
    temp2Collection->waitUntilDeleted();
}

void QueriesTest::initTestCase()
{
}

void QueriesTest::cleanupTestCase()
{
}

void QueriesTest::testGetAllDocuments()
{
    auto select = qb.createSelect(QStringLiteral("test"));

    QCOMPARE(select->collections().first(), QStringLiteral("test"));
    QCOMPARE(select->batchSize(), 15);
    QCOMPARE(select->isCounting(), false);

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->count(), 4);
}

void QueriesTest::testLoadMoreResults()
{
    auto select = qb.createSelect(QStringLiteral("test"), 2);

    QCOMPARE(select->collections().first(), QStringLiteral("test"));
    QCOMPARE(select->batchSize(), 2);
    QCOMPARE(select->isCounting(), false);

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), true);
    QCOMPARE(cursor->count(), 2);

    cursor->getMoreData();
    cursor->waitForResult();

    QCOMPARE(cursor->hasErrorOccurred(), false);
    QCOMPARE(cursor->hasMore(), false);
    QCOMPARE(cursor->count(), 4);
}

void QueriesTest::testGetDocByWhere()
{
    auto select = qb.createSelect(QStringLiteral("test"), 2);

    QCOMPARE(select->collections().first(), QStringLiteral("test"));
    QCOMPARE(select->batchSize(), 2);
    QCOMPARE(select->isCounting(), false);

    select->setWhere(QStringLiteral("name"), QStringLiteral("ll"));

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), false);
    QCOMPARE(cursor->count(), 1);
}

void QueriesTest::testGetMultipleDocsByWhere()
{
    auto select = qb.createSelect(QStringLiteral("webuser"), 2);

    QCOMPARE(select->collections().first(), QStringLiteral("webuser"));
    QCOMPARE(select->batchSize(), 2);
    QCOMPARE(select->isCounting(), false);

    QStringList vars;
    vars << "saeschdivara" << "root";
    select->setWhere(QStringLiteral("username"), vars);

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), false);
    QCOMPARE(cursor->count(), 1);
}

void QueriesTest::testGetAllDocumentsFromTwoCollections()
{
    auto select = qb.createSelect(tempCollection->name(), 2);
    select->addNewCollection(temp2Collection->name());

    QCOMPARE(select->collections().size(), 2);
    QCOMPARE(select->collections().at(0), QStringLiteral("temp"));
    QCOMPARE(select->collections().at(1), QStringLiteral("temp2"));

    auto cursor = driver.executeSelect(select);
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), true);

    cursor->getMoreData();
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), true);

    cursor->getMoreData();
    cursor->waitForResult();

    QVERIFY2(cursor->hasErrorOccurred() == false, cursor->errorMessage().toLocal8Bit());
    QCOMPARE(cursor->hasMore(), false);
    QCOMPARE(cursor->data().size(), 5);
}

QTEST_MAIN(QueriesTest)

#include "tst_QueriesTest.moc"
<|endoftext|>


<commit_before>/* **********************************************************
 * Copyright (c) 2012 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License, and no later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <windows.h>
#include <objbase.h>
#include <stdlib.h>

// For shell link stuff.
#include <shobjidl.h>
#include <shlguid.h>

#pragma comment(lib, "ole32.lib")

#include "gtest/gtest.h"

// Ensure that CoInitializeEx test comes first, because many of the leaks
// happen once per process, and the callstacks through CoInitializeEx are
// harder to suppress due its tail call.
TEST(OleTest, CoInitializeEx) {
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    ASSERT_TRUE(SUCCEEDED(hr));
    CoUninitialize();
}

TEST(OleTest, CoInitialize) {
    HRESULT hr = CoInitialize(NULL);
    ASSERT_TRUE(SUCCEEDED(hr));
    CoUninitialize();
}

TEST(OleTest, CoCreateInstance) {
    HRESULT hr = CoInitialize(NULL);
    ASSERT_TRUE(SUCCEEDED(hr));

    // Some COM object for creating shortcut files.  We just use it as an
    // arbitrary object that we can create.
    IShellLink* shell_link = NULL;
    hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                          IID_IShellLink, (LPVOID*)&shell_link);
    ASSERT_TRUE(SUCCEEDED(hr));
    shell_link->Release();

    CoUninitialize();
}
<commit_msg>fixes issue 746 + dos2unix on ole_tests_win.cpp + fix build error for ole_tests_win.cpp with VS2005<commit_after>/* **********************************************************
 * Copyright (c) 2012 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License, and no later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#if _MSC_VER <= 1400
# define _WIN32_WINNT 0x0400 /* == NT4 */ /* not set for VS2005 */
#endif

#include <windows.h>
#include <objbase.h>
#include <stdlib.h>

// For shell link stuff.
#include <shobjidl.h>
#include <shlguid.h>

#pragma comment(lib, "ole32.lib")

#include "gtest/gtest.h"

// Ensure that CoInitializeEx test comes first, because many of the leaks
// happen once per process, and the callstacks through CoInitializeEx are
// harder to suppress due its tail call.
TEST(OleTest, CoInitializeEx) {
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    ASSERT_TRUE(SUCCEEDED(hr));
    CoUninitialize();
}

TEST(OleTest, CoInitialize) {
    HRESULT hr = CoInitialize(NULL);
    ASSERT_TRUE(SUCCEEDED(hr));
    CoUninitialize();
}

TEST(OleTest, CoCreateInstance) {
    HRESULT hr = CoInitialize(NULL);
    ASSERT_TRUE(SUCCEEDED(hr));

    // Some COM object for creating shortcut files.  We just use it as an
    // arbitrary object that we can create.
    IShellLink* shell_link = NULL;
    hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                          IID_IShellLink, (LPVOID*)&shell_link);
    ASSERT_TRUE(SUCCEEDED(hr));
    shell_link->Release();

    CoUninitialize();
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>

#ifdef HAVE_FASP
#undef HAVE_FASP
#endif

#include <dune/common/exceptions.hh>

#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
#error This test requires ALUGrid!
#endif

#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/float_cmp.hh>

#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
//#include "elliptic-sipdg-discretization.hh"
//#include "elliptic-swipdg-discretization.hh"

class errors_are_not_as_expected : public Dune::Exception
{
};

typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;

// change this to toggle output
std::ostream& test_out = std::cout;
// std::ostream& test_out = DSC_LOG.devnull();

typedef testing::Types<EllipticTestCase::ESV07<AluConform2dGridType>,
                       EllipticTestCase::LocalThermalBlock<AluConform2dGridType>,
                       EllipticTestCase::ER07<AluConform2dGridType>,
                       EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>,
                       EllipticTestCase::Spe10Model1<AluConform2dGridType>> AluConform2dTestCases;

std::vector<double> truncate_vector(const std::vector<double>& in, const size_t size)
{
  assert(size <= in.size());
  if (size == in.size())
    return in;
  else {
    std::vector<double> out(size);
    for (size_t ii = 0; ii < size; ++ii)
      out[ii] = in[ii];
    return out;
  }
} // ... truncate_vector(...)

template <class TestCase>
struct EllipticCGDiscretization : public ::testing::Test
{
  void produces_correct_results() const
  {
    const TestCase test_case;
    test_case.print_header(test_out);
    test_out << std::endl;
    EllipticCG::EocStudy<TestCase, 1> eoc_study(test_case);
    auto errors = eoc_study.run(test_out);
    for (const auto& norm : eoc_study.provided_norms()) {
      if (!Dune::Stuff::Common::FloatCmp::lt(errors[norm],
                                             truncate_vector(eoc_study.expected_results(norm), errors[norm].size()))) {
        std::stringstream ss;
        Dune::Stuff::Common::print(errors[norm], "errors           (" + norm + ")", ss);
        Dune::Stuff::Common::print(eoc_study.expected_results(norm), "   expected results (" + norm + ")", ss);
        DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
      }
    }
  }
}; // EllipticCGDiscretization

// template< class TestCase >
// struct EllipticSIPDGDiscretization
//  : public ::testing::Test
//{
//  void produces_correct_results() const
//  {
//    if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
//      std::cerr
//          << Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for "
//                                                 "EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!")
//          << std::endl;
//    } else {
//      const TestCase test_case;
//      test_case.print_header(test_out);
//      test_out << std::endl;
//      EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
//      auto errors_1 = eoc_study_1.run(test_out);
//      for (const auto& norm : eoc_study_1.provided_norms()) {
//        if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
//          std::stringstream ss;
//          Dune::Stuff::Common::print(errors_1[norm],                     "errors           (" + norm + ")", ss);
//          Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), "   expected results (" + norm + ")", ss);
//          DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
//        }
//      }
//      test_out << std::endl;
//      EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
//      auto errors_2 = eoc_study_2.run(test_out);
//      for (const auto& norm : eoc_study_2.provided_norms())
//        if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
//          std::stringstream ss;
//          Dune::Stuff::Common::print(errors_2[norm],                     "errors           (" + norm + ")", ss);
//          Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), "   expected results (" + norm + ")", ss);
//          DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
//        }
//    }
//  }
//}; // EllipticSIPDGDiscretization

// template< class TestCase >
// struct EllipticSWIPDGDiscretization
//  : public ::testing::Test
//{
//  void produces_correct_results() const
//  {
//    const TestCase test_case;
//    test_case.print_header(test_out);
//    test_out << std::endl;
//    EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
//    auto errors_1 = eoc_study_1.run(test_out);
//    for (const auto& norm : eoc_study_1.provided_norms()) {
//      if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
//        std::stringstream ss;
//        Dune::Stuff::Common::print(errors_1[norm],                     "errors           (" + norm + ")", ss);
//        Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), "   expected results (" + norm + ")", ss);
//        DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
//      }
//    }
//    test_out << std::endl;
//    EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
//    auto errors_2 = eoc_study_2.run(test_out);
//    for (const auto& norm : eoc_study_2.provided_norms())
//      if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
//        std::stringstream ss;
//        Dune::Stuff::Common::print(errors_2[norm],                     "errors           (" + norm + ")", ss);
//        Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), "   expected results (" + norm + ")", ss);
//        DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
//      }
//  }
//};

TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results)
{
  this->produces_correct_results();
}

// TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
//  this->produces_correct_results();
//}

// TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
//  this->produces_correct_results();
//}

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "\nDune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << "\n" << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
}
<commit_msg>[tests.elliptic-discretizations] reenabled sipdg<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>

#ifdef HAVE_FASP
#undef HAVE_FASP
#endif

#include <dune/common/exceptions.hh>

#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
#error This test requires ALUGrid!
#endif

#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/float_cmp.hh>

#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
//#include "elliptic-swipdg-discretization.hh"

class errors_are_not_as_expected : public Dune::Exception
{
};

typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;

// change this to toggle output
std::ostream& test_out = std::cout;
// std::ostream& test_out = DSC_LOG.devnull();

typedef testing::Types<EllipticTestCase::ESV07<AluConform2dGridType>,
                       EllipticTestCase::LocalThermalBlock<AluConform2dGridType>,
                       EllipticTestCase::ER07<AluConform2dGridType>,
                       EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>,
                       EllipticTestCase::Spe10Model1<AluConform2dGridType>> AluConform2dTestCases;

std::vector<double> truncate_vector(const std::vector<double>& in, const size_t size)
{
  assert(size <= in.size());
  if (size == in.size())
    return in;
  else {
    std::vector<double> out(size);
    for (size_t ii = 0; ii < size; ++ii)
      out[ii] = in[ii];
    return out;
  }
} // ... truncate_vector(...)

template <class TestCase>
struct EllipticCGDiscretization : public ::testing::Test
{
  void produces_correct_results() const
  {
    const TestCase test_case;
    test_case.print_header(test_out);
    test_out << std::endl;
    EllipticCG::EocStudy<TestCase, 1> eoc_study(test_case);
    auto errors = eoc_study.run(test_out);
    for (const auto& norm : eoc_study.provided_norms()) {
      if (!Dune::Stuff::Common::FloatCmp::lt(errors[norm],
                                             truncate_vector(eoc_study.expected_results(norm), errors[norm].size()))) {
        std::stringstream ss;
        Dune::Stuff::Common::print(errors[norm], "errors           (" + norm + ")", ss);
        Dune::Stuff::Common::print(eoc_study.expected_results(norm), "   expected results (" + norm + ")", ss);
        DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
      }
    }
  }
}; // EllipticCGDiscretization

template <class TestCase>
struct EllipticSIPDGDiscretization : public ::testing::Test
{
  void produces_correct_results() const
  {
    if (std::is_same<TestCase, EllipticTestCase::Spe10Model1<Dune::ALUConformGrid<2, 2>>>::value) {
      std::cerr << Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for "
                                                       "EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!")
                << std::endl;
    } else {
      const TestCase test_case;
      test_case.print_header(test_out);
      test_out << std::endl;
      EllipticSIPDG::EocStudy<TestCase, 1> eoc_study_1(test_case);
      auto errors_1 = eoc_study_1.run(test_out);
      for (const auto& norm : eoc_study_1.provided_norms())
        if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
          std::stringstream ss;
          Dune::Stuff::Common::print(errors_1[norm], "errors           (" + norm + ")", ss);
          Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), "   expected results (" + norm + ")", ss);
          DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
        }
      test_out << std::endl;
      EllipticSIPDG::EocStudy<TestCase, 2> eoc_study_2(test_case);
      auto errors_2 = eoc_study_2.run(test_out);
      for (const auto& norm : eoc_study_2.provided_norms())
        if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
          std::stringstream ss;
          Dune::Stuff::Common::print(errors_2[norm], "errors           (" + norm + ")", ss);
          Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), "   expected results (" + norm + ")", ss);
          DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
        }
    }
  }
}; // EllipticSIPDGDiscretization

// template< class TestCase >
// struct EllipticSWIPDGDiscretization
//  : public ::testing::Test
//{
//  void produces_correct_results() const
//  {
//    const TestCase test_case;
//    test_case.print_header(test_out);
//    test_out << std::endl;
//    EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
//    auto errors_1 = eoc_study_1.run(test_out);
//    for (const auto& norm : eoc_study_1.provided_norms()) {
//      if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
//        std::stringstream ss;
//        Dune::Stuff::Common::print(errors_1[norm],                     "errors           (" + norm + ")", ss);
//        Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), "   expected results (" + norm + ")", ss);
//        DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
//      }
//    }
//    test_out << std::endl;
//    EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
//    auto errors_2 = eoc_study_2.run(test_out);
//    for (const auto& norm : eoc_study_2.provided_norms())
//      if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
//        std::stringstream ss;
//        Dune::Stuff::Common::print(errors_2[norm],                     "errors           (" + norm + ")", ss);
//        Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), "   expected results (" + norm + ")", ss);
//        DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
//      }
//  }
//};

TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results)
{
  this->produces_correct_results();
}

TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results)
{
  this->produces_correct_results();
}

// TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
//  this->produces_correct_results();
//}

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "\nDune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << "\n" << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
}
<|endoftext|>


<commit_before>//
// PROJECT CHRONO - http://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.
//
///////////////////////////////////////////////////
//
//   A tracked vehicle, M113, built and simulated using the trackedVehicle library.
//   Build the vehicle using a hierarchy of subsystems.
//   Simulate by GUI input to an irrlicht EventReceiver.
//    - similar to demo_tracks:
//     - model track shoes with simple or complex collision geometry
//     - using clones of collision shapes
//     - use  SetFamilyMaskNoCollisionWithFamily, SetFamily etc., to avoid collisions between different families of bodies.
//
//	 Author: Justin Madsen, (c) 2014
///////////////////////////////////////////////////

#include "physics/ChSystem.h"
#include "particlefactory/ChParticleEmitter.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
#include "unit_IRRLICHT/ChIrrApp.h"
#include "subsys/driver/ChIrrGuiTrack.h"

#include "subsys/trackVehicle/trackVehicle.h"

// Use the main namespace of Chrono, and other chrono namespaces

using namespace chrono;
using namespace chrono::geometry;

// Use the main namespaces of Irrlicht
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

#include <irrlicht.h>

int main(int argc, char* argv[])
{
  // no system to create, it's in the trackVehicle

	// ..the tank (this class - see above - is a 'set' of bodies and links, automatically added at creation)
	TrackVehicle vehicle("name");

	// Create the Irrlicht visualization applicaiton
	ChIrrApp application(&vehicle, L"Modeling a simplified   tank",core::dimension2d<u32>(800,600),false, true);

	// Easy shortcuts to add logo, camera, lights and sky in Irrlicht scene:
	ChIrrWizard::add_typical_Logo(application.GetDevice());
	ChIrrWizard::add_typical_Sky(application.GetDevice());
	ChIrrWizard::add_typical_Lights(application.GetDevice());
	ChIrrWizard::add_typical_Camera(application.GetDevice(), core::vector3df(0,0,-6), core::vector3df(-2,2,0));

	// ground plate
  ChSharedPtr<ChBody> ground(new ChBodyEasyBox(60.0, 1.0, 100.0, 1000.0, true, true);

	ground->SetFriction(1.0);
  my_system.Add(ground);  // add this body to the system

	// ..some obstacles on the ground:
	for (int i=0; i<50; i++)
	{
		ChBodySceneNode* my_obstacle = (ChBodySceneNode*)addChBodySceneNode_easyBox(
											&my_system, application.GetSceneManager(),
											3.0,
											ChVector<>(-6+6*ChRandom(),2+1*ChRandom(), 6*ChRandom()),
											Q_from_AngAxis(ChRandom()*CH_C_PI, VECT_Y),
											ChVector<>(0.6*(1-0.4*ChRandom()),
											           0.08,
													   0.3*(1-0.4*ChRandom()) ) );
		my_obstacle->addShadowVolumeSceneNode();
	}

	//
	// USER INTERFACE
	//

	// Create some graphical-user-interface (GUI) items to show on the screen.
	// This requires an event receiver object.
	MyEventReceiver receiver(&application, vehicle);
	  // note how to add the custom event receiver to the default interface:
	application.SetUserEventReceiver(&receiver);

	//
	// SETTINGS
	//

	my_system.SetIterLCPmaxItersSpeed(100); // the higher, the easier to keep the constraints 'mounted'.
	my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);

	//
	// THE SOFT-REAL-TIME CYCLE, SHOWING THE SIMULATION
	//

	application.SetStepManage(true);
	application.SetTimestep(0.03);
	application.SetTryRealtime(true);

	while(application.GetDevice()->run())
	{
		// Irrlicht must prepare frame to draw
		application.GetVideoDriver()->beginScene(true, true, SColor(255,140,161,192));

		// .. draw solid 3D items (boxes, cylinders, shapes) belonging to Irrlicht scene, if any
		application.DrawAll();

		// .. draw also a grid (rotated so that it's horizontal)
		ChIrrTools::drawGrid(application.GetVideoDriver(), 2, 2, 30,30,
			ChCoordsys<>(ChVector<>(0,0.01,0), Q_from_AngX(CH_C_PI_2) ),
			video::SColor(255, 60,60,60), true);

		// HERE CHRONO INTEGRATION IS PERFORMED:

		application.DoStep();

		application.GetVideoDriver()->endScene();
	}

	if (mytank) delete mytank;

	return 0;
}

<commit_msg>updating the includes to use with a tracked vehicle demo<commit_after>//
// PROJECT CHRONO - http://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.
//
///////////////////////////////////////////////////
//
//   A tracked vehicle, M113, built and simulated using the trackedVehicle library.
//   Build the vehicle using a hierarchy of subsystems.
//   Simulate by GUI input to an irrlicht EventReceiver.
//    - similar to demo_tracks:
//     - model track shoes with simple or complex collision geometry
//     - using clones of collision shapes
//     - use  SetFamilyMaskNoCollisionWithFamily, SetFamily etc., to avoid collisions between different families of bodies.
//
//	 Author: Justin Madsen, (c) 2014
///////////////////////////////////////////////////

#include "physics/ChSystem.h"
// #include "particlefactory/ChParticleEmitter.h"

#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"

#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
/*
#if IRRLICHT_ENABLED
*/
#include "unit_IRRLICHT/ChIrrApp.h"
#include "subsys/driver/ChIrrGuiTrack.h"
 /*
 # define USE_IRRLICHT
#endif
 */
#include "subsys/trackVehicle/trackVehicle.h"

// Use the main namespace of Chrono
using namespace chrono;

// Use the main namespaces of Irrlicht
using namespace irr;
using namespace core;

// // Initial vehicle position
ChVector<> initLoc(0, 1.0, 0);
// Initial vehicle orientation
ChQuaternion<> initRot(1, 0, 0, 0);
//ChQuaternion<> initRot(0.866025, 0, 0, 0.5);
//ChQuaternion<> initRot(0.7071068, 0, 0, 0.7071068);
//ChQuaternion<> initRot(0.25882, 0, 0, 0.965926);
//ChQuaternion<> initRot(0, 0, 0, 1);

// Simulation step size
double step_size = 0.001;

// Time interval between two render frames
int FPS = 50;
double render_step_size = 1.0 / FPS;   // FPS = 50

// #ifdef USE_IRRLICHT
  // Point on chassis tracked by the camera
  ChVector<> trackPoint(0.0, 0.0, .75);
  /*
#else
  double tend = 20.0;

  const std::string out_dir = "../HMMWV9";
  const std::string pov_dir = out_dir + "/POVRAY";
#endif
  */

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

  // no system to create, it's in the TrackVehicle
	TrackVehicle vehicle("name");

  vehicle.Initialize(ChCoordsys<>(initLoc, initRot));

/*
#ifdef USE_IRRLICHT
*/
	// Create the Irrlicht visualization applicaiton
  ChIrrApp application(&vehicle,
                      L"HMMWV 9-body demo",
                      dimension2d<u32>(1000, 800),
                      false,
                      true);

  // make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
  std::string mtexturedir = GetChronoDataFile("skybox/");
  std::string str_lf = mtexturedir + "sky_lf.jpg";
  std::string str_up = mtexturedir + "sky_up.jpg";
  std::string str_dn = mtexturedir + "sky_dn.jpg";
  irr::video::ITexture* map_skybox_side =
      application.GetVideoDriver()->getTexture(str_lf.c_str());
  irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
      application.GetVideoDriver()->getTexture(str_up.c_str()),
      application.GetVideoDriver()->getTexture(str_dn.c_str()),
      map_skybox_side,
      map_skybox_side,
      map_skybox_side,
      map_skybox_side);
  mbox->setRotation( irr::core::vector3df(0,0,0));

  bool do_shadows = true; // shadow map is experimental
  irr::scene::ILightSceneNode* mlight = 0;

  if (do_shadows)
  {
    mlight = application.AddLightWithShadow(
      irr::core::vector3df(10.f, 30.f, 60.f),
      irr::core::vector3df(0.f, 0.f, 0.f),
      150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);
  }
  else
  {
    application.AddTypicalLights(
      irr::core::vector3df(30.f, -30.f, 100.f),
      irr::core::vector3df(30.f, 50.f, 100.f),
      250, 130);
  }

  application.SetTimestep(step_size);

  ChIrrGuiTrack driver();

	// ground plate
  ChSharedPtr<ChBody> ground(new ChBodyEasyBox(60.0, 1.0, 100.0, 1000.0, true, true);

	ground->SetFriction(1.0);
  my_system.Add(ground);  // add this body to the system

	// ..some obstacles on the ground:
	for (int i=0; i<50; i++)
	{
		ChBodySceneNode* my_obstacle = (ChBodySceneNode*)addChBodySceneNode_easyBox(
											&my_system, application.GetSceneManager(),
											3.0,
											ChVector<>(-6+6*ChRandom(),2+1*ChRandom(), 6*ChRandom()),
											Q_from_AngAxis(ChRandom()*CH_C_PI, VECT_Y),
											ChVector<>(0.6*(1-0.4*ChRandom()),
											           0.08,
													   0.3*(1-0.4*ChRandom()) ) );
		my_obstacle->addShadowVolumeSceneNode();
	}

	//
	// USER INTERFACE
	//

	// Create some graphical-user-interface (GUI) items to show on the screen.
	// This requires an event receiver object.
	MyEventReceiver receiver(&application, vehicle);
	  // note how to add the custom event receiver to the default interface:
	application.SetUserEventReceiver(&receiver);

	//
	// SETTINGS
	//

	my_system.SetIterLCPmaxItersSpeed(100); // the higher, the easier to keep the constraints 'mounted'.
	my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);

	//
	// THE SOFT-REAL-TIME CYCLE, SHOWING THE SIMULATION
	//

	application.SetStepManage(true);
	application.SetTimestep(0.03);
	application.SetTryRealtime(true);

	while(application.GetDevice()->run())
	{
		// Irrlicht must prepare frame to draw
		application.GetVideoDriver()->beginScene(true, true, SColor(255,140,161,192));

		// .. draw solid 3D items (boxes, cylinders, shapes) belonging to Irrlicht scene, if any
		application.DrawAll();

		// .. draw also a grid (rotated so that it's horizontal)
		ChIrrTools::drawGrid(application.GetVideoDriver(), 2, 2, 30,30,
			ChCoordsys<>(ChVector<>(0,0.01,0), Q_from_AngX(CH_C_PI_2) ),
			video::SColor(255, 60,60,60), true);

		// HERE CHRONO INTEGRATION IS PERFORMED:

		application.DoStep();

		application.GetVideoDriver()->endScene();
	}

	if (mytank) delete mytank;

	return 0;
}

<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_WALK_HH_INCLUDED
#define DUNE_STUFF_WALK_HH_INCLUDED

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#else
 #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#include <dune/common/static_assert.hh>
#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/grid/common/geometry.hh>
#include <vector>
#include <boost/format.hpp>

namespace Dune {
namespace Stuff {
namespace Grid {

using namespace Dune::Stuff::Common;

/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
 **/
struct GridWalkDummyFunctor {
  GridWalkDummyFunctor(){}

  template < class Entity >
  void operator() ( const Entity&, const int) const
  {}
  template < class Entity, class Intersection >
  void operator() ( const Entity&, const Intersection&) const
  {}
};

namespace {
  /** \brief global \ref GridWalkDummyFunctor instance
   **/
  const GridWalkDummyFunctor gridWalkDummyFunctor;
}

/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
 *  \todo allow stacking of functor to save gridwalks?
 *  \tparam GridViewType any \ref GridView interface compliant type
 *  \tparam codim determines the codim of the Entities that are iterated on
 **/
template < class GridViewImp, int codim = 0 >
class GridWalk {
  typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
  GridWalk ( const GridViewType& gp )
    : gridView_( gp )
  {}

  /** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
   *  \param intersectionFunctor is applied on all Intersections of all codim 0 entities
   *        presented by \var gridView_
   *  \note only instantiable for codim == 0
   */
  template < class EntityFunctor, class IntersectionFunctor >
  void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
  {
    dune_static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
    for (const auto& entity : Common::viewRange(gridView_)) {
      const int entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
      for (const auto& intersection : intersectionRange(gridView_, entity)) {
        intersectionFunctor( entity, intersection);
      }
    }
  }

  /** \param entityFunctor is applied on all codim entities presented by \var gridView_
   *  \note only instantiable for codim < GridView::dimension
   */
  template < class EntityFunctor >
  void operator () ( EntityFunctor& entityFunctor ) const
  {
    dune_static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
    for (const auto& entity : viewRange(gridView_)) {
      const int entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
    }
  }

  template< class Functor >
  void walkCodim0(Functor& f) const DUNE_DEPRECATED_MSG("use operator()(Functor) instead ");

private:
  const GridViewType& gridView_;
};

template< class V, int i >
template< class Functor >
void GridWalk<V,i>::walkCodim0(Functor& f) const {
  this->operator()(f);
}

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // ifndef DUNE_STUFF_WALK_HH_INCLUDED
/** Copyright (c) 2012, Felix Albrecht, Rene Milk
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<commit_msg>[grid] adds GridWalk generator function<commit_after>#ifndef DUNE_STUFF_WALK_HH_INCLUDED
#define DUNE_STUFF_WALK_HH_INCLUDED

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#else
 #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#include <dune/common/static_assert.hh>
#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/grid/common/geometry.hh>
#include <vector>
#include <boost/format.hpp>

namespace Dune {
namespace Stuff {
namespace Grid {

using namespace Dune::Stuff::Common;

/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
 **/
struct GridWalkDummyFunctor {
  GridWalkDummyFunctor(){}

  template < class Entity >
  void operator() ( const Entity&, const int) const
  {}
  template < class Entity, class Intersection >
  void operator() ( const Entity&, const Intersection&) const
  {}
};

namespace {
  /** \brief global \ref GridWalkDummyFunctor instance
   **/
  const GridWalkDummyFunctor gridWalkDummyFunctor;
}

/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
 *  \todo allow stacking of functor to save gridwalks?
 *  \tparam GridViewType any \ref GridView interface compliant type
 *  \tparam codim determines the codim of the Entities that are iterated on
 **/
template < class GridViewImp, int codim = 0 >
class GridWalk {
  typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
  GridWalk ( const GridViewType& gp )
    : gridView_( gp )
  {}

  /** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
   *  \param intersectionFunctor is applied on all Intersections of all codim 0 entities
   *        presented by \var gridView_
   *  \note only instantiable for codim == 0
   */
  template < class EntityFunctor, class IntersectionFunctor >
  void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
  {
    dune_static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
    for (const auto& entity : Common::viewRange(gridView_)) {
      const int entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
      for (const auto& intersection : intersectionRange(gridView_, entity)) {
        intersectionFunctor( entity, intersection);
      }
    }
  }

  /** \param entityFunctor is applied on all codim entities presented by \var gridView_
   *  \note only instantiable for codim < GridView::dimension
   */
  template < class EntityFunctor >
  void operator () ( EntityFunctor& entityFunctor ) const
  {
    dune_static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
    for (const auto& entity : viewRange(gridView_)) {
      const int entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
    }
  }

  template< class Functor >
  void walkCodim0(Functor& f) const DUNE_DEPRECATED_MSG("use operator()(Functor) instead ");

private:
  const GridViewType& gridView_;
};

template< class V, int i >
template< class Functor >
void GridWalk<V,i>::walkCodim0(Functor& f) const {
  this->operator()(f);
}

//!
template <class ViewImp, int codim = 0>
GridWalk< Dune::GridView<ViewImp>, codim > make_gridwalk(const Dune::GridView<ViewImp>& view) {
    return GridWalk< Dune::GridView<ViewImp>, codim >(view);
}

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // ifndef DUNE_STUFF_WALK_HH_INCLUDED
/** Copyright (c) 2012, Felix Albrecht, Rene Milk
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>

#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"

using namespace std;
using namespace BALL;

int main (int argc, char **argv)
{
	// instantiate CommandlineParser object supplying
	// - tool name
	// - short description
	// - version string
	// - build date
	// - category
	CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");

	// we register an input file parameter
	// - CLI switch
	// - description
	// - Inputfile
	// - required
	parpars.registerParameter("i_dcd", "input dcd-file", INFILE, true);
	parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);

	// we register an output file parameter
	// - description
	// - Outputfile
	// - required
	parpars.registerParameter("o", "output dcd-file name for first solution", STRING, true, "", true);

	parpars.registerParameter("o_id", "output id", STRING, true, "", true);

	parpars.registerParameter("o_dir", "output directory for 2nd to last solution", STRING, true, "", true);

	// register String parameter for supplying max number of solutions
	parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
	parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);

	// choice of atom rmsd scope
	parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
	list<String> rmsd_levels;
	rmsd_levels.push_back("C_ALPHA");
	//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
	rmsd_levels.push_back("BACKBONE");
	rmsd_levels.push_back("ALL_ATOMS");
	parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);

  // the manual
	String man = "This tool computes clusters of docking poses given as conformation set using a complete linkage algorithm.\n\nParameters are the input ConformationSet (-i_dcd), one corresponding pdb file (-i_pdb) and a naming schema for the results (-o). Optional parameters the minimal rmsd between the final clusters  (-rmsd_cutoff) and the scope/level of detail of the rmsd computation (-rmsd_scope).\n\nOutput of this tool is a number of dcd files each containing one ConformationSet.";

	parpars.setToolManual(man);

	// here we set the types of I/O files, for example sdf is also allowed
	parpars.setSupportedFormats("i_dcd","dcd");
	parpars.setSupportedFormats("i_pdb","pdb");
	parpars.setSupportedFormats("o","dcd");

	parpars.parse(argc, argv);

	//////////////////////////////////////////////////

	// read the input
	PDBFile pdb;
	pdb.open(parpars.get("i_pdb"));
	System sys;
	pdb.read(sys);

	ConformationSet cs;
	cs.setup(sys);
	cs.readDCDFile(parpars.get("i_dcd"));
	cs.resetScoring();

	PoseClustering pc;

	if (parpars.has("rmsd_cutoff"))
	{
		float rmsd = parpars.get("rmsd_cutoff").toInt();
		pc.options.setReal(PoseClustering::Option::RMSD_THRESHOLD, rmsd);
	}

	if (parpars.has("rmsd_scope"))
	{
		String scope = parpars.get("rmsd_scope");
		if (scope == "C_ALPHA")
			pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::C_ALPHA);
		else if (scope == "BACKBONE")
			pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::BACKBONE);
		else if (scope == "ALL_ATOMS")
			pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::ALL_ATOMS);
	}

	pc.setConformationSet(&cs);

	pc.compute();

	Size num_clusters = pc.getNumberOfClusters();

	for (Size i = 0; i < num_clusters; i++)
	{
		Log << "   Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;

		boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);

		String outfile_name = (i == 0) ? String(parpars.get("o"))
			                             : String(parpars.get("o_dir")) + "/primary_"
			                               + String(parpars.get("o_id"))  + "_cluster" + String(i)
			                               + "_visible_dcd";
		//Log << "   Writing solution " << String(i) << " as " << outfile_name << endl;
		//	GenericMolFile* outfile = MolFileFactory::open(outfile_name, ios::out);

		//DCD2File outfile(outfile_name, ios::out);
		//outfile << new_cs;
		//outfile.close();

		new_cs->writeDCDFile(outfile_name);
	}

	Log << "done." << endl;

	return 0;
}

<commit_msg>added parameter for tool DockPoseClustering<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>

#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"

using namespace std;
using namespace BALL;

int main (int argc, char **argv)
{
	// instantiate CommandlineParser object supplying
	// - tool name
	// - short description
	// - version string
	// - build date
	// - category
	CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");

	// we register an input file parameter
	// - CLI switch
	// - description
	// - Inputfile
	// - required
	parpars.registerParameter("i_dcd", "input dcd-file", INFILE, true);
	parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);

	// we register an output file parameter
	// - description
	// - Outputfile
	// - required
	parpars.registerParameter("o", "output dcd-file name for first solution ", STRING, true, "", true);

	parpars.registerParameter("o_id", "output id ", STRING, true, "", true);

	parpars.registerParameter("o_dir", "output directory for 2nd to last solution ", STRING, true, "", true);

	parpars.registerParameter("o_dcd", "output directory for the reduced cluster set (one structure per final cluster) ", STRING, false, "", true);

	// register String parameter for supplying minimal rmsd between clusters
	parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
	parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);

	// choice of atom rmsd scope
	parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
	list<String> rmsd_levels;
	rmsd_levels.push_back("C_ALPHA");
	//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
	rmsd_levels.push_back("BACKBONE");
	rmsd_levels.push_back("ALL_ATOMS");
	parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);

  // the manual
	String man = "This tool computes clusters of docking poses given as conformation set using a complete linkage algorithm.\n\nParameters are the input ConformationSet (-i_dcd), one corresponding pdb file (-i_pdb) and a naming schema for the results (-o). Optional parameters are the minimal rmsd between the final clusters  (-rmsd_cutoff) and the scope/level of detail of the rmsd computation (-rmsd_scope). The optional parameter (-o_dcd)\n\nOutput of this tool is a number of dcd files each containing one ConformationSet.";

	parpars.setToolManual(man);

	// here we set the types of I/O files
	parpars.setSupportedFormats("i_dcd","dcd");
	parpars.setSupportedFormats("i_pdb","pdb");
	parpars.setSupportedFormats("o","dcd");
	parpars.setSupportedFormats("o_dcd","dcd");

	parpars.parse(argc, argv);

	//////////////////////////////////////////////////

	// read the input
	PDBFile pdb;
	pdb.open(parpars.get("i_pdb"));
	System sys;
	pdb.read(sys);

	ConformationSet cs;
	cs.setup(sys);
	cs.readDCDFile(parpars.get("i_dcd"));
	cs.resetScoring();

	PoseClustering pc;

	if (parpars.has("rmsd_cutoff"))
	{
		float rmsd = parpars.get("rmsd_cutoff").toInt();
		pc.options.setReal(PoseClustering::Option::RMSD_THRESHOLD, rmsd);
	}

	if (parpars.has("rmsd_scope"))
	{
		String scope = parpars.get("rmsd_scope");
		if (scope == "C_ALPHA")
			pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::C_ALPHA);
		else if (scope == "BACKBONE")
			pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::BACKBONE);
		else if (scope == "ALL_ATOMS")
			pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::RMSDLevelOfDetail::ALL_ATOMS);
	}

	pc.setConformationSet(&cs);

	pc.compute();

	Size num_clusters = pc.getNumberOfClusters();

	for (Size i = 0; i < num_clusters; i++)
	{
		Log << "   Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;

		boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);

		String outfile_name = (i == 0) ? String(parpars.get("o"))
			                             : String(parpars.get("o_dir")) + "/primary_"
			                               + String(parpars.get("o_id"))  + "_cluster" + String(i)
			                               + "_visible_dcd";
		//Log << "   Writing solution " << String(i) << " as " << outfile_name << endl;

		new_cs->writeDCDFile(outfile_name);
	}

	if (parpars.has("o_dcd"))
	{
		String outfile_name = String(parpars.get("o_dcd"));
		boost::shared_ptr<ConformationSet> cs = pc.getReducedConformationSet();
		cs->writeDCDFile(outfile_name);
	}

	Log << "done." << endl;

	return 0;
}

<|endoftext|>


<commit_before>#include <iterator>

#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "featureiterator.h"

using namespace Ilwis;

FeatureIterator::FeatureIterator(const IFeatureCoverage& fcoverage) : _fcoverage(fcoverage), _isInitial(true), _trackCounter(0),_flow(fFEATURES)
{
}

FeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, const Box3D<double>& envelope) :
    _fcoverage(fcoverage),
    _isInitial(true),
    _envelope(envelope),
    _trackCounter(0),
    _flow(fFEATURES)
{

}

FeatureIterator::FeatureIterator(const FeatureIterator &iter)
{
    _fcoverage = iter._fcoverage;
    _isInitial = iter._isInitial;
    _iterFeatures = iter._iterFeatures;
    _trackCounter = iter._trackCounter;
    _flow = iter._flow;
}

FeatureIterator &FeatureIterator::operator ++()
{
    if (!init()){
        move();
    }
    return *this;
}

FeatureIterator FeatureIterator::operator ++(int)
{
    init();
    FeatureIterator temp(*this);
    if(!move())
        return end();
    return temp;
}

FeatureIterator &FeatureIterator::operator +(int distance)
{
    init();
    _iterFeatures = _iterFeatures + distance;
    return *this;

}

FeatureIterator &FeatureIterator::operator -(int distance)
{
    init();
    _iterFeatures = _iterFeatures - distance;
    return *this;
}

bool FeatureIterator::operator ==(const FeatureIterator &iter)
{
    return _iterFeatures == iter._iterFeatures;
}

bool FeatureIterator::operator !=(const FeatureIterator &iter)
{
       return _iterFeatures != iter._iterFeatures;
}

FeatureInterface &FeatureIterator::operator *()
{
    init();
    _proxy.setProxy(*_iterFeatures, _trackCounter);
    return _proxy;
}

FeatureIterator FeatureIterator::end() const
{
    FeatureIterator temp(*this);
    temp._iterFeatures = _fcoverage->_features.end();
    return temp;
}

void FeatureIterator::flow(FeatureIterator::Flow f)
{
    _flow = f;
}

bool FeatureIterator::init()
{
    if ( _isInitial)     {
        _isInitial = false;
        _fcoverage->connector()->loadBinaryData(_fcoverage.ptr());
        if ( _fcoverage->_features.size() > 0 ) {
            _iterFeatures = _fcoverage->_features.begin();
            _trackCounter = 0;
        }
    } else
        return false;
    return true;
}

bool FeatureIterator::move() {
    if ( _flow == fFEATURES) {
        ++_iterFeatures;
        if ( _iterFeatures == _fcoverage->_features.end()) {
            _iterFeatures = _fcoverage->_features.begin();
            ++_trackCounter;
        }
        while((*_iterFeatures)->_track.size() < _trackCounter) {
            ++_iterFeatures;
            if (_iterFeatures == _fcoverage->_features.end())
                return false;
        }
    } else if (_flow == fTRACK) {
        ++_trackCounter;
        if ( _trackCounter >= (*_iterFeatures)->_track.size()) {
            ++_iterFeatures;
            _trackCounter = 0;
            if ( _iterFeatures == _fcoverage->_features.end())
                return false;
        }
    }
    return true;

}
<commit_msg>added guard<commit_after>#include <iterator>

#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "featureiterator.h"

using namespace Ilwis;

FeatureIterator::FeatureIterator(const IFeatureCoverage& fcoverage) : _fcoverage(fcoverage), _isInitial(true), _trackCounter(0),_flow(fFEATURES)
{
}

FeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, const Box3D<double>& envelope) :
    _fcoverage(fcoverage),
    _isInitial(true),
    _envelope(envelope),
    _trackCounter(0),
    _flow(fFEATURES)
{

}

FeatureIterator::FeatureIterator(const FeatureIterator &iter)
{
    _fcoverage = iter._fcoverage;
    _isInitial = iter._isInitial;
    _iterFeatures = iter._iterFeatures;
    _trackCounter = iter._trackCounter;
    _flow = iter._flow;
}

FeatureIterator &FeatureIterator::operator ++()
{
    if (!init()){
        move();
    }
    return *this;
}

FeatureIterator FeatureIterator::operator ++(int)
{
    init();
    FeatureIterator temp(*this);
    if(!move())
        return end();
    return temp;
}

FeatureIterator &FeatureIterator::operator +(int distance)
{
    init();
    _iterFeatures = _iterFeatures + distance;
    return *this;

}

FeatureIterator &FeatureIterator::operator -(int distance)
{
    init();
    _iterFeatures = _iterFeatures - distance;
    return *this;
}

bool FeatureIterator::operator ==(const FeatureIterator &iter)
{
    return _iterFeatures == iter._iterFeatures;
}

bool FeatureIterator::operator !=(const FeatureIterator &iter)
{
       return _iterFeatures != iter._iterFeatures;
}

FeatureInterface &FeatureIterator::operator *()
{
    init();
    _proxy.setProxy(*_iterFeatures, _trackCounter);
    return _proxy;
}

FeatureIterator FeatureIterator::end() const
{
    FeatureIterator temp(*this);
    temp._iterFeatures = _fcoverage->_features.end();
    return temp;
}

void FeatureIterator::flow(FeatureIterator::Flow f)
{
    _flow = f;
}

bool FeatureIterator::init()
{
    if ( _isInitial)     {
        _isInitial = false;
        bool ok = _fcoverage->connector()->loadBinaryData(_fcoverage.ptr());
        if (!ok)
            return false;
        if ( _fcoverage->_features.size() > 0 ) {
            _iterFeatures = _fcoverage->_features.begin();
            _trackCounter = 0;
        }
    } else
        return false;
    return true;
}

bool FeatureIterator::move() {
    if ( _flow == fFEATURES) {
        ++_iterFeatures;
        if ( _iterFeatures == _fcoverage->_features.end()) {
            _iterFeatures = _fcoverage->_features.begin();
            ++_trackCounter;
        }
        while((*_iterFeatures)->_track.size() < _trackCounter) {
            ++_iterFeatures;
            if (_iterFeatures == _fcoverage->_features.end())
                return false;
        }
    } else if (_flow == fTRACK) {
        ++_trackCounter;
        if ( _trackCounter >= (*_iterFeatures)->_track.size()) {
            ++_iterFeatures;
            _trackCounter = 0;
            if ( _iterFeatures == _fcoverage->_features.end())
                return false;
        }
    }
    return true;

}
<|endoftext|>


<commit_before>#include <robocup2Dsim/common/action.hpp>
#include <robocup2Dsim/common/action.capnp.h>
#include <capnp/message.h>
#include <gtest/gtest.h>
#include <turbo/memory/slab_allocator.hpp>
#include <turbo/memory/slab_allocator.hxx>
#include <robocup2Dsim/runtime/db_access.hpp>
#include <robocup2Dsim/engine/physics.hxx>
#include <robocup2Dsim/engine/inventory.hxx>

namespace rco = robocup2Dsim::common;
namespace ren = robocup2Dsim::engine;
namespace red = robocup2Dsim::engine::dynamics;
namespace rru = robocup2Dsim::runtime;

TEST(action_test, local_allocator_basic)
{
    EXPECT_TRUE(rru::update_local_db().component_allocator().in_configured_range(4U));
}

TEST(action_test, act_move_foot_basic)
{
    ren::energy original_energy1{rco::MoveFootAction::MAX_COST};
    ren::inventory inventory1({0U, 100U});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{original_energy1.quantity};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::success,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "failed to act";
    EXPECT_NE(original_energy1.quantity, stock1.quantity) << "energy stock quantity is the same after successful action";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
	    << "action had no effect on simulation";
}
<commit_msg>added more test cases for MoveFootAction<commit_after>#include <robocup2Dsim/common/action.hpp>
#include <robocup2Dsim/common/action.capnp.h>
#include <capnp/message.h>
#include <gtest/gtest.h>
#include <turbo/memory/slab_allocator.hpp>
#include <turbo/memory/slab_allocator.hxx>
#include <robocup2Dsim/runtime/db_access.hpp>
#include <robocup2Dsim/engine/physics.hxx>
#include <robocup2Dsim/engine/inventory.hxx>

namespace rco = robocup2Dsim::common;
namespace ren = robocup2Dsim::engine;
namespace red = robocup2Dsim::engine::dynamics;
namespace rru = robocup2Dsim::runtime;

TEST(action_test, local_allocator_basic)
{
    EXPECT_TRUE(rru::update_local_db().component_allocator().in_configured_range(4U));
}

TEST(action_test, act_move_foot_forward_understock)
{
    ren::energy original_energy1{rco::MoveFootAction::MAX_COST / 2};
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{original_energy1.quantity};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::understock,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "act succeeded when stock was insufficient";
    EXPECT_EQ(original_energy1.quantity, stock1.quantity) << "act failed but energy was still spent";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x == new_position1.x && original_position1.y == new_position1.y)
	    << "unsuccessful act affected the simulation";
}

TEST(action_test, act_move_foot_backward_understock)
{
    ren::energy original_energy1{rco::MoveFootAction::MAX_COST / 2};
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{original_energy1.quantity};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::understock,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "act succeeded when stock was insufficient";
    EXPECT_EQ(original_energy1.quantity, stock1.quantity) << "act failed but energy was still spent";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x == new_position1.x && original_position1.y == new_position1.y)
	    << "unsuccessful act affected the simulation";
}

TEST(action_test, act_move_foot_forward_basic)
{
    ren::energy original_energy1{rco::MoveFootAction::MAX_COST * 2};
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{original_energy1.quantity};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::success,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "failed to act";
    EXPECT_NE(original_energy1.quantity, stock1.quantity) << "energy stock quantity is the same after successful action";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
	    << "action had no effect on simulation";
}

TEST(action_test, act_move_foot_backward_basic)
{
    ren::energy original_energy1{rco::MoveFootAction::MAX_COST * 2};
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{original_energy1.quantity};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::success,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "failed to act";
    EXPECT_NE(original_energy1.quantity, stock1.quantity) << "energy stock quantity is the same after successful action";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
	    << "action had no effect on simulation";
}

TEST(action_test, act_move_foot_half_forward_velocity)
{
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{rco::MoveFootAction::MAX_COST};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY / 2);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::success,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "failed to act";
    EXPECT_EQ(rco::MoveFootAction::MAX_COST / 2, stock1.quantity) << "energy spent was not proportional to the specified velocity";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
	    << "action had no effect on simulation";
}

TEST(action_test, act_move_foot_half_backward_velocity)
{
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{rco::MoveFootAction::MAX_COST};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY / 2);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::success,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "failed to act";
    EXPECT_EQ(rco::MoveFootAction::MAX_COST / 2, stock1.quantity) << "energy spent was not proportional to the specified velocity";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
	    << "action had no effect on simulation";
}

TEST(action_test, act_move_foot_excess_forward_velocity)
{
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{rco::MoveFootAction::MAX_COST};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(rco::MoveFootAction::MAX_VELOCITY + 10);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::success,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "failed to act";
    EXPECT_EQ(0U, stock1.quantity) << "energy spent was not equal to the max cost";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
	    << "action had no effect on simulation";
}

TEST(action_test, act_move_foot_excess_backward_velocity)
{
    ren::inventory inventory1({0U, rco::MoveFootAction::MAX_COST * 2});
    ren::physics physics1(ren::physics::vec2(0.0, 0.0), {8U, 4U});
    ren::energy stock1{rco::MoveFootAction::MAX_COST};
    ren::physics::body_def body_def1;
    body_def1.type = b2_dynamicBody;
    body_def1.position.Set(20.0, 20.0);
    body_def1.angle = 0.0;
    ren::physics_ptr<red::body> torso1 = physics1.make_body(0U, body_def1);
    ren::physics_ptr<red::body> foot1 = physics1.make_body(0U, body_def1);
    capnp::MallocMessageBuilder arena1;
    rco::MoveFootAction::Builder action1 = arena1.initRoot<rco::MoveFootAction>();
    action1.setVelocity(-rco::MoveFootAction::MAX_VELOCITY - 10);
    ren::physics::vec2 original_position1 = foot1->GetPosition();
    EXPECT_EQ(ren::inventory::spend_result::success,
	    rco::act(inventory1, stock1, physics1, *torso1, *foot1, action1.asReader()))
	    << "failed to act";
    EXPECT_EQ(0U, stock1.quantity) << "energy spent was not equal to the max cost";
    physics1.step(10.0,
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { },
	    [&](const ren::physics::contact_participant&, const ren::physics::contact_participant&) -> void { });
    ren::physics::vec2 new_position1 = foot1->GetPosition();
    EXPECT_TRUE(original_position1.x != new_position1.x || original_position1.y != new_position1.y)
	    << "action had no effect on simulation";
}
<|endoftext|>


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

#include <cassert>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>

#include <sys/signal.h>

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <grpc/support/host_port.h>
#include <gflags/gflags.h>
#include <grpc++/client_context.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <gtest/gtest.h>
#include "test/core/util/grpc_profiler.h"
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/client.h"
#include "test/cpp/qps/qpstest.pb.h"
#include "test/cpp/qps/histogram.h"
#include "test/cpp/qps/timer.h"

namespace grpc {
namespace testing {

class SynchronousClient : public Client {
 public:
  SynchronousClient(const ClientConfig& config) : Client(config) {
    num_threads_ =
      config.outstanding_rpcs_per_channel() * config.client_channels();
    responses_.resize(num_threads_);
  }

  virtual ~SynchronousClient() { EndThreads(); }

 protected:
  size_t num_threads_;
  std::vector<SimpleResponse> responses_;
};

class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient {
 public:
  SynchronousUnaryClient(const ClientConfig& config):
    SynchronousClient(config) {StartThreads(num_threads_);}
  ~SynchronousUnaryClient() {}

  void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
    auto* stub = channels_[thread_idx % channels_.size()].get_stub();
    double start = Timer::Now();
    grpc::ClientContext context;
    grpc::Status s =
        stub->UnaryCall(&context, request_, &responses_[thread_idx]);
    histogram->Add((Timer::Now() - start) * 1e9);
  }
};

class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient {
 public:
  SynchronousStreamingClient(const ClientConfig& config):
    SynchronousClient(config) {
    for (size_t thread_idx=0;thread_idx<num_threads_;thread_idx++){
      auto* stub = channels_[thread_idx % channels_.size()].get_stub();
      stream_ = stub->StreamingCall(&context_);
    }
    StartThreads(num_threads_);
  }
  ~SynchronousStreamingClient() {
    if (stream_) {
      SimpleResponse response;
      stream_->WritesDone();
      EXPECT_FALSE(stream_->Read(&response));

      Status s = stream_->Finish();
      EXPECT_TRUE(s.IsOk());
    }
  }

  void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
    double start = Timer::Now();
    EXPECT_TRUE(stream_->Write(request_));
    EXPECT_TRUE(stream_->Read(&responses_[thread_idx]));
    histogram->Add((Timer::Now() - start) * 1e9);
  }
  private:
    grpc::ClientContext context_;
    std::unique_ptr<grpc::ClientReaderWriter<SimpleRequest,SimpleResponse>> stream_;
};

std::unique_ptr<Client>
CreateSynchronousUnaryClient(const ClientConfig& config) {
  return std::unique_ptr<Client>(new SynchronousUnaryClient(config));
}
std::unique_ptr<Client>
CreateSynchronousStreamingClient(const ClientConfig& config) {
  return std::unique_ptr<Client>(new SynchronousStreamingClient(config));
}

}  // namespace testing
}  // namespace grpc
<commit_msg>No need to do an extra read<commit_after>/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <cassert>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>

#include <sys/signal.h>

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <grpc/support/host_port.h>
#include <gflags/gflags.h>
#include <grpc++/client_context.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <gtest/gtest.h>
#include "test/core/util/grpc_profiler.h"
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/client.h"
#include "test/cpp/qps/qpstest.pb.h"
#include "test/cpp/qps/histogram.h"
#include "test/cpp/qps/timer.h"

namespace grpc {
namespace testing {

class SynchronousClient : public Client {
 public:
  SynchronousClient(const ClientConfig& config) : Client(config) {
    num_threads_ =
      config.outstanding_rpcs_per_channel() * config.client_channels();
    responses_.resize(num_threads_);
  }

  virtual ~SynchronousClient() { EndThreads(); }

 protected:
  size_t num_threads_;
  std::vector<SimpleResponse> responses_;
};

class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient {
 public:
  SynchronousUnaryClient(const ClientConfig& config):
    SynchronousClient(config) {StartThreads(num_threads_);}
  ~SynchronousUnaryClient() {}

  void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
    auto* stub = channels_[thread_idx % channels_.size()].get_stub();
    double start = Timer::Now();
    grpc::ClientContext context;
    grpc::Status s =
        stub->UnaryCall(&context, request_, &responses_[thread_idx]);
    histogram->Add((Timer::Now() - start) * 1e9);
  }
};

class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient {
 public:
  SynchronousStreamingClient(const ClientConfig& config):
    SynchronousClient(config) {
    for (size_t thread_idx=0;thread_idx<num_threads_;thread_idx++){
      auto* stub = channels_[thread_idx % channels_.size()].get_stub();
      stream_ = stub->StreamingCall(&context_);
    }
    StartThreads(num_threads_);
  }
  ~SynchronousStreamingClient() {
    if (stream_) {
      SimpleResponse response;
      stream_->WritesDone();
      EXPECT_TRUE(stream_->Finish().IsOk());
    }
  }

  void ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
    double start = Timer::Now();
    EXPECT_TRUE(stream_->Write(request_));
    EXPECT_TRUE(stream_->Read(&responses_[thread_idx]));
    histogram->Add((Timer::Now() - start) * 1e9);
  }
  private:
    grpc::ClientContext context_;
    std::unique_ptr<grpc::ClientReaderWriter<SimpleRequest,
                                             SimpleResponse>> stream_;
};

std::unique_ptr<Client>
CreateSynchronousUnaryClient(const ClientConfig& config) {
  return std::unique_ptr<Client>(new SynchronousUnaryClient(config));
}
std::unique_ptr<Client>
CreateSynchronousStreamingClient(const ClientConfig& config) {
  return std::unique_ptr<Client>(new SynchronousStreamingClient(config));
}

}  // namespace testing
}  // namespace grpc
<|endoftext|>


<commit_before>// This is core/vnl/tests/test_cholesky.cxx
#include <testlib/testlib_test.h>
#include <vcl_iostream.h>
#include <vnl/vnl_matrix.h>
#include <vnl/algo/vnl_cholesky.h>
#include <vnl/algo/vnl_svd.h>
#include <vcl_ctime.h>
#include <vnl/vnl_sample.h>

#include "test_util.h"

void test_cholesky()
{
  vnl_matrix<double> A(3,3);
  test_util_fill_random(A.begin(), A.end());
  A = A * A.transpose();

  vnl_matrix<double> I(3,3);
  I.set_identity();

  {
    vnl_cholesky chol(A);
    vnl_svd<double> svd(A);
    vcl_cout << "cholesky inverse:\n" << chol.inverse() << '\n'
             << "svd inverse:\n" << svd.inverse() << '\n';
    testlib_test_assert_near("svd.inverse() ~= cholesky.inverse()",
                             (chol.inverse() - svd.inverse()).fro_norm());
  }
  {
    vnl_cholesky chol(A);
    testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
    testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
  }
  {
    vnl_cholesky chol(A, vnl_cholesky::estimate_condition);
    testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
    testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
  }
}

TESTMAIN(test_cholesky);
<commit_msg>COMP: Supply default seed on cygwin<commit_after>// This is core/vnl/tests/test_cholesky.cxx
#include <testlib/testlib_test.h>
#include <vcl_iostream.h>
#include <vnl/vnl_matrix.h>
#include <vnl/algo/vnl_cholesky.h>
#include <vnl/algo/vnl_svd.h>
#include <vnl/vnl_sample.h>

#include "test_util.h"

void test_cholesky()
{
  vnl_matrix<double> A(3,3);
  vnl_sample_reseed(0x1234abcd);
  test_util_fill_random(A.begin(), A.end());
  A = A * A.transpose();

  vnl_matrix<double> I(3,3);
  I.set_identity();

  {
    vnl_cholesky chol(A);
    vnl_svd<double> svd(A);
    vcl_cout << "cholesky inverse:\n" << chol.inverse() << '\n'
             << "svd inverse:\n" << svd.inverse() << '\n';
    testlib_test_assert_near("svd.inverse() ~= cholesky.inverse()",
                             (chol.inverse() - svd.inverse()).fro_norm());
  }
  {
    vnl_cholesky chol(A);
    testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
    testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
  }
  {
    vnl_cholesky chol(A, vnl_cholesky::estimate_condition);
    testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm());
    testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm());
  }
}

TESTMAIN(test_cholesky);
<|endoftext|>