<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012-2020 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include "config.h"
#include "iotests.h"
#include <map>
#include <libcouchbase/utils.h>
#include "internal.h"

class ServeropsUnitTest : public MockUnitTest
{
};

extern "C" {
static void testServerStatsCallback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp)
{
    int *counter;
    lcb_respstats_cookie(resp, (void **)&counter);
    EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));
    ++(*counter);
}

static void statKey_callback(lcb_INSTANCE *, int, const lcb_RESPSTATS *resp)
{
    const char *server;
    size_t server_len;
    lcb_respstats_server(resp, &server, &server_len);
    if (server == nullptr) {
        return;
    }
    EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));
    std::map<std::string, bool> *mm;
    lcb_respstats_cookie(resp, (void **)&mm);
    (*mm)[std::string(server, server_len)] = true;
}
}

/**
 * @test Server Statistics
 * @pre Schedule a server statistics command
 * @post The response is a valid statistics structure and its status is
 * @c SUCCESS.
 *
 * @post the statistics callback is invoked more than once.
 */
TEST_F(ServeropsUnitTest, testServerStats)
{
    lcb_INSTANCE *instance;
    HandleWrap hw;
    createConnection(hw, &instance);

    lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)testServerStatsCallback);
    int numcallbacks = 0;
    lcb_CMDSTATS *cmd;
    lcb_cmdstats_create(&cmd);
    EXPECT_EQ(LCB_SUCCESS, lcb_stats(instance, &numcallbacks, cmd));
    lcb_cmdstats_destroy(cmd);
    lcb_wait(instance, LCB_WAIT_DEFAULT);
    EXPECT_LT(1, numcallbacks);
}

TEST_F(ServeropsUnitTest, testKeyStats)
{
    SKIP_UNLESS_MOCK(); // FIXME: works on 5.5.0, fails on 6.0.0
    lcb_INSTANCE *instance;
    HandleWrap hw;
    createConnection(hw, &instance);
    lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)statKey_callback);
    lcb_CMDSTATS *cmd;
    lcb_cmdstats_create(&cmd);

    std::string key = "keystats_test";
    storeKey(instance, key, "blah blah");
    lcb_cmdstats_key(cmd, key.c_str(), key.size());
    lcb_cmdstats_is_keystats(cmd, true);
    std::map<std::string, bool> mm;

    lcb_sched_enter(instance);
    lcb_STATUS err = lcb_stats(instance, &mm, cmd);
    ASSERT_EQ(LCB_SUCCESS, err);
    lcb_sched_leave(instance);

    lcb_wait(instance, LCB_WAIT_DEFAULT);
    ASSERT_EQ(lcb_get_num_replicas(instance) + 1, mm.size());

    // Ensure that a key with an embedded space fails
    key = "key with space";
    lcb_cmdstats_key(cmd, key.c_str(), key.size());
    lcb_cmdstats_is_keystats(cmd, true);
    err = lcb_stats(instance, nullptr, cmd);
    ASSERT_NE(LCB_SUCCESS, err);
    lcb_cmdstats_create(&cmd);
}
<commit_msg>tests: fix minor memory leak<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012-2020 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include "config.h"
#include "iotests.h"
#include <map>
#include <libcouchbase/utils.h>
#include "internal.h"

class ServeropsUnitTest : public MockUnitTest
{
};

extern "C" {
static void testServerStatsCallback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp)
{
    int *counter;
    lcb_respstats_cookie(resp, (void **)&counter);
    EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));
    ++(*counter);
}

static void statKey_callback(lcb_INSTANCE *, int, const lcb_RESPSTATS *resp)
{
    const char *server;
    size_t server_len;
    lcb_respstats_server(resp, &server, &server_len);
    if (server == nullptr) {
        return;
    }
    EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));
    std::map<std::string, bool> *mm;
    lcb_respstats_cookie(resp, (void **)&mm);
    (*mm)[std::string(server, server_len)] = true;
}
}

/**
 * @test Server Statistics
 * @pre Schedule a server statistics command
 * @post The response is a valid statistics structure and its status is
 * @c SUCCESS.
 *
 * @post the statistics callback is invoked more than once.
 */
TEST_F(ServeropsUnitTest, testServerStats)
{
    lcb_INSTANCE *instance;
    HandleWrap hw;
    createConnection(hw, &instance);

    lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)testServerStatsCallback);
    int numcallbacks = 0;
    lcb_CMDSTATS *cmd;
    lcb_cmdstats_create(&cmd);
    EXPECT_EQ(LCB_SUCCESS, lcb_stats(instance, &numcallbacks, cmd));
    lcb_cmdstats_destroy(cmd);
    lcb_wait(instance, LCB_WAIT_DEFAULT);
    EXPECT_LT(1, numcallbacks);
}

TEST_F(ServeropsUnitTest, testKeyStats)
{
    SKIP_UNLESS_MOCK(); // FIXME: works on 5.5.0, fails on 6.0.0
    lcb_INSTANCE *instance;
    HandleWrap hw;
    createConnection(hw, &instance);
    lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)statKey_callback);
    lcb_CMDSTATS *cmd;
    lcb_cmdstats_create(&cmd);

    std::string key = "keystats_test";
    storeKey(instance, key, "blah blah");
    lcb_cmdstats_key(cmd, key.c_str(), key.size());
    lcb_cmdstats_is_keystats(cmd, true);
    std::map<std::string, bool> mm;

    lcb_sched_enter(instance);
    lcb_STATUS err = lcb_stats(instance, &mm, cmd);
    ASSERT_EQ(LCB_SUCCESS, err);
    lcb_sched_leave(instance);

    lcb_wait(instance, LCB_WAIT_DEFAULT);
    ASSERT_EQ(lcb_get_num_replicas(instance) + 1, mm.size());

    // Ensure that a key with an embedded space fails
    key = "key with space";
    lcb_cmdstats_key(cmd, key.c_str(), key.size());
    lcb_cmdstats_is_keystats(cmd, true);
    err = lcb_stats(instance, nullptr, cmd);
    ASSERT_NE(LCB_SUCCESS, err);
    lcb_cmdstats_destroy(cmd);
}
<|endoftext|>


<commit_before>#include "test.hpp"
#include "../compiler_macro.hpp"

namespace frea {
	namespace test {
		// template <class T>
		// using SMatrix = RMatrix<T>;
		// using SqTypes_t = seq::ExpandTypes_t2<
		// 	types::SquareMat_t,
		// 	std::tuple<
		// 		types::Reg_t,
		// 		seq::Range_t<2,5>,
		// 		std::tuple<BConst<false>>
		// 	>
		// >;
		// using SqTypes = ToTestTypes_t<SqTypes_t>;
		// TYPED_TEST_CASE(SMatrix, SqTypes);
		// TYPED_TEST(SMatrix, Transpose) {
		// 	using value_t = typename TestFixture::value_t;
		// 	using array_t = typename TestFixture::array_t;
		// 	using mat_t = typename TestFixture::mat_t;
		//
		// 	// 転置行列を二次元配列で計算した結果と比較
		// 	constexpr auto range = Range<value_t>{-1e3, 1e3};
		// 	auto mat = this->makeRMat(range);
		// 	array_t raw(mat);
		//
		// 	raw.transpose();
		// 	mat.transpose();
		// 	ASSERT_LT(AbsMax(raw - mat), Threshold<value_t>());
		//
		// 	// (AB)t と (B)t(A)tの結果は同じ
		// 	mat = this->makeRMat(range);
		// 	auto mat2 = this->makeRMat(range);
		// 	const mat_t result0 = (mat * mat2).transposition();
		// 	mat.transpose();
		// 	mat2.transpose();
		// 	const mat_t result1 = mat2 * mat;
		// 	ASSERT_LT(AbsMax(mat_t(result0 - result1)), Threshold<value_t>());
		// }
	}
}
<commit_msg>コメントアウトしたままになっていたテストコードを有効化<commit_after>#include "test.hpp"

namespace frea {
	namespace test {
		template <class T>
		using SMatrix = RMatrix<T>;
		using SqTypes_t = seq::ExpandTypes_t2<
			types::SquareMat_t,
			std::tuple<
				types::Reg_t,
				seq::Range_t<2,5>,
				std::tuple<BConst<false>>
			>
		>;
		using SqTypes = ToTestTypes_t<SqTypes_t>;
		TYPED_TEST_CASE(SMatrix, SqTypes);
		TYPED_TEST(SMatrix, Transpose) {
			using value_t = typename TestFixture::value_t;
			using array_t = typename TestFixture::array_t;
			using mat_t = typename TestFixture::mat_t;

			// 転置行列を二次元配列で計算した結果と比較
			constexpr auto range = Range<value_t>{-1e3, 1e3};
			auto mat = this->makeRMat(range);
			array_t raw(mat);

			raw.transpose();
			mat.transpose();
			ASSERT_LE(AbsMax(raw - mat), Threshold<value_t>(1<<5,0));

			// (AB)t と (B)t(A)tの結果は同じ
			mat = this->makeRMat(range);
			auto mat2 = this->makeRMat(range);
			const mat_t result0 = (mat * mat2).transposition();
			mat.transpose();
			mat2.transpose();
			const mat_t result1 = mat2 * mat;
			ASSERT_LE(AbsMax(mat_t(result0 - result1)), Threshold<value_t>(1<<5,0));
		}
	}
}
<|endoftext|>


<commit_before>extern "C"
{
    #include "packet_queue.h"
    #include "error.h"
    #include "nrf51.h"
    #include "nrf51_bitfields.h"
}

#include "CppUTest/TestHarness.h"

#include <limits.h>
#include <string.h>

extern "C"
{
    void error_handler(uint32_t err_code, uint32_t line_num, char * file_name)
    {

    }
}

TEST_GROUP(packet_queue)
{
    packet_queue_t queue;

    void setup(void)
    {
        packet_queue_init(&queue);
    }

    void teardown(void)
    {
    }
};

TEST(packet_queue, test_queue_init_succeed)
{
    packet_queue_t queue;
    LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}

TEST(packet_queue, test_queue_new_queue_is_empty)
{
    LONGS_EQUAL(true, packet_queue_is_empty(&queue));

    radio_packet_t packet;
    packet_queue_add(&queue, &packet);

    LONGS_EQUAL(false, packet_queue_is_empty(&queue));
}

TEST(packet_queue, test_queue_full_queue_is_full)
{
    LONGS_EQUAL(false, packet_queue_is_full(&queue));

    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        radio_packet_t packet;
        packet_queue_add(&queue, &packet);
    }
    LONGS_EQUAL(true, packet_queue_is_full(&queue));
}

TEST(packet_queue, test_queue_add_succeeds_on_empty_queue)
{
    radio_packet_t packet;
    packet.data[0] = rand()*INT_MAX;
    LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));

    LONGS_EQUAL(0, memcmp(&packet, &queue.packets[0], sizeof(packet)));
}

TEST(packet_queue, test_queue_add_succeeds_on_non_empty_queue)
{
    radio_packet_t packet;
    packet_queue_add(&queue, &packet);

    packet.data[0] = rand()*INT_MAX;
    LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));

    LONGS_EQUAL(0, memcmp(&packet, &queue.packets[queue.tail-1], sizeof(packet)));
}

TEST(packet_queue, test_queue_add_fails_on_full_queue)
{
    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        radio_packet_t packet;
        LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));
    }

    radio_packet_t packet;
    LONGS_EQUAL(NO_MEMORY, packet_queue_add(&queue, &packet));
}

TEST(packet_queue, test_queue_get_fails_on_empty_queue)
{
    radio_packet_t * packet;
    LONGS_EQUAL(NOT_FOUND, packet_queue_get(&queue, &packet));

}

TEST(packet_queue, test_queue_get_returns_correct_pointer)
{
    radio_packet_t in_packet;
    packet_queue_add(&queue, &in_packet);

    radio_packet_t * out_packet = 0;
    packet_queue_get(&queue, &out_packet);

    POINTERS_EQUAL(out_packet, &queue.packets[0]);
}

TEST(packet_queue, test_queue_add_get_packet)
{
    radio_packet_t in_packet;
    in_packet.data[0] = rand()*INT_MAX;
    packet_queue_add(&queue, &in_packet);

    radio_packet_t * out_packet;
    packet_queue_get(&queue, &out_packet);

    LONGS_EQUAL(0, memcmp(&in_packet, out_packet, sizeof(in_packet)));
}

TEST(packet_queue, test_queue_is_fifo)
{
    radio_packet_t in_packets[PACKET_QUEUE_ELEMENTS];

    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        in_packets[i].data[0] = rand()*INT_MAX;
        LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &in_packets[i]));
    }

    radio_packet_t * out_packets[PACKET_QUEUE_ELEMENTS] = {0};
    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        LONGS_EQUAL(SUCCESS, packet_queue_get(&queue, &out_packets[i]));
    }

    CHECK(0 != out_packets[0]);
    LONGS_EQUAL(0, memcmp(out_packets[0], &in_packets[0], sizeof(in_packets[0])));
    CHECK(0 != out_packets[1]);
    LONGS_EQUAL(0, memcmp(out_packets[1], &in_packets[1], sizeof(in_packets[1])));
    CHECK(0 != out_packets[2]);
    LONGS_EQUAL(0, memcmp(out_packets[2], &in_packets[2], sizeof(in_packets[2])));
    CHECK(0 != out_packets[3]);
    LONGS_EQUAL(0, memcmp(out_packets[3], &in_packets[3], sizeof(in_packets[3])));
    CHECK(0 != out_packets[4]);
    LONGS_EQUAL(0, memcmp(out_packets[4], &in_packets[4], sizeof(in_packets[4])));
    CHECK(0 != out_packets[5]);
    LONGS_EQUAL(0, memcmp(out_packets[5], &in_packets[5], sizeof(in_packets[5])));
    CHECK(0 != out_packets[6]);
    LONGS_EQUAL(0, memcmp(out_packets[6], &in_packets[6], sizeof(in_packets[6])));
    CHECK(0 != out_packets[7]);
    LONGS_EQUAL(0, memcmp(out_packets[7], &in_packets[7], sizeof(in_packets[7])));
    CHECK(0 != out_packets[8]);
    LONGS_EQUAL(0, memcmp(out_packets[8], &in_packets[8], sizeof(in_packets[8])));
    CHECK(0 != out_packets[9]);
    LONGS_EQUAL(0, memcmp(out_packets[9], &in_packets[9], sizeof(in_packets[9])));
}
<commit_msg>Accomodate smaller queue in tests.<commit_after>extern "C"
{
    #include "packet_queue.h"
    #include "error.h"
    #include "nrf51.h"
    #include "nrf51_bitfields.h"
}

#include "CppUTest/TestHarness.h"

#include <limits.h>
#include <string.h>

extern "C"
{
    void error_handler(uint32_t err_code, uint32_t line_num, char * file_name)
    {

    }
}

TEST_GROUP(packet_queue)
{
    packet_queue_t queue;

    void setup(void)
    {
        packet_queue_init(&queue);
    }

    void teardown(void)
    {
    }
};

TEST(packet_queue, test_queue_init_succeed)
{
    packet_queue_t queue;
    LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}

TEST(packet_queue, test_queue_new_queue_is_empty)
{
    LONGS_EQUAL(true, packet_queue_is_empty(&queue));

    radio_packet_t packet;
    packet_queue_add(&queue, &packet);

    LONGS_EQUAL(false, packet_queue_is_empty(&queue));
}

TEST(packet_queue, test_queue_full_queue_is_full)
{
    LONGS_EQUAL(false, packet_queue_is_full(&queue));

    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        radio_packet_t packet;
        packet_queue_add(&queue, &packet);
    }
    LONGS_EQUAL(true, packet_queue_is_full(&queue));
}

TEST(packet_queue, test_queue_add_succeeds_on_empty_queue)
{
    radio_packet_t packet;
    packet.data[0] = rand()*INT_MAX;
    LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));

    LONGS_EQUAL(0, memcmp(&packet, &queue.packets[0], sizeof(packet)));
}

TEST(packet_queue, test_queue_add_succeeds_on_non_empty_queue)
{
    radio_packet_t packet;
    packet_queue_add(&queue, &packet);

    packet.data[0] = rand()*INT_MAX;
    LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));

    LONGS_EQUAL(0, memcmp(&packet, &queue.packets[queue.tail-1], sizeof(packet)));
}

TEST(packet_queue, test_queue_add_fails_on_full_queue)
{
    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        radio_packet_t packet;
        LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));
    }

    radio_packet_t packet;
    LONGS_EQUAL(NO_MEMORY, packet_queue_add(&queue, &packet));
}

TEST(packet_queue, test_queue_get_fails_on_empty_queue)
{
    radio_packet_t * packet;
    LONGS_EQUAL(NOT_FOUND, packet_queue_get(&queue, &packet));

}

TEST(packet_queue, test_queue_get_returns_correct_pointer)
{
    radio_packet_t in_packet;
    packet_queue_add(&queue, &in_packet);

    radio_packet_t * out_packet = 0;
    packet_queue_get(&queue, &out_packet);

    POINTERS_EQUAL(out_packet, &queue.packets[0]);
}

TEST(packet_queue, test_queue_add_get_packet)
{
    radio_packet_t in_packet;
    in_packet.data[0] = rand()*INT_MAX;
    packet_queue_add(&queue, &in_packet);

    radio_packet_t * out_packet;
    packet_queue_get(&queue, &out_packet);

    LONGS_EQUAL(0, memcmp(&in_packet, out_packet, sizeof(in_packet)));
}

TEST(packet_queue, test_queue_is_fifo)
{
    radio_packet_t in_packets[PACKET_QUEUE_ELEMENTS];

    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        in_packets[i].data[0] = rand()*INT_MAX;
        LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &in_packets[i]));
    }

    radio_packet_t * out_packets[PACKET_QUEUE_ELEMENTS] = {0};
    for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)
    {
        LONGS_EQUAL(SUCCESS, packet_queue_get(&queue, &out_packets[i]));
    }

    CHECK(0 != out_packets[0]);
    LONGS_EQUAL(0, memcmp(out_packets[0], &in_packets[0], sizeof(in_packets[0])));
    CHECK(0 != out_packets[1]);
    LONGS_EQUAL(0, memcmp(out_packets[1], &in_packets[1], sizeof(in_packets[1])));
    CHECK(0 != out_packets[2]);
    LONGS_EQUAL(0, memcmp(out_packets[2], &in_packets[2], sizeof(in_packets[2])));
    CHECK(0 != out_packets[3]);
    LONGS_EQUAL(0, memcmp(out_packets[3], &in_packets[3], sizeof(in_packets[3])));
    CHECK(0 != out_packets[4]);
    LONGS_EQUAL(0, memcmp(out_packets[4], &in_packets[4], sizeof(in_packets[4])));
    CHECK(0 != out_packets[5]);
    LONGS_EQUAL(0, memcmp(out_packets[5], &in_packets[5], sizeof(in_packets[5])));
    CHECK(0 != out_packets[6]);
    LONGS_EQUAL(0, memcmp(out_packets[6], &in_packets[6], sizeof(in_packets[6])));
}
<|endoftext|>


<commit_before>///
/// @file  IteratorHelper.cpp
///        Functions used to calculate the next start and stop
///        numbers for primesieve::iterator.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/config.hpp>
#include <primesieve/IteratorHelper.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <primesieve/pmath.hpp>

#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <limits>

using namespace std;
using namespace primesieve;

namespace {

uint64_t getNextDist(uint64_t n, uint64_t dist)
{
  double x = (double) n;
  uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;
  uint64_t minDist = (uint64_t) sqrt(x);
  uint64_t maxDist = 1ull << 60;

  dist *= 4;
  dist = max(dist, tinyDist);
  dist = max(dist, minDist);
  dist = min(dist, maxDist);

  return dist;
}

uint64_t getPrevDist(uint64_t n, uint64_t dist)
{
  double x = (double) n;
  x = max(x, 10.0);
  double logx = ceil(log(x));

  uint64_t minDist = config::MIN_CACHE_ITERATOR;
  uint64_t maxDist = config::MAX_CACHE_ITERATOR;
  minDist /= sizeof(uint64_t);
  maxDist /= sizeof(uint64_t);
  minDist *= (uint64_t) logx;
  maxDist *= (uint64_t) logx;

  uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;
  uint64_t defaultDist = (uint64_t) (sqrt(x) * 2);

  dist *= 4;
  dist = max(dist, tinyDist);
  dist = min(dist, minDist);
  dist = max(dist, defaultDist);
  dist = min(dist, maxDist);

  return dist;
}

bool useStopHint(uint64_t start,
                 uint64_t stopHint)
{
  return stopHint >= start &&
         stopHint < numeric_limits<uint64_t>::max();
}

bool useStopHint(uint64_t start,
                 uint64_t stop,
                 uint64_t stopHint)
{
  return stopHint >= start &&
         stopHint <= stop;
}

} // namespace

namespace primesieve {

void IteratorHelper::next(uint64_t* start,
                          uint64_t* stop,
                          uint64_t stopHint,
                          uint64_t* dist)
{
  *start = checkedAdd(*stop, 1);
  uint64_t maxCachedPrime = PrimeGenerator::maxCachedPrime();

  if (*start < maxCachedPrime)
  {
    // When the stop number <= maxCachedPrime
    // primesieve::iterator uses the primes
    // cache instead of sieving and does not
    // even initialize Erat::init()
    *stop = maxCachedPrime;
    *dist = *stop - *start;
  }
  else
  {
    *dist = getNextDist(*start, *dist);
    *stop = checkedAdd(*start, *dist);

    if (useStopHint(*start, stopHint))
      *stop = checkedAdd(stopHint, maxPrimeGap(stopHint));
  }
}

void IteratorHelper::prev(uint64_t* start,
                          uint64_t* stop,
                          uint64_t stopHint,
                          uint64_t* dist)
{
  *stop = checkedSub(*start, 1);
  *dist = getPrevDist(*stop, *dist);
  *start = checkedSub(*stop, *dist);

  if (useStopHint(*start, *stop, stopHint))
    *start = checkedSub(stopHint, maxPrimeGap(stopHint));
}

} // namespace
<commit_msg>Remove unused header<commit_after>///
/// @file  IteratorHelper.cpp
///        Functions used to calculate the next start and stop
///        numbers for primesieve::iterator.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/config.hpp>
#include <primesieve/IteratorHelper.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <primesieve/pmath.hpp>

#include <stdint.h>
#include <algorithm>
#include <cmath>

using namespace std;
using namespace primesieve;

namespace {

uint64_t getNextDist(uint64_t n, uint64_t dist)
{
  double x = (double) n;
  uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;
  uint64_t minDist = (uint64_t) sqrt(x);
  uint64_t maxDist = 1ull << 60;

  dist *= 4;
  dist = max(dist, tinyDist);
  dist = max(dist, minDist);
  dist = min(dist, maxDist);

  return dist;
}

uint64_t getPrevDist(uint64_t n, uint64_t dist)
{
  double x = (double) n;
  x = max(x, 10.0);
  double logx = ceil(log(x));

  uint64_t minDist = config::MIN_CACHE_ITERATOR;
  uint64_t maxDist = config::MAX_CACHE_ITERATOR;
  minDist /= sizeof(uint64_t);
  maxDist /= sizeof(uint64_t);
  minDist *= (uint64_t) logx;
  maxDist *= (uint64_t) logx;

  uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;
  uint64_t defaultDist = (uint64_t) (sqrt(x) * 2);

  dist *= 4;
  dist = max(dist, tinyDist);
  dist = min(dist, minDist);
  dist = max(dist, defaultDist);
  dist = min(dist, maxDist);

  return dist;
}

bool useStopHint(uint64_t start,
                 uint64_t stopHint)
{
  return stopHint >= start &&
         stopHint < numeric_limits<uint64_t>::max();
}

bool useStopHint(uint64_t start,
                 uint64_t stop,
                 uint64_t stopHint)
{
  return stopHint >= start &&
         stopHint <= stop;
}

} // namespace

namespace primesieve {

void IteratorHelper::next(uint64_t* start,
                          uint64_t* stop,
                          uint64_t stopHint,
                          uint64_t* dist)
{
  *start = checkedAdd(*stop, 1);
  uint64_t maxCachedPrime = PrimeGenerator::maxCachedPrime();

  if (*start < maxCachedPrime)
  {
    // When the stop number <= maxCachedPrime
    // primesieve::iterator uses the primes
    // cache instead of sieving and does not
    // even initialize Erat::init()
    *stop = maxCachedPrime;
    *dist = *stop - *start;
  }
  else
  {
    *dist = getNextDist(*start, *dist);
    *stop = checkedAdd(*start, *dist);

    if (useStopHint(*start, stopHint))
      *stop = checkedAdd(stopHint, maxPrimeGap(stopHint));
  }
}

void IteratorHelper::prev(uint64_t* start,
                          uint64_t* stop,
                          uint64_t stopHint,
                          uint64_t* dist)
{
  *stop = checkedSub(*start, 1);
  *dist = getPrevDist(*stop, *dist);
  *start = checkedSub(*stop, *dist);

  if (useStopHint(*start, *stop, stopHint))
    *start = checkedSub(stopHint, maxPrimeGap(stopHint));
}

} // namespace
<|endoftext|>


<commit_before>
#include <unistd.h>
#include <sstream>

#include "tclap/CmdLine.h"
#include "beanstalk.hpp"
#include "alpr.h"
#include "openalpr/simpleini/simpleini.h"
#include "openalpr/cjson.h"
#include "support/tinythread.h"
#include "videobuffer.h"
#include "uuid.h"
#include <curl/curl.h>

// prototypes
void streamRecognitionThread(void* arg);
bool writeToQueue(std::string jsonResult);
bool uploadPost(std::string url, std::string data);
void dataUploadThread(void* arg);

// Constants
const std::string DEFAULT_LOG_FILE_PATH="/var/log/openalpr.log";
const std::string WTS_CONFIG_FILE_PATH="/etc/openalpr/wts.conf";

const std::string BEANSTALK_QUEUE_HOST="127.0.0.1";
const int BEANSTALK_PORT=11300;
const std::string BEANSTALK_TUBE_NAME="alpr";

struct CaptureThreadData
{
  std::string stream_url;
  std::string site_id;
  int camera_id;

  std::string config_file;
  std::string country_code;
  std::string output_image_folder;
};

struct UploadThreadData
{
  std::string upload_url;
};

bool daemon_active;

int main( int argc, const char** argv )
{
  daemon_active = true;

  bool noDaemon = false;
  std::string logFile;
  int topn;

  std::string configFile;
  std::string country;

  TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion());

  TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe).  Default=us",false, "us" ,"country_code");
  TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file.",false, "" ,"config_file");
  TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return.  Default=10",false, 10 ,"topN");
  TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to.  Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN");

  TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging.  Disables forking the process as a daemon and runs in the foreground.  Default=off", cmd, false);

  try
  {

    cmd.add( topNArg );
    cmd.add( configFileArg );
    cmd.add( logFileArg );

    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    country = countryCodeArg.getValue();
    configFile = configFileArg.getValue();
    logFile = logFileArg.getValue();
    topn = topNArg.getValue();
    noDaemon = daemonOffSwitch.getValue();
  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }

  if (noDaemon == false)
  {
    // Fork off into a separate daemon
    daemon(0, 0);

    // Redirect std out to log file

    std::ofstream out(logFile.c_str());
    std::cout.rdbuf(out.rdbuf());
    std::cerr.rdbuf(out.rdbuf());

    std::cout << "Running OpenALPR daemon in daemon mode." << std::endl;
  }
  else
  {
    std::cout << "Running OpenALPR daemon in the foreground" << std::endl;
  }

  CSimpleIniA ini;
  ini.SetMultiKey();

  ini.LoadFile(WTS_CONFIG_FILE_PATH.c_str());

  std::vector<std::string> stream_urls;

  CSimpleIniA::TNamesDepend values;
  ini.GetAllValues("daemon", "stream", values);

  // sort the values into the original load order
  values.sort(CSimpleIniA::Entry::LoadOrder());

  // output all of the items
  CSimpleIniA::TNamesDepend::const_iterator i;
  for (i = values.begin(); i != values.end(); ++i) {
      stream_urls.push_back(i->pItem);
  }

  if (stream_urls.size() == 0)
  {
    std::cout << "No video streams defined in the configuration" << std::endl;
    return 1;
  }

  std::string imageFolder = ini.GetValue("daemon", "image_folder", "/tmp/");
  std::string upload_url = ini.GetValue("daemon", "upload_address", "");
  std::string site_id = ini.GetValue("daemon", "site_id", "");

  std::cout << "Using: " << imageFolder << " for storing valid plate images" << std::endl;

  for (int i = 0; i < stream_urls.size(); i++)
  {
    CaptureThreadData* tdata = new CaptureThreadData();
    tdata->stream_url = stream_urls[i];
    tdata->camera_id = i + 1;
    tdata->config_file = configFile;
    tdata->output_image_folder = imageFolder;
    tdata->country_code = country;
    tdata->site_id = site_id;

    tthread::thread* t = new tthread::thread(streamRecognitionThread, (void*) tdata);
  }

  // Kick off the data upload thread
  UploadThreadData* udata = new UploadThreadData();
  udata->upload_url = upload_url;
  tthread::thread* t = new tthread::thread(dataUploadThread, (void*) udata );

  while (daemon_active)
  {
    usleep(30000);
  }

}

void streamRecognitionThread(void* arg)
{
  CaptureThreadData* tdata = (CaptureThreadData*) arg;

  std::cout << "country: " << tdata->country_code << " -- config file: " << tdata->config_file << std::endl;
  std::cout << "Stream " << tdata->camera_id << ": " << tdata->stream_url << std::endl;

  Alpr alpr(tdata->country_code, tdata->config_file);

  std::cout << "asdf" << std::endl;

  int framenum = 0;

  VideoBuffer videoBuffer;

  videoBuffer.connect(tdata->stream_url, 5);

  cv::Mat latestFrame;

  std::vector<uchar> buffer;

  std::cout << "Daemon active: " << daemon_active << std::endl;

  while (daemon_active)
  {
    int response = videoBuffer.getLatestFrame(&latestFrame);

    if (response != -1)
    {
      cv::imencode(".bmp", latestFrame, buffer );
      std::vector<AlprResult> results = alpr.recognize(buffer);

      if (results.size() > 0)
      {
	// Create a UUID for the image
	std::string uuid = newUUID();

	// Save the image to disk (using the UUID)
	std::stringstream ss;
	ss << tdata->output_image_folder << "/" << uuid << ".jpg";

	cv::imwrite(ss.str(), latestFrame);

	// Update the JSON content to include UUID and camera ID
	cJSON *root;

	root=cJSON_CreateObject();

	std::string json = alpr.toJson(results);

	cJSON *array = cJSON_Parse(json.c_str());
	cJSON_AddStringToObject(root,	"uuid",		uuid.c_str());
	cJSON_AddNumberToObject(root,	"camera_id",	tdata->camera_id);
	cJSON_AddStringToObject(root, "site-id", 	tdata->site_id.c_str());
	cJSON_AddItemToObject(root, 	"results", 	array);

	char *out;
	out=cJSON_PrintUnformatted(root);
	cJSON_Delete(root);

	std::string response(out);

	free(out);

	// Push the results to the Beanstalk queue
	writeToQueue(response);
      }
    }

    usleep(10000);
  }

  videoBuffer.disconnect();

  std::cout << "Video processing ended" << std::endl;

  delete tdata;
}

bool writeToQueue(std::string jsonResult)
{

    Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);
    client.use(BEANSTALK_TUBE_NAME);

    int id = client.put(jsonResult);

    if (id <= 0)
      return false;

    std::cout << "put job id: " << id << std::endl;

    return true;
}

void dataUploadThread(void* arg)
{

  UploadThreadData* udata = (UploadThreadData*) arg;

  Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);

  client.watch(BEANSTALK_TUBE_NAME);

  while(daemon_active)
  {
    Beanstalk::Job job;

    client.reserve(job);

    if (job.id() > 0)
    {
      if (uploadPost(udata->upload_url, job.body()))
      {
	client.del(job.id());
	std::cout << "Job: " << job.id() << " successfully uploaded" << std::endl;
      }
      else
      {
	client.release(job);
	std::cout << "Job: " << job.id() << " failed to upload.  Will retry." << std::endl;
      }
    }

    usleep(10000);
  }

}

bool uploadPost(std::string url, std::string data)
{
  bool success = true;
  CURL *curl;
  CURLcode res;

  /* In windows, this will init the winsock stuff */
  curl_global_init(CURL_GLOBAL_ALL);

  /* get a curl handle */
  curl = curl_easy_init();
  if(curl) {
    /* First set the URL that is about to receive our POST. This URL can
       just as well be a https:// URL if that is what should receive the
       data. */
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    /* Now specify the POST data */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());

    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK)
    {
      success = false;
    }

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  curl_global_cleanup();

  return success;

}<commit_msg>Updated POSTS to work with web server<commit_after>
#include <unistd.h>
#include <sstream>

#include "tclap/CmdLine.h"
#include "beanstalk.hpp"
#include "alpr.h"
#include "openalpr/simpleini/simpleini.h"
#include "openalpr/cjson.h"
#include "support/tinythread.h"
#include "videobuffer.h"
#include "uuid.h"
#include <curl/curl.h>

// prototypes
void streamRecognitionThread(void* arg);
bool writeToQueue(std::string jsonResult);
bool uploadPost(std::string url, std::string data);
void dataUploadThread(void* arg);

// Constants
const std::string DEFAULT_LOG_FILE_PATH="/var/log/openalpr.log";
const std::string WTS_CONFIG_FILE_PATH="/etc/openalpr/wts.conf";

const std::string BEANSTALK_QUEUE_HOST="127.0.0.1";
const int BEANSTALK_PORT=11300;
const std::string BEANSTALK_TUBE_NAME="alpr";

struct CaptureThreadData
{
  std::string stream_url;
  std::string site_id;
  int camera_id;

  std::string config_file;
  std::string country_code;
  std::string output_image_folder;
};

struct UploadThreadData
{
  std::string upload_url;
};

bool daemon_active;

int main( int argc, const char** argv )
{
  daemon_active = true;

  bool noDaemon = false;
  std::string logFile;
  int topn;

  std::string configFile;
  std::string country;

  TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion());

  TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe).  Default=us",false, "us" ,"country_code");
  TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file.",false, "" ,"config_file");
  TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return.  Default=10",false, 10 ,"topN");
  TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to.  Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN");

  TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging.  Disables forking the process as a daemon and runs in the foreground.  Default=off", cmd, false);

  try
  {

    cmd.add( topNArg );
    cmd.add( configFileArg );
    cmd.add( logFileArg );

    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    country = countryCodeArg.getValue();
    configFile = configFileArg.getValue();
    logFile = logFileArg.getValue();
    topn = topNArg.getValue();
    noDaemon = daemonOffSwitch.getValue();
  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }

  if (noDaemon == false)
  {
    // Fork off into a separate daemon
    daemon(0, 0);

    // Redirect std out to log file

    std::ofstream out(logFile.c_str());
    std::cout.rdbuf(out.rdbuf());
    std::cerr.rdbuf(out.rdbuf());

    std::cout << "Running OpenALPR daemon in daemon mode." << std::endl;
  }
  else
  {
    std::cout << "Running OpenALPR daemon in the foreground" << std::endl;
  }

  CSimpleIniA ini;
  ini.SetMultiKey();

  ini.LoadFile(WTS_CONFIG_FILE_PATH.c_str());

  std::vector<std::string> stream_urls;

  CSimpleIniA::TNamesDepend values;
  ini.GetAllValues("daemon", "stream", values);

  // sort the values into the original load order
  values.sort(CSimpleIniA::Entry::LoadOrder());

  // output all of the items
  CSimpleIniA::TNamesDepend::const_iterator i;
  for (i = values.begin(); i != values.end(); ++i) {
      stream_urls.push_back(i->pItem);
  }

  if (stream_urls.size() == 0)
  {
    std::cout << "No video streams defined in the configuration" << std::endl;
    return 1;
  }

  std::string imageFolder = ini.GetValue("daemon", "image_folder", "/tmp/");
  std::string upload_url = ini.GetValue("daemon", "upload_address", "");
  std::string site_id = ini.GetValue("daemon", "site_id", "");

  std::cout << "Using: " << imageFolder << " for storing valid plate images" << std::endl;

  for (int i = 0; i < stream_urls.size(); i++)
  {
    CaptureThreadData* tdata = new CaptureThreadData();
    tdata->stream_url = stream_urls[i];
    tdata->camera_id = i + 1;
    tdata->config_file = configFile;
    tdata->output_image_folder = imageFolder;
    tdata->country_code = country;
    tdata->site_id = site_id;

    tthread::thread* t = new tthread::thread(streamRecognitionThread, (void*) tdata);
  }

  // Kick off the data upload thread
  UploadThreadData* udata = new UploadThreadData();
  udata->upload_url = upload_url;
  tthread::thread* t = new tthread::thread(dataUploadThread, (void*) udata );

  while (daemon_active)
  {
    usleep(30000);
  }

}

void streamRecognitionThread(void* arg)
{
  CaptureThreadData* tdata = (CaptureThreadData*) arg;

  std::cout << "country: " << tdata->country_code << " -- config file: " << tdata->config_file << std::endl;
  std::cout << "Stream " << tdata->camera_id << ": " << tdata->stream_url << std::endl;

  Alpr alpr(tdata->country_code, tdata->config_file);

  std::cout << "asdf" << std::endl;

  int framenum = 0;

  VideoBuffer videoBuffer;

  videoBuffer.connect(tdata->stream_url, 5);

  cv::Mat latestFrame;

  std::vector<uchar> buffer;

  std::cout << "Daemon active: " << daemon_active << std::endl;

  while (daemon_active)
  {
    int response = videoBuffer.getLatestFrame(&latestFrame);

    if (response != -1)
    {
      cv::imencode(".bmp", latestFrame, buffer );
      std::vector<AlprResult> results = alpr.recognize(buffer);

      if (results.size() > 0)
      {
	// Create a UUID for the image
	std::string uuid = newUUID();

	// Save the image to disk (using the UUID)
	std::stringstream ss;
	ss << tdata->output_image_folder << "/" << uuid << ".jpg";

	cv::imwrite(ss.str(), latestFrame);

	// Update the JSON content to include UUID and camera ID
	cJSON *root;

	root=cJSON_CreateObject();

	std::string json = alpr.toJson(results);

	cJSON *array = cJSON_Parse(json.c_str());
	cJSON_AddStringToObject(root,	"uuid",		uuid.c_str());
	cJSON_AddNumberToObject(root,	"camera_id",	tdata->camera_id);
	cJSON_AddStringToObject(root, "site-id", 	tdata->site_id.c_str());
	cJSON_AddItemToObject(root, 	"results", 	array);

	char *out;
	out=cJSON_PrintUnformatted(root);
	cJSON_Delete(root);

	std::string response(out);

	free(out);

	// Push the results to the Beanstalk queue
	writeToQueue(response);
      }
    }

    usleep(10000);
  }

  videoBuffer.disconnect();

  std::cout << "Video processing ended" << std::endl;

  delete tdata;
}

bool writeToQueue(std::string jsonResult)
{

    Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);
    client.use(BEANSTALK_TUBE_NAME);

    int id = client.put(jsonResult);

    if (id <= 0)
      return false;

    std::cout << "put job id: " << id << std::endl;

    return true;
}

void dataUploadThread(void* arg)
{

  /* In windows, this will init the winsock stuff */
  curl_global_init(CURL_GLOBAL_ALL);

  UploadThreadData* udata = (UploadThreadData*) arg;

  Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);

  client.watch(BEANSTALK_TUBE_NAME);

  while(daemon_active)
  {
    Beanstalk::Job job;

    client.reserve(job);

    if (job.id() > 0)
    {
      if (uploadPost(udata->upload_url, job.body()))
      {
	client.del(job.id());
	std::cout << "Job: " << job.id() << " successfully uploaded" << std::endl;
      }
      else
      {
	client.release(job);
	std::cout << "Job: " << job.id() << " failed to upload.  Will retry." << std::endl;
      }
    }

    usleep(10000);
  }

  curl_global_cleanup();
}

bool uploadPost(std::string url, std::string data)
{
  bool success = true;
  CURL *curl;
  CURLcode res;

  /* get a curl handle */
  curl = curl_easy_init();
  if(curl) {
    /* First set the URL that is about to receive our POST. This URL can
       just as well be a https:// URL if that is what should receive the
       data. */
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    /* Now specify the POST data */
    //char* escaped_data = curl_easy_escape(curl, data.c_str(), data.length());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
    //curl_free(escaped_data);

    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK)
    {
      success = false;
    }

    /* always cleanup */
    curl_easy_cleanup(curl);
  }

  return success;

}<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    liFilterConsole2D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <liFilterConsole2D.h>
#include <FL/fl_file_chooser.H>

/************************************
 *
 *  Constructor
 *
 ***********************************/
liFilterConsole2D
::liFilterConsole2D()
{

  m_InputViewer = InputImageViewerType::New();

  m_Viewer_H1x  = ImageViewerType::New();
  m_Viewer_H1y  = ImageViewerType::New();

  m_Viewer_H2x  = ImageViewerType::New();
  m_Viewer_H2y  = ImageViewerType::New();

  m_Viewer_Laplacian =        ImageViewerType::New();
  m_Viewer_Smoothed  =        ImageViewerType::New();
  m_Viewer_Gradient_Modulus = ImageViewerType::New();

  m_InputViewer->SetLabel( "Input Image" );

  m_Viewer_H1x->SetLabel( "Gradient X" );
  m_Viewer_H1y->SetLabel( "Gradient Y" );

  m_Viewer_H2x->SetLabel( "Second Derivative X" );
  m_Viewer_H2y->SetLabel( "Second Derivative Y" );

  m_Viewer_Laplacian->SetLabel( "Laplacian" );
  m_Viewer_Smoothed->SetLabel( "Smoothed" );
  m_Viewer_Gradient_Modulus->SetLabel( "Gradient Modulus" );

  progressSlider->Observe( m_Hx.GetPointer() );
  progressSlider->Observe( m_Hy.GetPointer() );
  progressSlider->Observe( m_H1x.GetPointer() );
  progressSlider->Observe( m_H1y.GetPointer() );
  progressSlider->Observe( m_H2x.GetPointer() );
  progressSlider->Observe( m_H2y.GetPointer() );
  progressSlider->Observe( m_Laplacian.GetPointer() );
  progressSlider->Observe( m_Smoothed.GetPointer() );
  progressSlider->Observe( m_Modulus.GetPointer() );
  progressSlider->Observe( m_IntensityScaleSmoothed.GetPointer() );
  progressSlider->Observe( m_IntensityScaleLaplacian.GetPointer() );
  progressSlider->Observe( m_IntensityScaleModulus.GetPointer() );
  progressSlider->Observe( m_WriterSmoothed.GetPointer() );
  progressSlider->Observe( m_WriterLaplacian.GetPointer() );
  progressSlider->Observe( m_WriterModulus.GetPointer() );

  loadButton->Observe( m_Reader.GetPointer() );
  inputButton->Observe( m_Reader.GetPointer() );
  HxButton->Observe( m_Hx.GetPointer() );
  HyButton->Observe( m_Hy.GetPointer() );
  H1xButton->Observe( m_H1x.GetPointer() );
  H1yButton->Observe( m_H1y.GetPointer() );
  H2xButton->Observe( m_H2x.GetPointer() );
  H2yButton->Observe( m_H2y.GetPointer() );
  laplacianButton->Observe( m_Laplacian.GetPointer() );
  smoothedButton->Observe( m_Smoothed.GetPointer() );
  modulusButton->Observe( m_Modulus.GetPointer() );

  m_Reader->AddObserver( itk::ModifiedEvent(), HxButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), HyButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H1xButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H1yButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H2xButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H2yButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), laplacianButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), smoothedButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), modulusButton->GetRedrawCommand().GetPointer() );

  m_IntensityScaleModulus->SetScale(    0.2  );
  m_IntensityScaleSmoothed->SetScale(   0.2  );
  m_IntensityScaleLaplacian->SetScale(  0.2  );

  m_IntensityScaleModulus->SetShift(   1000  );
  m_IntensityScaleSmoothed->SetScale(  1000  );
  m_IntensityScaleLaplacian->SetScale( 1000  );

  this->ShowStatus("Let's start by loading an image...");

}

/************************************
 *
 *  Destructor
 *
 ***********************************/
liFilterConsole2D
::~liFilterConsole2D()
{

}

/************************************
 *
 *  Load
 *
 ***********************************/
void
liFilterConsole2D
::Load( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Loading image file...");

  try
  {
    liFilterConsole2DBase::Load( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems reading file format");
    controlsGroup->deactivate();
    return;
  }

  this->ShowStatus("File Loaded");

  controlsGroup->activate();

}

/************************************
 *
 *  Show
 *
 ***********************************/
void
liFilterConsole2D
::Show( void )
{
  consoleWindow->show();
}

/************************************
 *
 *  Hide
 *
 ***********************************/
void
liFilterConsole2D
::Hide( void )
{

  consoleWindow->hide();
  m_Viewer_H1x->Hide();
  m_Viewer_H1y->Hide();
  m_Viewer_H2x->Hide();
  m_Viewer_H2y->Hide();
  m_InputViewer->Hide();
  m_Viewer_Laplacian->Hide();
  m_Viewer_Smoothed->Hide();
  m_Viewer_Gradient_Modulus->Hide();
}

/************************************
 *
 *  Quit
 *
 ***********************************/
void
liFilterConsole2D
::Quit( void )
{
  Hide();
}

/************************************
 *
 *  Show Status
 *
 ***********************************/
void
liFilterConsole2D
::ShowStatus( const char * message )
{
  liFilterConsole2DBase::ShowStatus( message );
  statusTextOutput->value( message );
  Fl::check();
}

/************************************
 *
 *  Show Input Image
 *
 ***********************************/
void
liFilterConsole2D
::ShowInput( void )
{

  if( ! (m_ImageLoaded) )
  {
    this->ShowStatus("Please load an image first");
    return;
  }

  m_InputViewer->SetImage( m_Reader->GetOutput() );
  m_InputViewer->Show();

}

/************************************
 *
 *  Show Filtered Image
 *
 ***********************************/
void
liFilterConsole2D
::ShowFilteredX( void )
{

  m_H1x->Update();
  m_Viewer_H1x->SetImage( m_H1x->GetOutput() );
  m_Viewer_H1x->Show();

}

/************************************
 *
 *  Show Filtered Image
 *
 ***********************************/
void
liFilterConsole2D
::ShowFilteredY( void )
{

  m_H1y->Update();
  m_Viewer_H1y->SetImage( m_H1y->GetOutput() );
  m_Viewer_H1y->Show();

}

/************************************
 *
 *  Show Second Derivative X
 *
 ***********************************/
void
liFilterConsole2D
::ShowSecondDerivativeX( void )
{

  m_H2x->Update();
  m_Viewer_H2x->SetImage( m_H2x->GetOutput() );
  m_Viewer_H2x->Show();

}

/************************************
 *
 *  Show Second Derivative Y
 *
 ***********************************/
void
liFilterConsole2D
::ShowSecondDerivativeY( void )
{

  m_H2y->Update();
  m_Viewer_H2y->SetImage( m_H2y->GetOutput() );
  m_Viewer_H2y->Show();

}

/************************************
 *
 *  Show Smoothed
 *
 ***********************************/
void
liFilterConsole2D
::ShowSmoothed( void )
{

  m_Smoothed->Update();
  m_Viewer_Smoothed->SetImage( m_Smoothed->GetOutput() );
  m_Viewer_Smoothed->Show();

}

/************************************
 *
 *  Show Laplacian
 *
 ***********************************/
void
liFilterConsole2D
::ShowLaplacian( void )
{

  m_Laplacian->Update();
  m_Viewer_Laplacian->SetImage( m_Laplacian->GetOutput() );
  m_Viewer_Laplacian->Show();

}

/************************************
 *
 *  Show Gradient Modulus
 *
 ***********************************/
void
liFilterConsole2D
::ShowGradientModulus( void )
{

  m_Modulus->Update();
  m_Viewer_Gradient_Modulus->SetImage( m_Modulus->GetOutput() );
  m_Viewer_Gradient_Modulus->Show();

}

/************************************
 *
 *  Execute
 *
 ***********************************/
void
liFilterConsole2D
::Execute( void )
{

  if( ! (m_ImageLoaded) )
  {
    this->ShowStatus("Please load an image first");
    return;
  }

  this->ShowStatus("Filtering Image with a Gaussian...");

  liFilterConsole2DBase::Execute();

  this->ShowStatus("Filtering done ");

}

/************************************
 *
 *  SaveLaplacian
 *
 ***********************************/
void
liFilterConsole2D
::SaveLaplacian( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Saving image file...");

  try
  {
    liFilterConsole2DBase::SaveLaplacian( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems writing file format");
    return;
  }

  this->ShowStatus("File Saved");

}

/************************************
 *
 *  SaveModulus
 *
 ***********************************/
void
liFilterConsole2D
::SaveModulus( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Saving image file...");

  try
  {
    liFilterConsole2DBase::SaveModulus( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems writing file format");
    return;
  }

  this->ShowStatus("File Saved");

}

/************************************
 *
 *  SaveSmoothed
 *
 ***********************************/
void
liFilterConsole2D
::SaveSmoothed( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Saving image file...");

  try
  {
    liFilterConsole2DBase::SaveSmoothed( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems writing file format");
    return;
  }

  this->ShowStatus("File Saved");

}

<commit_msg>ENH: The GaussianFilter is better scaled now, so the ShiftFilter is set to 1.0.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    liFilterConsole2D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <liFilterConsole2D.h>
#include <FL/fl_file_chooser.H>

/************************************
 *
 *  Constructor
 *
 ***********************************/
liFilterConsole2D
::liFilterConsole2D()
{

  m_InputViewer = InputImageViewerType::New();

  m_Viewer_H1x  = ImageViewerType::New();
  m_Viewer_H1y  = ImageViewerType::New();

  m_Viewer_H2x  = ImageViewerType::New();
  m_Viewer_H2y  = ImageViewerType::New();

  m_Viewer_Laplacian =        ImageViewerType::New();
  m_Viewer_Smoothed  =        ImageViewerType::New();
  m_Viewer_Gradient_Modulus = ImageViewerType::New();

  m_InputViewer->SetLabel( "Input Image" );

  m_Viewer_H1x->SetLabel( "Gradient X" );
  m_Viewer_H1y->SetLabel( "Gradient Y" );

  m_Viewer_H2x->SetLabel( "Second Derivative X" );
  m_Viewer_H2y->SetLabel( "Second Derivative Y" );

  m_Viewer_Laplacian->SetLabel( "Laplacian" );
  m_Viewer_Smoothed->SetLabel( "Smoothed" );
  m_Viewer_Gradient_Modulus->SetLabel( "Gradient Modulus" );

  progressSlider->Observe( m_Hx.GetPointer() );
  progressSlider->Observe( m_Hy.GetPointer() );
  progressSlider->Observe( m_H1x.GetPointer() );
  progressSlider->Observe( m_H1y.GetPointer() );
  progressSlider->Observe( m_H2x.GetPointer() );
  progressSlider->Observe( m_H2y.GetPointer() );
  progressSlider->Observe( m_Laplacian.GetPointer() );
  progressSlider->Observe( m_Smoothed.GetPointer() );
  progressSlider->Observe( m_Modulus.GetPointer() );
  progressSlider->Observe( m_IntensityScaleSmoothed.GetPointer() );
  progressSlider->Observe( m_IntensityScaleLaplacian.GetPointer() );
  progressSlider->Observe( m_IntensityScaleModulus.GetPointer() );
  progressSlider->Observe( m_WriterSmoothed.GetPointer() );
  progressSlider->Observe( m_WriterLaplacian.GetPointer() );
  progressSlider->Observe( m_WriterModulus.GetPointer() );

  loadButton->Observe( m_Reader.GetPointer() );
  inputButton->Observe( m_Reader.GetPointer() );
  HxButton->Observe( m_Hx.GetPointer() );
  HyButton->Observe( m_Hy.GetPointer() );
  H1xButton->Observe( m_H1x.GetPointer() );
  H1yButton->Observe( m_H1y.GetPointer() );
  H2xButton->Observe( m_H2x.GetPointer() );
  H2yButton->Observe( m_H2y.GetPointer() );
  laplacianButton->Observe( m_Laplacian.GetPointer() );
  smoothedButton->Observe( m_Smoothed.GetPointer() );
  modulusButton->Observe( m_Modulus.GetPointer() );

  m_Reader->AddObserver( itk::ModifiedEvent(), HxButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), HyButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H1xButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H1yButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H2xButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), H2yButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), laplacianButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), smoothedButton->GetRedrawCommand().GetPointer() );
  m_Reader->AddObserver( itk::ModifiedEvent(), modulusButton->GetRedrawCommand().GetPointer() );

  m_IntensityScaleModulus->SetScale(    1.0  );
  m_IntensityScaleSmoothed->SetScale(   1.0  );
  m_IntensityScaleLaplacian->SetScale(  1.0  );

  m_IntensityScaleModulus->SetShift(   1000  );
  m_IntensityScaleSmoothed->SetScale(  1000  );
  m_IntensityScaleLaplacian->SetScale( 1000  );

  this->ShowStatus("Let's start by loading an image...");

}

/************************************
 *
 *  Destructor
 *
 ***********************************/
liFilterConsole2D
::~liFilterConsole2D()
{

}

/************************************
 *
 *  Load
 *
 ***********************************/
void
liFilterConsole2D
::Load( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Loading image file...");

  try
  {
    liFilterConsole2DBase::Load( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems reading file format");
    controlsGroup->deactivate();
    return;
  }

  this->ShowStatus("File Loaded");

  controlsGroup->activate();

}

/************************************
 *
 *  Show
 *
 ***********************************/
void
liFilterConsole2D
::Show( void )
{
  consoleWindow->show();
}

/************************************
 *
 *  Hide
 *
 ***********************************/
void
liFilterConsole2D
::Hide( void )
{

  consoleWindow->hide();
  m_Viewer_H1x->Hide();
  m_Viewer_H1y->Hide();
  m_Viewer_H2x->Hide();
  m_Viewer_H2y->Hide();
  m_InputViewer->Hide();
  m_Viewer_Laplacian->Hide();
  m_Viewer_Smoothed->Hide();
  m_Viewer_Gradient_Modulus->Hide();
}

/************************************
 *
 *  Quit
 *
 ***********************************/
void
liFilterConsole2D
::Quit( void )
{
  Hide();
}

/************************************
 *
 *  Show Status
 *
 ***********************************/
void
liFilterConsole2D
::ShowStatus( const char * message )
{
  liFilterConsole2DBase::ShowStatus( message );
  statusTextOutput->value( message );
  Fl::check();
}

/************************************
 *
 *  Show Input Image
 *
 ***********************************/
void
liFilterConsole2D
::ShowInput( void )
{

  if( ! (m_ImageLoaded) )
  {
    this->ShowStatus("Please load an image first");
    return;
  }

  m_InputViewer->SetImage( m_Reader->GetOutput() );
  m_InputViewer->Show();

}

/************************************
 *
 *  Show Filtered Image
 *
 ***********************************/
void
liFilterConsole2D
::ShowFilteredX( void )
{

  m_H1x->Update();
  m_Viewer_H1x->SetImage( m_H1x->GetOutput() );
  m_Viewer_H1x->Show();

}

/************************************
 *
 *  Show Filtered Image
 *
 ***********************************/
void
liFilterConsole2D
::ShowFilteredY( void )
{

  m_H1y->Update();
  m_Viewer_H1y->SetImage( m_H1y->GetOutput() );
  m_Viewer_H1y->Show();

}

/************************************
 *
 *  Show Second Derivative X
 *
 ***********************************/
void
liFilterConsole2D
::ShowSecondDerivativeX( void )
{

  m_H2x->Update();
  m_Viewer_H2x->SetImage( m_H2x->GetOutput() );
  m_Viewer_H2x->Show();

}

/************************************
 *
 *  Show Second Derivative Y
 *
 ***********************************/
void
liFilterConsole2D
::ShowSecondDerivativeY( void )
{

  m_H2y->Update();
  m_Viewer_H2y->SetImage( m_H2y->GetOutput() );
  m_Viewer_H2y->Show();

}

/************************************
 *
 *  Show Smoothed
 *
 ***********************************/
void
liFilterConsole2D
::ShowSmoothed( void )
{

  m_Smoothed->Update();
  m_Viewer_Smoothed->SetImage( m_Smoothed->GetOutput() );
  m_Viewer_Smoothed->Show();

}

/************************************
 *
 *  Show Laplacian
 *
 ***********************************/
void
liFilterConsole2D
::ShowLaplacian( void )
{

  m_Laplacian->Update();
  m_Viewer_Laplacian->SetImage( m_Laplacian->GetOutput() );
  m_Viewer_Laplacian->Show();

}

/************************************
 *
 *  Show Gradient Modulus
 *
 ***********************************/
void
liFilterConsole2D
::ShowGradientModulus( void )
{

  m_Modulus->Update();
  m_Viewer_Gradient_Modulus->SetImage( m_Modulus->GetOutput() );
  m_Viewer_Gradient_Modulus->Show();

}

/************************************
 *
 *  Execute
 *
 ***********************************/
void
liFilterConsole2D
::Execute( void )
{

  if( ! (m_ImageLoaded) )
  {
    this->ShowStatus("Please load an image first");
    return;
  }

  this->ShowStatus("Filtering Image with a Gaussian...");

  liFilterConsole2DBase::Execute();

  this->ShowStatus("Filtering done ");

}

/************************************
 *
 *  SaveLaplacian
 *
 ***********************************/
void
liFilterConsole2D
::SaveLaplacian( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Saving image file...");

  try
  {
    liFilterConsole2DBase::SaveLaplacian( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems writing file format");
    return;
  }

  this->ShowStatus("File Saved");

}

/************************************
 *
 *  SaveModulus
 *
 ***********************************/
void
liFilterConsole2D
::SaveModulus( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Saving image file...");

  try
  {
    liFilterConsole2DBase::SaveModulus( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems writing file format");
    return;
  }

  this->ShowStatus("File Saved");

}

/************************************
 *
 *  SaveSmoothed
 *
 ***********************************/
void
liFilterConsole2D
::SaveSmoothed( void )
{

  const char * filename = fl_file_chooser("Image filename","*.png","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Saving image file...");

  try
  {
    liFilterConsole2DBase::SaveSmoothed( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems writing file format");
    return;
  }

  this->ShowStatus("File Saved");

}

<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <dart/dynamics/dynamics.h>
#include <dart/common/StlHelpers.h>
#include <aikido/constraint/dart.hpp>
#include <aikido/statespace/dart/RealVectorJointStateSpace.hpp>
#include <aikido/statespace/dart/SO2JointStateSpace.hpp>

using Vector0d = Eigen::Matrix<double, 0, 1>;
using Vector1d = Eigen::Matrix<double, 1, 1>;

using dart::common::make_unique;
using dart::dynamics::BodyNode;
using dart::dynamics::Joint;
using dart::dynamics::RevoluteJoint;
using dart::dynamics::Skeleton;
using dart::dynamics::SkeletonPtr;
using aikido::constraint::SampleGenerator;
using aikido::statespace::RealVectorJointStateSpace;
using aikido::statespace::SO2JointStateSpace;
using aikido::util::RNGWrapper;

using aikido::constraint::createDifferentiableBoundsFor;
using aikido::constraint::createProjectableBoundsFor;
using aikido::constraint::createTestableBoundsFor;
using aikido::constraint::createSampleableBoundsFor;

static Vector1d make_vector(double _x)
{
  Vector1d matrix;
  matrix(0, 0) = _x;
  return matrix;
}

//=============================================================================
class RealVectorJointStateSpaceHelpersTests : public ::testing::Test
{
protected:
  static constexpr int NUM_SAMPLES { 1000 };

  void SetUp() override
  {
    mSkeleton = Skeleton::create();
    mJoint = mSkeleton->createJointAndBodyNodePair<
      RevoluteJoint, BodyNode>().first;
    mJoint->setPositionLowerLimit(0, -1.);
    mJoint->setPositionUpperLimit(0, 2.);

    mStateSpace = std::make_shared<RealVectorJointStateSpace>(mJoint);
  }

  SkeletonPtr mSkeleton;
  RevoluteJoint* mJoint;
  std::shared_ptr<RealVectorJointStateSpace> mStateSpace;
};

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createTestableBoundsFor)
{
  auto constraint = createTestableBoundsFor<RealVectorJointStateSpace>(
    mStateSpace);
  auto state = mStateSpace->createState();

  EXPECT_EQ(mStateSpace, constraint->getStateSpace());

  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(state);
  EXPECT_TRUE(constraint->isSatisfied(state));

  mJoint->setPosition(0, 1.9);
  mStateSpace->getState(state);
  EXPECT_TRUE(constraint->isSatisfied(state));

  mJoint->setPosition(0, -1.1);
  mStateSpace->getState(state);
  EXPECT_FALSE(constraint->isSatisfied(state));

  mJoint->setPosition(0, 2.1);
  mStateSpace->getState(state);
  EXPECT_FALSE(constraint->isSatisfied(state));
}

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createProjectableBounds)
{
  auto testableConstraint
    = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);
  auto projectableConstraint
    = createProjectableBoundsFor<RealVectorJointStateSpace>(mStateSpace);

  auto inState = mStateSpace->createState();
  auto outState = mStateSpace->createState();

  EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace());

  // Doesn't change the value if the constraint is satisfied.
  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));

  mJoint->setPosition(0, 1.9);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));

  // Output is feasible if the constriant is not satisfied.
  mJoint->setPosition(0, -1.1);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(testableConstraint->isSatisfied(outState));

  mJoint->setPosition(0, 2.1);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(testableConstraint->isSatisfied(outState));
}

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createDifferentiableBounds)
{
  const auto differentiableConstraint
    = createDifferentiableBoundsFor<RealVectorJointStateSpace>(mStateSpace);

  EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace());

  auto state = mStateSpace->createState();

  // Value is zero when the constraint is satisfied.
  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(state);
  auto constraintValue = differentiableConstraint->getValue(state);
  EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));

  mJoint->setPosition(0, 1.9);
  mStateSpace->getState(state);
  constraintValue = differentiableConstraint->getValue(state);
  EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));

  // Value is non-zero when the constraint is not satisfied.
  mJoint->setPosition(0, -1.1);
  mStateSpace->getState(state);
  constraintValue = differentiableConstraint->getValue(state);
  EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));

  mJoint->setPosition(0, 2.1);
  mStateSpace->getState(state);
  constraintValue = differentiableConstraint->getValue(state);
  EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));
}

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createSampleableBounds)
{
  auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0);
  const auto testableConstraint
    = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);
  const auto sampleableConstraint
    = createSampleableBoundsFor<RealVectorJointStateSpace>(
        mStateSpace, std::move(rng));
  ASSERT_TRUE(!!sampleableConstraint);
  EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());

  const auto generator = sampleableConstraint->createSampleGenerator();
  ASSERT_TRUE(!!generator);
  EXPECT_EQ(mStateSpace, generator->getStateSpace());

  auto state = mStateSpace->createState();

  for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)
  {
    ASSERT_TRUE(generator->canSample());
    ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());
    ASSERT_TRUE(generator->sample(state));
    ASSERT_TRUE(testableConstraint->isSatisfied(state));
  }
}

//=============================================================================
class SO2JointStateSpaceHelpersTests : public ::testing::Test
{
protected:
  static constexpr int NUM_SAMPLES { 1000 };

  void SetUp() override
  {
    mSkeleton = Skeleton::create();
    mJoint = mSkeleton->createJointAndBodyNodePair<
      RevoluteJoint, BodyNode>().first;
    // Don't set any limits.

    mStateSpace = std::make_shared<SO2JointStateSpace>(mJoint);
  }

  SkeletonPtr mSkeleton;
  RevoluteJoint* mJoint;
  std::shared_ptr<SO2JointStateSpace> mStateSpace;
};

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createTestableBoundsFor)
{
  auto constraint = createTestableBoundsFor<SO2JointStateSpace>(
    mStateSpace);
  auto state = mStateSpace->createState();

  EXPECT_EQ(mStateSpace, constraint->getStateSpace());

  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(state);
  EXPECT_TRUE(constraint->isSatisfied(state));
}

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createProjectableBounds)
{
  auto testableConstraint
    = createTestableBoundsFor<SO2JointStateSpace>(mStateSpace);
  auto projectableConstraint
    = createProjectableBoundsFor<SO2JointStateSpace>(mStateSpace);

  auto inState = mStateSpace->createState();
  auto outState = mStateSpace->createState();

  EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace());

  // Doesn't change the value if the constraint is satisfied.
  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_DOUBLE_EQ(inState.getAngle(), outState.getAngle());
}

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createDifferentiableBounds)
{
  const auto differentiableConstraint
    = createDifferentiableBoundsFor<SO2JointStateSpace>(mStateSpace);

  EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace());

  auto state = mStateSpace->createState();

  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(state);
  auto constraintValue = differentiableConstraint->getValue(state);
  EXPECT_TRUE(Vector0d::Zero().isApprox(constraintValue));
}

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createSampleableBounds)
{
  auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0);
  const auto sampleableConstraint
    = createSampleableBoundsFor<SO2JointStateSpace>(
        mStateSpace, std::move(rng));
  ASSERT_TRUE(!!sampleableConstraint);
  EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());

  const auto generator = sampleableConstraint->createSampleGenerator();
  ASSERT_TRUE(!!generator);
  EXPECT_EQ(mStateSpace, generator->getStateSpace());

  auto state = mStateSpace->createState();

  for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)
  {
    ASSERT_TRUE(generator->canSample());
    ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());
    ASSERT_TRUE(generator->sample(state));
    // There is nothing to test here.
  }
}
<commit_msg>Simplified some SO2 bound tests.<commit_after>#include <gtest/gtest.h>
#include <dart/dynamics/dynamics.h>
#include <dart/common/StlHelpers.h>
#include <aikido/constraint/dart.hpp>
#include <aikido/constraint/SatisfiedConstraint.hpp>
#include <aikido/statespace/dart/RealVectorJointStateSpace.hpp>
#include <aikido/statespace/dart/SO2JointStateSpace.hpp>

using Vector0d = Eigen::Matrix<double, 0, 1>;
using Vector1d = Eigen::Matrix<double, 1, 1>;

using dart::common::make_unique;
using dart::dynamics::BodyNode;
using dart::dynamics::Joint;
using dart::dynamics::RevoluteJoint;
using dart::dynamics::Skeleton;
using dart::dynamics::SkeletonPtr;
using aikido::constraint::SampleGenerator;
using aikido::constraint::SatisfiedConstraint;
using aikido::statespace::RealVectorJointStateSpace;
using aikido::statespace::SO2JointStateSpace;
using aikido::util::RNGWrapper;

using aikido::constraint::createDifferentiableBoundsFor;
using aikido::constraint::createProjectableBoundsFor;
using aikido::constraint::createTestableBoundsFor;
using aikido::constraint::createSampleableBoundsFor;

static Vector1d make_vector(double _x)
{
  Vector1d matrix;
  matrix(0, 0) = _x;
  return matrix;
}

//=============================================================================
class RealVectorJointStateSpaceHelpersTests : public ::testing::Test
{
protected:
  static constexpr int NUM_SAMPLES { 1000 };

  void SetUp() override
  {
    mSkeleton = Skeleton::create();
    mJoint = mSkeleton->createJointAndBodyNodePair<
      RevoluteJoint, BodyNode>().first;
    mJoint->setPositionLowerLimit(0, -1.);
    mJoint->setPositionUpperLimit(0, 2.);

    mStateSpace = std::make_shared<RealVectorJointStateSpace>(mJoint);
  }

  SkeletonPtr mSkeleton;
  RevoluteJoint* mJoint;
  std::shared_ptr<RealVectorJointStateSpace> mStateSpace;
};

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createTestableBoundsFor)
{
  auto constraint = createTestableBoundsFor<RealVectorJointStateSpace>(
    mStateSpace);
  auto state = mStateSpace->createState();

  EXPECT_EQ(mStateSpace, constraint->getStateSpace());

  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(state);
  EXPECT_TRUE(constraint->isSatisfied(state));

  mJoint->setPosition(0, 1.9);
  mStateSpace->getState(state);
  EXPECT_TRUE(constraint->isSatisfied(state));

  mJoint->setPosition(0, -1.1);
  mStateSpace->getState(state);
  EXPECT_FALSE(constraint->isSatisfied(state));

  mJoint->setPosition(0, 2.1);
  mStateSpace->getState(state);
  EXPECT_FALSE(constraint->isSatisfied(state));
}

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createProjectableBounds)
{
  auto testableConstraint
    = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);
  auto projectableConstraint
    = createProjectableBoundsFor<RealVectorJointStateSpace>(mStateSpace);

  auto inState = mStateSpace->createState();
  auto outState = mStateSpace->createState();

  EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace());

  // Doesn't change the value if the constraint is satisfied.
  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));

  mJoint->setPosition(0, 1.9);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));

  // Output is feasible if the constriant is not satisfied.
  mJoint->setPosition(0, -1.1);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(testableConstraint->isSatisfied(outState));

  mJoint->setPosition(0, 2.1);
  mStateSpace->getState(inState);
  EXPECT_TRUE(projectableConstraint->project(inState, outState));
  EXPECT_TRUE(testableConstraint->isSatisfied(outState));
}

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createDifferentiableBounds)
{
  const auto differentiableConstraint
    = createDifferentiableBoundsFor<RealVectorJointStateSpace>(mStateSpace);

  EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace());

  auto state = mStateSpace->createState();

  // Value is zero when the constraint is satisfied.
  mJoint->setPosition(0, -0.9);
  mStateSpace->getState(state);
  auto constraintValue = differentiableConstraint->getValue(state);
  EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));

  mJoint->setPosition(0, 1.9);
  mStateSpace->getState(state);
  constraintValue = differentiableConstraint->getValue(state);
  EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));

  // Value is non-zero when the constraint is not satisfied.
  mJoint->setPosition(0, -1.1);
  mStateSpace->getState(state);
  constraintValue = differentiableConstraint->getValue(state);
  EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));

  mJoint->setPosition(0, 2.1);
  mStateSpace->getState(state);
  constraintValue = differentiableConstraint->getValue(state);
  EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));
}

//=============================================================================
TEST_F(RealVectorJointStateSpaceHelpersTests, createSampleableBounds)
{
  auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0);
  const auto testableConstraint
    = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);
  const auto sampleableConstraint
    = createSampleableBoundsFor<RealVectorJointStateSpace>(
        mStateSpace, std::move(rng));
  ASSERT_TRUE(!!sampleableConstraint);
  EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());

  const auto generator = sampleableConstraint->createSampleGenerator();
  ASSERT_TRUE(!!generator);
  EXPECT_EQ(mStateSpace, generator->getStateSpace());

  auto state = mStateSpace->createState();

  for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)
  {
    ASSERT_TRUE(generator->canSample());
    ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());
    ASSERT_TRUE(generator->sample(state));
    ASSERT_TRUE(testableConstraint->isSatisfied(state));
  }
}

//=============================================================================
class SO2JointStateSpaceHelpersTests : public ::testing::Test
{
protected:
  static constexpr int NUM_SAMPLES { 1000 };

  void SetUp() override
  {
    mSkeleton = Skeleton::create();
    mJoint = mSkeleton->createJointAndBodyNodePair<
      RevoluteJoint, BodyNode>().first;
    // Don't set any limits.

    mStateSpace = std::make_shared<SO2JointStateSpace>(mJoint);
  }

  SkeletonPtr mSkeleton;
  RevoluteJoint* mJoint;
  std::shared_ptr<SO2JointStateSpace> mStateSpace;
};

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createTestableBoundsFor)
{
  const auto constraint
    = createTestableBoundsFor<SO2JointStateSpace>(mStateSpace);
  EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get()));
  EXPECT_EQ(mStateSpace, constraint->getStateSpace());
}

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createProjectableBounds)
{
  const auto constraint
    = createProjectableBoundsFor<SO2JointStateSpace>(mStateSpace);
  EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get()));
  EXPECT_EQ(mStateSpace, constraint->getStateSpace());
}

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createDifferentiableBounds)
{
  const auto constraint
    = createDifferentiableBoundsFor<SO2JointStateSpace>(mStateSpace);
  EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get()));
  EXPECT_EQ(mStateSpace, constraint->getStateSpace());
}

//=============================================================================
TEST_F(SO2JointStateSpaceHelpersTests, createSampleableBounds)
{
  const auto sampleableConstraint
    = createSampleableBoundsFor<SO2JointStateSpace>(mStateSpace,
        make_unique<RNGWrapper<std::default_random_engine>>(0));

  ASSERT_TRUE(!!sampleableConstraint);
  EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());

  const auto generator = sampleableConstraint->createSampleGenerator();
  ASSERT_TRUE(!!generator);
  EXPECT_EQ(mStateSpace, generator->getStateSpace());

  auto state = mStateSpace->createState();

  for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)
  {
    ASSERT_TRUE(generator->canSample());
    ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());
    ASSERT_TRUE(generator->sample(state));
    // There is nothing to test here.
  }
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#include <seastar/core/reactor.hh>
#include <seastar/core/app-template.hh>
#include <seastar/core/print.hh>
#include <seastar/core/shared_ptr.hh>

using namespace seastar;

const char* de_type_desc(directory_entry_type t)
{
    switch (t) {
    case directory_entry_type::unknown:
        return "unknown";
    case directory_entry_type::block_device:
        return "block_device";
    case directory_entry_type::char_device:
        return "char_device";
    case directory_entry_type::directory:
        return "directory";
    case directory_entry_type::fifo:
        return "fifo";
    case directory_entry_type::link:
        return "link";
    case directory_entry_type::regular:
        return "regular";
    case directory_entry_type::socket:
        return "socket";
    }
    assert(0 && "should not get here");
    return nullptr;
}

int main(int ac, char** av) {
    class lister {
        file _f;
        subscription<directory_entry> _listing;
    public:
        lister(file f)
                : _f(std::move(f))
                , _listing(_f.list_directory([this] (directory_entry de) { return report(de); })) {
        }
        future<> done() { return _listing.done(); }
    private:
        future<> report(directory_entry de) {
            return file_stat(de.name, follow_symlink::no).then([de = std::move(de)] (stat_data sd) {
                if (de.type) {
                    assert(*de.type == sd.type);
                } else {
                    assert(sd.type == directory_entry_type::unknown);
                }
                fmt::print("{} (type={})\n", de.name, de_type_desc(sd.type));
                return make_ready_future<>();
            });
        }
    };
    return app_template().run_deprecated(ac, av, [] {
        return engine().open_directory(".").then([] (file f) {
            auto l = make_lw_shared<lister>(std::move(f));
            return l->done().then([l] {
                // ugly thing to keep *l alive
                engine().exit(0);
            });
        });
    });
}
<commit_msg>directory_test: Update to use run instead of run_deprecated<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#include <seastar/core/reactor.hh>
#include <seastar/core/app-template.hh>
#include <seastar/core/print.hh>
#include <seastar/core/shared_ptr.hh>

using namespace seastar;

const char* de_type_desc(directory_entry_type t)
{
    switch (t) {
    case directory_entry_type::unknown:
        return "unknown";
    case directory_entry_type::block_device:
        return "block_device";
    case directory_entry_type::char_device:
        return "char_device";
    case directory_entry_type::directory:
        return "directory";
    case directory_entry_type::fifo:
        return "fifo";
    case directory_entry_type::link:
        return "link";
    case directory_entry_type::regular:
        return "regular";
    case directory_entry_type::socket:
        return "socket";
    }
    assert(0 && "should not get here");
    return nullptr;
}

int main(int ac, char** av) {
    class lister {
        file _f;
        subscription<directory_entry> _listing;
    public:
        lister(file f)
                : _f(std::move(f))
                , _listing(_f.list_directory([this] (directory_entry de) { return report(de); })) {
        }
        future<> done() { return _listing.done(); }
    private:
        future<> report(directory_entry de) {
            return file_stat(de.name, follow_symlink::no).then([de = std::move(de)] (stat_data sd) {
                if (de.type) {
                    assert(*de.type == sd.type);
                } else {
                    assert(sd.type == directory_entry_type::unknown);
                }
                fmt::print("{} (type={})\n", de.name, de_type_desc(sd.type));
                return make_ready_future<>();
            });
        }
    };
    return app_template().run(ac, av, [] {
        return engine().open_directory(".").then([] (file f) {
            return do_with(lister(std::move(f)), [] (lister& l) {
              return l.done().then([] {
                  return 0;
              });
           });
        });
    });
}
<|endoftext|>