<commit_before>/****************************************************************************
 *
 * Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
 *
 * 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.
 *
 * 3. Neither the name of the copyright holder 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 HOLDER 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 "microRTPS_transport.h"
#include "microRTPS_client.h"

#include <cinttypes>
#include <cstdio>
#include <ctime>
#include <termios.h>

#include <px4_config.h>
#include <px4_getopt.h>
#include <px4_posix.h>
#include <px4_tasks.h>
#include <px4_time.h>

extern "C" __EXPORT int micrortps_client_main(int argc, char *argv[]);

static int _rtps_task = -1;
bool _should_exit_task = false;
Transport_node *transport_node = nullptr;
struct options _options;

static void usage(const char *name)
{
	PX4_INFO("usage: %s start|stop [options]\n\n"
		 "  -t <transport>          [UART|UDP] Default UART\n"
		 "  -d <device>             UART device. Default /dev/ttyACM0\n"
		 "  -u <update_time_ms>     Time in ms for uORB subscribed topics update. Default 0\n"
		 "  -l <loops>              How many iterations will this program have. -1 for infinite. Default 10000\n"
		 "  -w <sleep_time_ms>      Time in ms for which each iteration sleep. Default 1ms\n"
		 "  -b <baudrate>           UART device baudrate. Default 460800\n"
		 "  -p <poll_ms>            Time in ms to poll over UART. Default 1ms\n"
		 "  -r <reception port>     UDP port for receiving. Default 2019\n"
		 "  -s <sending port>       UDP port for sending. Default 2020\n",
		 name);
}

static int parse_options(int argc, char *argv[])
{
	int ch;
	int myoptind = 1;
	const char *myoptarg = nullptr;

	while ((ch = px4_getopt(argc, argv, "t:d:u:l:w:b:p:r:s:", &myoptind, &myoptarg)) != EOF) {
		switch (ch) {
		case 't': _options.transport      = strcmp(myoptarg, "UDP") == 0 ?
							    options::eTransports::UDP
							    : options::eTransports::UART;      break;

		case 'd': if (nullptr != myoptarg) strcpy(_options.device, myoptarg); break;

		case 'u': _options.update_time_ms = strtol(myoptarg, nullptr, 10);    break;

		case 'l': _options.loops          = strtol(myoptarg, nullptr, 10);    break;

		case 'w': _options.sleep_ms       = strtol(myoptarg, nullptr, 10);    break;

		case 'b': _options.baudrate       = strtoul(optarg, nullptr, 10);     break;

		case 'p': _options.poll_ms        = strtol(optarg, nullptr, 10);      break;

		case 'r': _options.recv_port      = strtoul(optarg, nullptr, 10);     break;

		case 's': _options.send_port      = strtoul(optarg, nullptr, 10);     break;

		default:
			usage(argv[1]);
			return -1;
		}
	}

	return 0;
}

static int micrortps_start(int argc, char *argv[])
{
	if (0 > parse_options(argc, argv)) {
		printf("EXITING...\n");
		_rtps_task = -1;
		return -1;
	}

	switch (_options.transport) {
	case options::eTransports::UART: {
			transport_node = new UART_node(_options.device, _options.baudrate, _options.poll_ms);
			printf("\nUART transport: device: %s; baudrate: %d; sleep: %dms; poll: %dms\n\n",
			       _options.device, _options.baudrate, _options.sleep_ms, _options.poll_ms);
		}
		break;

	case options::eTransports::UDP: {
			transport_node = new UDP_node(_options.recv_port, _options.send_port);
			printf("\nUDP transport: recv port: %u; send port: %u; sleep: %dms\n\n",
			       _options.recv_port, _options.send_port, _options.sleep_ms);
		}
		break;

	default:
		_rtps_task = -1;
		printf("EXITING...\n");
		return -1;
	}

	if (0 > transport_node->init()) {
		printf("EXITING...\n");
		_rtps_task = -1;
		return -1;
	}

	sleep(1);

	struct timespec begin;
	int total_read = 0;
	uint32_t received = 0;
	int loop = 0;
	micrortps_start_topics(begin, total_read, received, loop);

	struct timespec end;
	px4_clock_gettime(CLOCK_REALTIME, &end);
	double elapsed_secs = double(end.tv_sec - begin.tv_sec) + double(end.tv_nsec - begin.tv_nsec) / double(1000000000);
	printf("RECEIVED: %lu messages in %d LOOPS, %d bytes in %.03f seconds - %.02fKB/s\n\n",
	       (unsigned long)received, loop, total_read, elapsed_secs, (double)total_read / (1000 * elapsed_secs));

	delete transport_node;
	transport_node = nullptr;
	PX4_INFO("exiting");
	fflush(stdout);

	_rtps_task = -1;

	return 0;
}

int micrortps_client_main(int argc, char *argv[])
{
	if (argc < 2) {
		usage(argv[0]);
		return -1;
	}

	if (!strcmp(argv[1], "start")) {
		if (_rtps_task != -1) {
			PX4_INFO("Already running");
			return -1;
		}

		_rtps_task = px4_task_spawn_cmd("rtps",
						SCHED_DEFAULT,
						SCHED_PRIORITY_DEFAULT,
						4096,
						(px4_main_t) micrortps_start,
						(char *const *)argv);

		if (_rtps_task < 0) {
			PX4_WARN("Could not start task");
			_rtps_task = -1;
			return -1;
		}

		return 0;
	}

	if (!strcmp(argv[1], "stop")) {
		if (_rtps_task == -1) {
			PX4_INFO("Not running");
			return -1;
		}

		_should_exit_task = true;

		if (nullptr != transport_node) { transport_node->close(); }

		return 0;
	}

	usage(argv[0]);

	return -1;
}
<commit_msg>micrortps_client_main: add status command<commit_after>/****************************************************************************
 *
 * Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
 *
 * 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.
 *
 * 3. Neither the name of the copyright holder 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 HOLDER 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 "microRTPS_transport.h"
#include "microRTPS_client.h"

#include <cinttypes>
#include <cstdio>
#include <ctime>
#include <termios.h>

#include <px4_config.h>
#include <px4_getopt.h>
#include <px4_posix.h>
#include <px4_tasks.h>
#include <px4_time.h>

extern "C" __EXPORT int micrortps_client_main(int argc, char *argv[]);

static int _rtps_task = -1;
bool _should_exit_task = false;
Transport_node *transport_node = nullptr;
struct options _options;

static void usage(const char *name)
{
	PX4_INFO("usage: %s start|stop [options]\n\n"
		 "  -t <transport>          [UART|UDP] Default UART\n"
		 "  -d <device>             UART device. Default /dev/ttyACM0\n"
		 "  -u <update_time_ms>     Time in ms for uORB subscribed topics update. Default 0\n"
		 "  -l <loops>              How many iterations will this program have. -1 for infinite. Default 10000\n"
		 "  -w <sleep_time_ms>      Time in ms for which each iteration sleep. Default 1ms\n"
		 "  -b <baudrate>           UART device baudrate. Default 460800\n"
		 "  -p <poll_ms>            Time in ms to poll over UART. Default 1ms\n"
		 "  -r <reception port>     UDP port for receiving. Default 2019\n"
		 "  -s <sending port>       UDP port for sending. Default 2020\n",
		 name);
}

static int parse_options(int argc, char *argv[])
{
	int ch;
	int myoptind = 1;
	const char *myoptarg = nullptr;

	while ((ch = px4_getopt(argc, argv, "t:d:u:l:w:b:p:r:s:", &myoptind, &myoptarg)) != EOF) {
		switch (ch) {
		case 't': _options.transport      = strcmp(myoptarg, "UDP") == 0 ?
							    options::eTransports::UDP
							    : options::eTransports::UART;      break;

		case 'd': if (nullptr != myoptarg) strcpy(_options.device, myoptarg); break;

		case 'u': _options.update_time_ms = strtol(myoptarg, nullptr, 10);    break;

		case 'l': _options.loops          = strtol(myoptarg, nullptr, 10);    break;

		case 'w': _options.sleep_ms       = strtol(myoptarg, nullptr, 10);    break;

		case 'b': _options.baudrate       = strtoul(optarg, nullptr, 10);     break;

		case 'p': _options.poll_ms        = strtol(optarg, nullptr, 10);      break;

		case 'r': _options.recv_port      = strtoul(optarg, nullptr, 10);     break;

		case 's': _options.send_port      = strtoul(optarg, nullptr, 10);     break;

		default:
			usage(argv[1]);
			return -1;
		}
	}

	return 0;
}

static int micrortps_start(int argc, char *argv[])
{
	if (0 > parse_options(argc, argv)) {
		printf("EXITING...\n");
		_rtps_task = -1;
		return -1;
	}

	switch (_options.transport) {
	case options::eTransports::UART: {
			transport_node = new UART_node(_options.device, _options.baudrate, _options.poll_ms);
			printf("\nUART transport: device: %s; baudrate: %d; sleep: %dms; poll: %dms\n\n",
			       _options.device, _options.baudrate, _options.sleep_ms, _options.poll_ms);
		}
		break;

	case options::eTransports::UDP: {
			transport_node = new UDP_node(_options.recv_port, _options.send_port);
			printf("\nUDP transport: recv port: %u; send port: %u; sleep: %dms\n\n",
			       _options.recv_port, _options.send_port, _options.sleep_ms);
		}
		break;

	default:
		_rtps_task = -1;
		printf("EXITING...\n");
		return -1;
	}

	if (0 > transport_node->init()) {
		printf("EXITING...\n");
		_rtps_task = -1;
		return -1;
	}

	sleep(1);

	struct timespec begin;
	int total_read = 0;
	uint32_t received = 0;
	int loop = 0;
	micrortps_start_topics(begin, total_read, received, loop);

	struct timespec end;
	px4_clock_gettime(CLOCK_REALTIME, &end);
	double elapsed_secs = double(end.tv_sec - begin.tv_sec) + double(end.tv_nsec - begin.tv_nsec) / double(1000000000);
	printf("RECEIVED: %lu messages in %d LOOPS, %d bytes in %.03f seconds - %.02fKB/s\n\n",
	       (unsigned long)received, loop, total_read, elapsed_secs, (double)total_read / (1000 * elapsed_secs));

	delete transport_node;
	transport_node = nullptr;
	PX4_INFO("exiting");
	fflush(stdout);

	_rtps_task = -1;

	return 0;
}

int micrortps_client_main(int argc, char *argv[])
{
	if (argc < 2) {
		usage(argv[0]);
		return -1;
	}

	if (!strcmp(argv[1], "start")) {
		if (_rtps_task != -1) {
			PX4_INFO("Already running");
			return -1;
		}

		_rtps_task = px4_task_spawn_cmd("rtps",
						SCHED_DEFAULT,
						SCHED_PRIORITY_DEFAULT,
						4096,
						(px4_main_t) micrortps_start,
						(char *const *)argv);

		if (_rtps_task < 0) {
			PX4_WARN("Could not start task");
			_rtps_task = -1;
			return -1;
		}

		return 0;
	}

	if (!strcmp(argv[1], "status")) {
		if (_rtps_task == -1) {
			PX4_INFO("Not running");

		} else {
			PX4_INFO("Running");
		}

		return 0;
	}

	if (!strcmp(argv[1], "stop")) {
		if (_rtps_task == -1) {
			PX4_INFO("Not running");
			return -1;
		}

		_should_exit_task = true;

		if (nullptr != transport_node) { transport_node->close(); }

		return 0;
	}

	usage(argv[0]);

	return -1;
}
<|endoftext|>


<commit_before>#include <hop_bits/optimisationProblem/benchmark/blackBoxOptimisationBenchmark2013.hpp>

// C++ Standard Library
#include <algorithm>
#include <cmath>
#include <random>

// HOP
#include <hop_bits/helper/rng.hpp>
#include <hop_bits/helper/random.hpp>

namespace hop {
  namespace bbob2013 {
    BlackBoxOptimisationBenchmark2013::BlackBoxOptimisationBenchmark2013(
        const unsigned int& numberOfDimensions) noexcept
      : OptimisationProblem(numberOfDimensions) {
      setLowerBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) - 5.0);
      setUpperBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) + 5.0);
      setObjectiveValueTranslation(std::min(1000.0, std::max(-1000.0, std::cauchy_distribution<double>(0.0, 100.0)(Rng::generator))));

      setAcceptableObjectiveValue(objectiveValueTranslation_ + 10e-3);

      setTranslation(arma::randu<arma::Col<double>>(numberOfDimensions_) * 8.0 - 4.0);
      setOne(arma::zeros<arma::Col<double>>(numberOfDimensions_) + (std::bernoulli_distribution(0.5)(Rng::generator) ? 1.0 : -1.0));
      setRotationR(getRandomRotationMatrix(numberOfDimensions_));
      setRotationQ(getRandomRotationMatrix(numberOfDimensions_));
      setDeltaC101(getRandomDeltaC101());
      setLocalOptimaY101(getRandomLocalOptimaY101());
      setDeltaC21(getRandomDeltaC21());
      setLocalOptimaY21(getRandomLocalOptimaY21());
    }

    void BlackBoxOptimisationBenchmark2013::setTranslation(
        const arma::Col<double>& translation) {
      // TODO Add exception
      translation_ = translation;
    }

    void BlackBoxOptimisationBenchmark2013::setOne(
        const arma::Col<double>& one) {
      // TODO Add exception
      one_ = one;
    }

    void BlackBoxOptimisationBenchmark2013::setRotationR(
        const arma::Mat<double>& rotationR) {
      // TODO Add exception
      rotationR_ = rotationR;
    }

    void BlackBoxOptimisationBenchmark2013::setRotationQ(
        const arma::Mat<double>& rotationQ) {
      // TODO Add exception
      rotationQ_ = rotationQ;
    }

    void BlackBoxOptimisationBenchmark2013::setDeltaC101(
        const arma::Mat<double>& deltaC101) {
      // TODO Add exception
      deltaC101_ = deltaC101;
    }

    void BlackBoxOptimisationBenchmark2013::setLocalOptimaY101(
        const arma::Mat<double>& localOptimaY101) {
      // TODO Add exception
      localOptimaY101_ = localOptimaY101;
    }

    void BlackBoxOptimisationBenchmark2013::setDeltaC21(
        const arma::Mat<double>& deltaC21) {
      // TODO Add exception
      deltaC21_ = deltaC21;
    }

    void BlackBoxOptimisationBenchmark2013::setLocalOptimaY21(
        const arma::Mat<double>& localOptimaY21) {
      // TODO Add exception
      localOptimaY21_ = localOptimaY21;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomDeltaC101() const noexcept {
      arma::Mat<double> deltaC101(numberOfDimensions_, 101);
      deltaC101.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25);

      std::uniform_int_distribution<int> uniformIntDistribution(0, 99);
      for (std::size_t n = 1; n < deltaC101.n_cols; ++n) {
        deltaC101.col(n) = getScaling(sqrt(1000.0)) / pow(pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 99.0), 0.25);
      }

      return deltaC101;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomDeltaC21() const noexcept {
      arma::Mat<double> deltaC21(numberOfDimensions_, 21);
      deltaC21.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25);

      std::uniform_int_distribution<int> uniformIntDistribution(0, 19);
      for (std::size_t n = 1; n < deltaC21.n_cols; ++n) {
        deltaC21.col(n) = getScaling(sqrt(1000.0)) / std::pow(std::pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 19.0), 0.25);
      }

      return deltaC21;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomLocalOptimaY101() const noexcept {
      arma::Mat<double> localOptimaY101 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 101) * 8.0 - 4.0;
      localOptimaY101.col(0) = 0.8 * localOptimaY101.col(0);

      return localOptimaY101;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomLocalOptimaY21() const noexcept {
      arma::Mat<double> localOptimaY21 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 21) * 9.8 - 4.9;
      localOptimaY21.col(0) = 0.8 * localOptimaY21.col(0);

      return localOptimaY21;
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getScaling(
        const double& condition) const noexcept {
      arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0, 1, numberOfDimensions_);

      for (auto& scale : scaling) {
        scale = std::pow(condition, scale);
      }

      return scaling;
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getScaling(
        const arma::Col<double>& condition) const noexcept {
      arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0, 1, numberOfDimensions_);

      for (std::size_t n = 0; n < scaling.n_elem; ++n) {
        scaling.at(n) = std::pow(condition.at(n), scaling.at(n));
      }

      return scaling;
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getAsymmetricTransformation(
        const double& beta,
        const arma::Col<double>& parameter) const noexcept {
      arma::Col<double> asymmetricTransformation(parameter.n_elem);
      arma::Col<double> spacing = arma::linspace<arma::Col<double>>(0, 1, numberOfDimensions_);

      for (std::size_t n = 0; n < parameter.n_elem; ++n) {
        double value = parameter.at(n);

        if (value > 0.0) {
          asymmetricTransformation.at(n) = std::pow(value, 1 + beta * spacing.at(n) * std::sqrt(value));
        } else {
          asymmetricTransformation.at(n) = value;
        }
      }

      return asymmetricTransformation;
    }

    double BlackBoxOptimisationBenchmark2013::getOscillationTransformation(
        const double& value) const noexcept {
      if (value != 0.0) {
        double c1;
        double c2;
        if (value > 0.0) {
          c1 = 10.0;
          c2 = 7.9;
        } else {
          c1 = 5.5;
          c2 = 3.1;
        }

        double x = std::log(std::abs(value));
        return std::copysign(1.0, value) * std::exp(x + 0.049 * (std::sin(c1 * x) + std::sin(c2 * x)));
      } else {
        return 0.0;
      }
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getOscillationTransformation(
        const arma::Col<double>& parameter) const noexcept {
      arma::Col<double> oscillate(parameter.n_elem);

      for (std::size_t n = 0; n < parameter.n_elem; ++n) {
        oscillate.at(n) = getOscillationTransformation(parameter.at(n));
      }

      return oscillate;
    }

    double BlackBoxOptimisationBenchmark2013::getPenality(
        const arma::Col<double>& parameter) const noexcept {
      double penality = 0.0;

      for (std::size_t n = 0; n < parameter.n_elem; ++n) {
        penality += std::pow(std::max(0.0, std::abs(parameter.at(n)) - 5.0), 2.0);
      }

      return penality;
    }
  }
}
<commit_msg>devel: Added exceptions to the general BBOB 2013 class<commit_after>#include <hop_bits/optimisationProblem/benchmark/blackBoxOptimisationBenchmark2013.hpp>

// C++ Standard Library
#include <algorithm>
#include <cmath>
#include <random>

// HOP
#include <hop_bits/helper/rng.hpp>
#include <hop_bits/helper/random.hpp>

namespace hop {
  namespace bbob2013 {
    BlackBoxOptimisationBenchmark2013::BlackBoxOptimisationBenchmark2013(
        const unsigned int& numberOfDimensions) noexcept
      : OptimisationProblem(numberOfDimensions) {
      setLowerBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) - 5.0);
      setUpperBounds(arma::zeros<arma::Col<double>>(numberOfDimensions_) + 5.0);
      setObjectiveValueTranslation(std::min(1000.0, std::max(-1000.0, std::cauchy_distribution<double>(0.0, 100.0)(Rng::generator))));

      // TODO Check value within the paper
      setAcceptableObjectiveValue(objectiveValueTranslation_ + 10e-3);

      setTranslation(arma::randu<arma::Col<double>>(numberOfDimensions_) * 8.0 - 4.0);
      setOne(arma::zeros<arma::Col<double>>(numberOfDimensions_) + (std::bernoulli_distribution(0.5)(Rng::generator) ? 1.0 : -1.0));
      setRotationR(getRandomRotationMatrix(numberOfDimensions_));
      setRotationQ(getRandomRotationMatrix(numberOfDimensions_));
      setDeltaC101(getRandomDeltaC101());
      setLocalOptimaY101(getRandomLocalOptimaY101());
      setDeltaC21(getRandomDeltaC21());
      setLocalOptimaY21(getRandomLocalOptimaY21());
    }

    void BlackBoxOptimisationBenchmark2013::setTranslation(
        const arma::Col<double>& translation) {
      if (translation.n_elem != numberOfDimensions_) {
        throw std::logic_error("The number of dimensions of the translation (" + std::to_string(translation.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
      }

      translation_ = translation;
    }

    void BlackBoxOptimisationBenchmark2013::setOne(
        const arma::Col<double>& one) {
      if (one.n_elem != numberOfDimensions_) {
        throw std::logic_error("The number of dimensions of the one vector (" + std::to_string(one.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
      }

      one_ = one;
    }

    void BlackBoxOptimisationBenchmark2013::setRotationR(
        const arma::Mat<double>& rotationR) {
      if (!rotationR.is_square()) {
        throw std::logic_error("The rotation matrix (" + std::to_string(rotationR.n_rows) + ", " + std::to_string(rotationR.n_cols) + ") must be square.");
      } else if (rotationR.n_rows != numberOfDimensions_) {
        throw std::logic_error("The number of dimensions of the parameter rotation maxtrix (" + std::to_string(rotationR.n_rows) + ", " + std::to_string(rotationR.n_cols) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
      } else if(arma::any(arma::vectorise(arma::abs(rotationR.i() - rotationR.t()) > 1e-15)) || std::abs(std::abs(arma::det(rotationR)) - 1) > 1e-15) {
        throw std::logic_error("The rotation matrix must be orthonormal and its determinant (" + std::to_string(arma::det(rotationR)) + ") equally to 1 or -1.");
      }

      rotationR_ = rotationR;
    }

    void BlackBoxOptimisationBenchmark2013::setRotationQ(
        const arma::Mat<double>& rotationQ) {
      if (!rotationQ.is_square()) {
        throw std::logic_error("The rotation matrix (" + std::to_string(rotationQ.n_rows) + ", " + std::to_string(rotationQ.n_cols) + ") must be square.");
      } else if (rotationQ.n_rows != numberOfDimensions_) {
        throw std::logic_error("The number of dimensions of the parameter rotation maxtrix (" + std::to_string(rotationQ.n_rows) + ", " + std::to_string(rotationQ.n_cols) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
      } else if(arma::any(arma::vectorise(arma::abs(rotationQ.i() - rotationQ.t()) > 1e-15)) || std::abs(std::abs(arma::det(rotationQ)) - 1) > 1e-15) {
        throw std::logic_error("The rotation matrix must be orthonormal and its determinant (" + std::to_string(arma::det(rotationQ)) + ") equally to 1 or -1.");
      }

      rotationQ_ = rotationQ;
    }

    void BlackBoxOptimisationBenchmark2013::setDeltaC101(
        const arma::Mat<double>& deltaC101) {
      if (deltaC101.n_rows != numberOfDimensions_) {
        throw std::logic_error("The number of dimensions of each delta (" + std::to_string(deltaC101.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
      } else if (deltaC101.n_cols != 101) {
        throw std::logic_error("The number of deltas (" + std::to_string(deltaC101.n_cols) + ") must be 101.");
      }

      deltaC101_ = deltaC101;
    }

    void BlackBoxOptimisationBenchmark2013::setLocalOptimaY101(
        const arma::Mat<double>& localOptimaY101) {
    if (localOptimaY101.n_rows != numberOfDimensions_) {
      throw std::logic_error("The number of dimensions of each local optimum (" + std::to_string(localOptimaY101.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
    } else if (localOptimaY101.n_cols != 101) {
      throw std::logic_error("The number of local optima (" + std::to_string(localOptimaY101.n_cols) + ") must be 101.");
    }

      localOptimaY101_ = localOptimaY101;
    }

    void BlackBoxOptimisationBenchmark2013::setDeltaC21(
        const arma::Mat<double>& deltaC21) {
      if (deltaC21.n_rows != numberOfDimensions_) {
        throw std::logic_error("The number of dimensions of each delta (" + std::to_string(deltaC21.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
      } else if (deltaC21.n_cols != 21) {
        throw std::logic_error("The number of deltas (" + std::to_string(deltaC21.n_cols) + ") must be 21.");
      }

      deltaC21_ = deltaC21;
    }

    void BlackBoxOptimisationBenchmark2013::setLocalOptimaY21(
        const arma::Mat<double>& localOptimaY21) {
      if (localOptimaY21.n_rows != numberOfDimensions_) {
        throw std::logic_error("The number of dimensions of each local optimum (" + std::to_string(localOptimaY21.n_rows) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(numberOfDimensions_) + ").");
      } else if (localOptimaY21.n_cols != 21) {
        throw std::logic_error("The number of local optima (" + std::to_string(localOptimaY21.n_cols) + ") must be 21.");
      }

      localOptimaY21_ = localOptimaY21;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomDeltaC101() const noexcept {
      arma::Mat<double> deltaC101(numberOfDimensions_, 101);
      deltaC101.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25);

      std::uniform_int_distribution<int> uniformIntDistribution(0, 99);
      for (std::size_t n = 1; n < deltaC101.n_cols; ++n) {
        deltaC101.col(n) = getScaling(sqrt(1000.0)) / pow(pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 99.0), 0.25);
      }

      return deltaC101;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomDeltaC21() const noexcept {
      arma::Mat<double> deltaC21(numberOfDimensions_, 21);
      deltaC21.col(0) = getScaling(std::sqrt(1000.0)) / std::pow(1000.0, 0.25);

      std::uniform_int_distribution<int> uniformIntDistribution(0, 19);
      for (std::size_t n = 1; n < deltaC21.n_cols; ++n) {
        deltaC21.col(n) = getScaling(sqrt(1000.0)) / std::pow(std::pow(1000.0, 2.0 * static_cast<double>(uniformIntDistribution(Rng::generator)) / 19.0), 0.25);
      }

      return deltaC21;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomLocalOptimaY101() const noexcept {
      arma::Mat<double> localOptimaY101 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 101) * 8.0 - 4.0;
      localOptimaY101.col(0) = 0.8 * localOptimaY101.col(0);

      return localOptimaY101;
    }

    arma::Mat<double> BlackBoxOptimisationBenchmark2013::getRandomLocalOptimaY21() const noexcept {
      arma::Mat<double> localOptimaY21 = arma::randu<arma::Mat<double>>(numberOfDimensions_, 21) * 9.8 - 4.9;
      localOptimaY21.col(0) = 0.8 * localOptimaY21.col(0);

      return localOptimaY21;
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getScaling(
        const double& condition) const noexcept {
      arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0, 1, numberOfDimensions_);

      for (auto& scale : scaling) {
        scale = std::pow(condition, scale);
      }

      return scaling;
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getScaling(
        const arma::Col<double>& condition) const noexcept {
      arma::Col<double> scaling = arma::linspace<arma::Col<double>>(0, 1, numberOfDimensions_);

      for (std::size_t n = 0; n < scaling.n_elem; ++n) {
        scaling.at(n) = std::pow(condition.at(n), scaling.at(n));
      }

      return scaling;
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getAsymmetricTransformation(
        const double& beta,
        const arma::Col<double>& parameter) const noexcept {
      arma::Col<double> asymmetricTransformation(parameter.n_elem);
      arma::Col<double> spacing = arma::linspace<arma::Col<double>>(0, 1, numberOfDimensions_);

      for (std::size_t n = 0; n < parameter.n_elem; ++n) {
        double value = parameter.at(n);

        if (value > 0.0) {
          asymmetricTransformation.at(n) = std::pow(value, 1 + beta * spacing.at(n) * std::sqrt(value));
        } else {
          asymmetricTransformation.at(n) = value;
        }
      }

      return asymmetricTransformation;
    }

    double BlackBoxOptimisationBenchmark2013::getOscillationTransformation(
        const double& value) const noexcept {
      if (value != 0.0) {
        double c1;
        double c2;
        if (value > 0.0) {
          c1 = 10.0;
          c2 = 7.9;
        } else {
          c1 = 5.5;
          c2 = 3.1;
        }

        double x = std::log(std::abs(value));
        return std::copysign(1.0, value) * std::exp(x + 0.049 * (std::sin(c1 * x) + std::sin(c2 * x)));
      } else {
        return 0.0;
      }
    }

    arma::Col<double> BlackBoxOptimisationBenchmark2013::getOscillationTransformation(
        const arma::Col<double>& parameter) const noexcept {
      arma::Col<double> oscillate(parameter.n_elem);

      for (std::size_t n = 0; n < parameter.n_elem; ++n) {
        oscillate.at(n) = getOscillationTransformation(parameter.at(n));
      }

      return oscillate;
    }

    double BlackBoxOptimisationBenchmark2013::getPenality(
        const arma::Col<double>& parameter) const noexcept {
      double penality = 0.0;

      for (std::size_t n = 0; n < parameter.n_elem; ++n) {
        penality += std::pow(std::max(0.0, std::abs(parameter.at(n)) - 5.0), 2.0);
      }

      return penality;
    }
  }
}
<|endoftext|>


<commit_before>/*
    This file is part of Kontact.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qlabel.h>
#include <qlayout.h>

#include <dcopclient.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>

#include "core.h"
#include "summary.h"
#include "summarywidget.h"

SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent, const char *name )
  : Kontact::Summary( parent, name ), mPlugin( plugin )
{
  QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
  QHBoxLayout *hbox = new QHBoxLayout( mainLayout, 3 );
  mLayout = new QGridLayout( mainLayout, 6, 3, 3 );
  mainLayout->addStretch();

  QFont boldFont;
  boldFont.setBold( true );
  boldFont.setPointSize( boldFont.pointSize() + 2 );

  QLabel *label = new QLabel( this );
  label->setFixedSize( 32, 32 );
  label->setPixmap( KGlobal::iconLoader()->loadIcon( "kmail", KIcon::Desktop,
                                                     KIcon::SizeMedium ) );
  hbox->addWidget( label );

  label = new QLabel( i18n( "EMails" ), this );
  label->setAlignment( AlignLeft );
  label->setFont( boldFont );
  hbox->addWidget( label );

  connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );
  mTimer.start( 0 );
}

void SummaryWidget::raisePart()
{
  QString dcopApp;

  // FIXME: select specific folder when 'selectFolder' dcop call is implemented
  if ( kapp->dcopClient()->isApplicationRegistered( "kmail" ) )
    dcopApp = "kmail";
  else {
    mPlugin->core()->selectPlugin( mPlugin );
    dcopApp = "kontact";
  }
}

void SummaryWidget::timeout()
{
  mTimer.stop();

  mLabels.setAutoDelete( true );
  mLabels.clear();
  mLabels.setAutoDelete( false );

  KConfig config( "kmailrc" );

  QStringList groups = config.groupList();
  groups.sort();

  int counter = 0;
  QStringList::Iterator it;
  for ( it = groups.begin(); it != groups.end() && counter < 6; ++it ) {
    if ( (*it).startsWith( QString::fromLatin1( "Folder-" ) ) ) { // hmm, that may fail...
      config.setGroup( *it );
      int numMsg = config.readNumEntry( "TotalMsgs", 0 );
      int numUnreadMsg = config.readNumEntry( "UnreadMsgs", 0 );
      KURLLabel *urlLabel = new KURLLabel( QString::null, (*it).mid( 7 ), this );
      urlLabel->setAlignment( AlignLeft );
      urlLabel->show();
      // ### FIXME emit dcop signal to jumo to actual folder
      connect( urlLabel, SIGNAL( leftClickedURL() ), SLOT( raisePart() ) );
      mLayout->addWidget( urlLabel, counter, 0 );
      mLabels.append( urlLabel );
      QLabel *label = new QLabel( QString( "%1 / %2" ).arg( numUnreadMsg ).arg( numMsg ), this );
      if ( numUnreadMsg > 0 ) {
        QFont font = label->font();
        font.setBold( true );
        label->setFont( font );
      }
      label->setAlignment( AlignLeft );
      label->show();
      mLayout->addWidget( label, counter, 0 );
      mLayout->addWidget( label, counter, 2 );
      mLabels.append( label );

      counter++;
    }
  }

  mTimer.start( 15 * 1000 );
}

#include "summarywidget.moc"
<commit_msg>Now the kmail summary displays only folders which contains unread messages or a label 'No unread messages' when there is no folder with unread messages.<commit_after>/*
    This file is part of Kontact.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qlabel.h>
#include <qlayout.h>

#include <dcopclient.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>

#include "core.h"
#include "summary.h"
#include "summarywidget.h"

SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent, const char *name )
  : Kontact::Summary( parent, name ), mPlugin( plugin )
{
  QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
  QHBoxLayout *hbox = new QHBoxLayout( mainLayout, 3 );
  mLayout = new QGridLayout( mainLayout, 6, 3, 3 );
  mainLayout->addStretch();

  QFont boldFont;
  boldFont.setBold( true );
  boldFont.setPointSize( boldFont.pointSize() + 2 );

  QLabel *label = new QLabel( this );
  label->setFixedSize( 32, 32 );
  label->setPixmap( KGlobal::iconLoader()->loadIcon( "kmail", KIcon::Desktop,
                                                     KIcon::SizeMedium ) );
  hbox->addWidget( label );

  label = new QLabel( i18n( "EMails" ), this );
  label->setAlignment( AlignLeft );
  label->setFont( boldFont );
  hbox->addWidget( label );

  connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );
  mTimer.start( 0 );
}

void SummaryWidget::raisePart()
{
  QString dcopApp;

  // FIXME: select specific folder when 'selectFolder' dcop call is implemented
  if ( kapp->dcopClient()->isApplicationRegistered( "kmail" ) )
    dcopApp = "kmail";
  else {
    mPlugin->core()->selectPlugin( mPlugin );
    dcopApp = "kontact";
  }
}

void SummaryWidget::timeout()
{
  mTimer.stop();

  mLabels.setAutoDelete( true );
  mLabels.clear();
  mLabels.setAutoDelete( false );

  KConfig config( "kmailrc" );

  QStringList groups = config.groupList();
  groups.sort();

  int counter = 0;
  QStringList::Iterator it;
  for ( it = groups.begin(); it != groups.end() && counter < 6; ++it ) {
    if ( (*it).startsWith( QString::fromLatin1( "Folder-" ) ) ) { // hmm, that may fail...
      config.setGroup( *it );
      int numMsg = config.readNumEntry( "TotalMsgs", 0 );
      int numUnreadMsg = config.readNumEntry( "UnreadMsgs", 0 );
      if ( numUnreadMsg != 0 ) {
        KURLLabel *urlLabel = new KURLLabel( QString::null, (*it).mid( 7 ), this );
        urlLabel->setAlignment( AlignLeft );
        urlLabel->show();
        // ### FIXME emit dcop signal to jumo to actual folder
        connect( urlLabel, SIGNAL( leftClickedURL() ), SLOT( raisePart() ) );
        mLayout->addWidget( urlLabel, counter, 0 );
        mLabels.append( urlLabel );
        QLabel *label = new QLabel( QString( "%1 / %2" ).arg( numUnreadMsg ).arg( numMsg ), this );

        label->setAlignment( AlignLeft );
        label->show();
        mLayout->addWidget( label, counter, 2 );
        mLabels.append( label );

        counter++;
      }
    }
  }

  if ( counter == 0 ) {
    QLabel *label = new QLabel( i18n( "No unread messages" ), this );
    label->show();
    mLayout->addMultiCellWidget( label, 1, 1, 1, 2 );
    mLabels.append( label );
  }

  mTimer.start( 15 * 1000 );
}

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


<commit_before>/*  -*- mode: C++; c-file-style: "gnu" -*-

  This file is part of Kontact.

  Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program 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 General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "summarywidget.h"
#include "kmailinterface.h"
#include "kmail_folder_interface.h"

#include <kontactinterfaces/core.h>

#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kurllabel.h>
#include <kparts/part.h>

#include <QLabel>
#include <QLayout>
#include <QPixmap>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QEvent>

#include <time.h>

#define DBUS_KMAIL "org.kde.kmail"

SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent )
  : Kontact::Summary( parent ), mPlugin( plugin )
{
  QDBusConnection::sessionBus().registerObject( "/MailSummary", this );
  QVBoxLayout *mainLayout = new QVBoxLayout( this );
  mainLayout->setSpacing( 3 );
  mainLayout->setMargin( 3 );

  QWidget *header = createHeader( this, "view-pim-mail", i18n( "New Messages" ) );
  mainLayout->addWidget( header );

  mLayout = new QGridLayout();
  mainLayout->addItem( mLayout );
  mLayout->setSpacing( 3 );
  mLayout->setRowStretch( 6, 1 );

  slotUnreadCountChanged();
  QDBusConnection::sessionBus().connect(
    QString(), "/KMail","org.kde.kmail.kmail", "unreadCountChanged",
    this, SLOT(slotUnreadCountChanged()) );
}

void SummaryWidget::selectFolder( const QString &folder )
{
  if ( mPlugin->isRunningStandalone() ) {
    mPlugin->bringToForeground();
  } else {
    mPlugin->core()->selectPlugin( mPlugin );
  }

  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  kmail.selectFolder( folder );
}

void SummaryWidget::updateSummary( bool )
{
  // check whether we need to update the message counts
  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  const int timeOfLastMessageCountChange = kmail.timeOfLastMessageCountChange();
  if ( timeOfLastMessageCountChange > mTimeOfLastMessageCountUpdate ) {
    slotUnreadCountChanged();
  }
}

void SummaryWidget::slotUnreadCountChanged()
{
  kDebug();
  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  QDBusReply<QStringList> reply = kmail.folderList();
  if ( reply.isValid() ) {
    QStringList folderList = reply;
    updateFolderList( folderList );
  } else {
    kDebug() << "Calling kmail->KMailIface->folderList() via D-Bus failed.";
  }
  mTimeOfLastMessageCountUpdate = ::time( 0 );
}

void SummaryWidget::updateFolderList( const QStringList &folders )
{
  qDeleteAll( mLabels );
  mLabels.clear();

  KConfig _config( "kcmkmailsummaryrc" );
  KConfigGroup config( &_config, "General" );

  QStringList activeFolders;
  if ( !config.hasKey( "ActiveFolders" ) ) {
    activeFolders << "/Local/inbox";
  } else {
    activeFolders = config.readEntry( "ActiveFolders", QStringList() );
  }

  int counter = 0;
  QStringList::ConstIterator it;
  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  for ( it = folders.begin(); it != folders.end(); ++it ) {
    if ( activeFolders.contains( *it ) ) {
      QDBusReply<QString> ref = kmail.getFolder( *it );
      if ( ref.isValid() && !ref.value().isEmpty() ) {
        OrgKdeKmailFolderInterface folderInterface(
          DBUS_KMAIL, "/Folder", QDBusConnection::sessionBus() );
        QDBusReply<int> replyNumMsg = folderInterface.messages();
        const int numMsg = replyNumMsg;
        QDBusReply<int> replyUnreadNumMsg = folderInterface.unreadMessages();
        const int numUnreadMsg=replyUnreadNumMsg;

        if ( numUnreadMsg == 0 ) {
          continue;
        }

        QString folderPath;
        QDBusReply<QString> replyFolderPath;
        if ( config.readEntry( "ShowFullPath", true ) ) {
          replyFolderPath= folderInterface.displayPath();
        } else {
          replyFolderPath= folderInterface.displayName();
        }
        folderPath = replyFolderPath;
        KUrlLabel *urlLabel = new KUrlLabel( *it, folderPath, this );
        urlLabel->installEventFilter( this );
        urlLabel->setAlignment( Qt::AlignLeft );
        urlLabel->show();
        connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)),
                 SLOT(selectFolder(const QString&)) );
        mLayout->addWidget( urlLabel, counter, 0 );
        mLabels.append( urlLabel );

        QLabel *label = new QLabel( i18nc( "%1: number of unread messages "
                                           "%2: total number of messages", "%1 / %2",
                                           numUnreadMsg, numMsg ), this );
        label->setAlignment( Qt::AlignLeft );
        label->show();
        mLayout->addWidget( label, counter, 2 );
        mLabels.append( label );

        counter++;
      }
    }
  }

  if ( counter == 0 ) {
    QLabel *label = new QLabel( i18n( "No unread messages in your monitored folders" ), this );
    label->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
    mLayout->addWidget( label, 0, 0, 1, 3 );
    label->show();
    mLabels.append( label );
  }
}

bool SummaryWidget::eventFilter( QObject *obj, QEvent *e )
{
  if ( obj->inherits( "KUrlLabel" ) ) {
    KUrlLabel* label = static_cast<KUrlLabel*>( obj );
    if ( e->type() == QEvent::Enter ) {
      emit message( i18n( "Open Folder: \"%1\"", label->text() ) );
    }  if ( e->type() == QEvent::Leave ) {
      emit message( QString::null );	//krazy:exclude=nullstrassign for old broken gcc
    }
  }

  return Kontact::Summary::eventFilter( obj, e );
}

QStringList SummaryWidget::configModules() const
{
  return QStringList( "kcmkmailsummary.desktop" );
}

#include "summarywidget.moc"
<commit_msg>Backport r880597 by winterz from trunk to the 4.1 branch:<commit_after>/*  -*- mode: C++; c-file-style: "gnu" -*-

  This file is part of Kontact.

  Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program 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 General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "summarywidget.h"
#include "kmailinterface.h"
#include "kmail_folder_interface.h"

#include <kontactinterfaces/core.h>

#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kurllabel.h>
#include <kparts/part.h>

#include <QLabel>
#include <QLayout>
#include <QPixmap>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QEvent>

#include <time.h>

#define DBUS_KMAIL "org.kde.kmail"

SummaryWidget::SummaryWidget( Kontact::Plugin *plugin, QWidget *parent )
  : Kontact::Summary( parent ), mPlugin( plugin )
{
  QDBusConnection::sessionBus().registerObject( "/MailSummary", this );
  QVBoxLayout *mainLayout = new QVBoxLayout( this );
  mainLayout->setSpacing( 3 );
  mainLayout->setMargin( 3 );

  QWidget *header = createHeader( this, "view-pim-mail", i18n( "New Messages" ) );
  mainLayout->addWidget( header );

  mLayout = new QGridLayout();
  mainLayout->addItem( mLayout );
  mLayout->setSpacing( 3 );
  mLayout->setColumnStretch( 1, 1 );
  mLayout->setRowStretch( 6, 1 );

  slotUnreadCountChanged();
  QDBusConnection::sessionBus().connect(
    QString(), "/KMail","org.kde.kmail.kmail", "unreadCountChanged",
    this, SLOT(slotUnreadCountChanged()) );
}

void SummaryWidget::selectFolder( const QString &folder )
{
  if ( mPlugin->isRunningStandalone() ) {
    mPlugin->bringToForeground();
  } else {
    mPlugin->core()->selectPlugin( mPlugin );
  }

  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  kmail.selectFolder( folder );
}

void SummaryWidget::updateSummary( bool )
{
  // check whether we need to update the message counts
  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  const int timeOfLastMessageCountChange = kmail.timeOfLastMessageCountChange();
  if ( timeOfLastMessageCountChange > mTimeOfLastMessageCountUpdate ) {
    slotUnreadCountChanged();
  }
}

void SummaryWidget::slotUnreadCountChanged()
{
  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  QDBusReply<QStringList> reply = kmail.folderList();
  if ( reply.isValid() ) {
    QStringList folderList = reply;
    updateFolderList( folderList );
  } else {
    kDebug() << "Calling kmail->KMailIface->folderList() via D-Bus failed.";
  }
  mTimeOfLastMessageCountUpdate = ::time( 0 );
}

void SummaryWidget::updateFolderList( const QStringList &folders )
{
  qDeleteAll( mLabels );
  mLabels.clear();

  KConfig _config( "kcmkmailsummaryrc" );
  KConfigGroup config( &_config, "General" );

  QStringList activeFolders;
  if ( !config.hasKey( "ActiveFolders" ) ) {
    activeFolders << "/Local/inbox";
  } else {
    activeFolders = config.readEntry( "ActiveFolders", QStringList() );
  }

  QLabel *label = 0;
  int counter = 0;
  QStringList::ConstIterator it;
  org::kde::kmail::kmail kmail( DBUS_KMAIL, "/KMail", QDBusConnection::sessionBus() );
  for ( it = folders.begin(); it != folders.end(); ++it ) {
    if ( activeFolders.contains( *it ) ) {
      QDBusReply<QString> ref = kmail.getFolder( *it );
      if ( ref.isValid() && !ref.value().isEmpty() ) {
        OrgKdeKmailFolderInterface folderInterface(
          DBUS_KMAIL, "/Folder", QDBusConnection::sessionBus() );
        QDBusReply<int> replyNumMsg = folderInterface.messages();
        const int numMsg = replyNumMsg;
        QDBusReply<int> replyUnreadNumMsg = folderInterface.unreadMessages();
        const int numUnreadMsg=replyUnreadNumMsg;

        if ( numUnreadMsg == 0 ) {
          continue;
        }

        QString folderPath;
        QDBusReply<QString> replyFolderPath;
        if ( config.readEntry( "ShowFullPath", true ) ) {
          replyFolderPath= folderInterface.displayPath();
        } else {
          replyFolderPath= folderInterface.displayName();
        }
        folderPath = replyFolderPath;
        KUrlLabel *urlLabel = new KUrlLabel( *it, folderPath, this );
        urlLabel->installEventFilter( this );
        urlLabel->setAlignment( Qt::AlignLeft );
        mLayout->addWidget( urlLabel, counter, 0 );
        mLabels.append( urlLabel );

        connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)),
                 SLOT(selectFolder(const QString&)) );

        label = new QLabel( i18nc( "%1: number of unread messages "
                                   "%2: total number of messages",
                                   "%1 / %2", numUnreadMsg, numMsg ), this );
        label->setAlignment( Qt::AlignLeft );
        mLayout->addWidget( label, counter, 1 );
        mLabels.append( label );

        counter++;
      }
    }
  }

  if ( counter == 0 ) {
    label = new QLabel( i18n( "No unread messages in your monitored folders" ), this );
    label->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
    mLayout->addWidget( label, 0, 2 );
    mLabels.append( label );
  }

  QList<QLabel*>::iterator lit;
  for ( lit = mLabels.begin(); lit != mLabels.end(); ++lit ) {
    (*lit)->show();
  }
}

bool SummaryWidget::eventFilter( QObject *obj, QEvent *e )
{
  if ( obj->inherits( "KUrlLabel" ) ) {
    KUrlLabel* label = static_cast<KUrlLabel*>( obj );
    if ( e->type() == QEvent::Enter ) {
      emit message( i18n( "Open Folder: \"%1\"", label->text() ) );
    }  if ( e->type() == QEvent::Leave ) {
      emit message( QString::null );	//krazy:exclude=nullstrassign for old broken gcc
    }
  }

  return Kontact::Summary::eventFilter( obj, e );
}

QStringList SummaryWidget::configModules() const
{
  return QStringList( "kcmkmailsummary.desktop" );
}

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


<commit_before>/*************************************************************************
 *
 *  $RCSfile: pszctrl.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 17:00:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser 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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVX_PSZCTRL_HXX
#define _SVX_PSZCTRL_HXX

// include ---------------------------------------------------------------

#ifndef _SFXSTBITEM_HXX //autogen
#include <sfx2/stbitem.hxx>
#endif

// forward ---------------------------------------------------------------

class  SvxSizeItem;
struct SvxPosSizeStatusBarControl_Impl;

// class SvxPosSizeToolBoxControl ----------------------------------------

class SvxPosSizeStatusBarControl : public SfxStatusBarControl
{
private:
    SvxPosSizeStatusBarControl_Impl*    pImp;

    SfxStatusForwarder                  aPosForwarder;
    SfxStatusForwarder                  aTableForwarder;
    SfxStatusForwarder                  aFuncForwarder;

public:
    SFX_DECL_STATUSBAR_CONTROL();

    SvxPosSizeStatusBarControl( USHORT nId, StatusBar& rStb, SfxBindings& rBind );
    ~SvxPosSizeStatusBarControl();

    virtual void    StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState );
    virtual void    Paint( const UserDrawEvent& rEvt );
    virtual void    Command( const CommandEvent& rCEvt );

    static ULONG    GetDefItemWidth( const StatusBar& rStb );
};

#endif

<commit_msg>INTEGRATION: CWS toolbars2 (1.1.1.1.936); FILE MERGED 2004/08/18 13:47:03 cd 1.1.1.1.936.2: #i32219# Adapt status bar controller to new base class 2004/08/11 10:44:50 cd 1.1.1.1.936.1: #i32219# Adapt statusbar controller to new base class<commit_after>/*************************************************************************
 *
 *  $RCSfile: pszctrl.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-09-09 15:37:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser 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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVX_PSZCTRL_HXX
#define _SVX_PSZCTRL_HXX

// include ---------------------------------------------------------------

#ifndef _SFXSTBITEM_HXX //autogen
#include <sfx2/stbitem.hxx>
#endif

// forward ---------------------------------------------------------------

class  SvxSizeItem;
struct SvxPosSizeStatusBarControl_Impl;

// class SvxPosSizeToolBoxControl ----------------------------------------

class SvxPosSizeStatusBarControl : public SfxStatusBarControl
{
private:
    SvxPosSizeStatusBarControl_Impl*    pImp;
public:
    SFX_DECL_STATUSBAR_CONTROL();

    SvxPosSizeStatusBarControl( USHORT nSlotId, USHORT nId, StatusBar& rStb );
    ~SvxPosSizeStatusBarControl();

    virtual void    StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState );
    virtual void    Paint( const UserDrawEvent& rEvt );
    virtual void    Command( const CommandEvent& rCEvt );

    static ULONG    GetDefItemWidth( const StatusBar& rStb );
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fmtflcnt.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-07-04 13:19:06 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser 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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FMTFLCNT_HXX
#define _FMTFLCNT_HXX

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

class SwFrmFmt;
// ATT_FLYCNT *******************************************************

class SwFmtFlyCnt : public SfxPoolItem
{
    friend class SwTxtFlyCnt;
    SwTxtFlyCnt* pTxtAttr;      // mein TextAttribut
    SwFrmFmt* pFmt;             // mein Fly/DrawFrame-Format
    // geschuetzter CopyCtor
    SwFmtFlyCnt& operator=(const SwFmtFlyCnt& rFlyCnt);

public:
    SwFmtFlyCnt( SwFrmFmt *pFrmFmt );
    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, USHORT nVer) const;
    virtual SvStream&       Store(SvStream &, USHORT nIVer) const;

    inline SwFrmFmt *GetFrmFmt() const { return pFmt; }
    // fuer Undo: loesche "logisch" das FlyFrmFormat, wird sich im
    //          Undo-Object gemerkt.
    inline void SetFlyFmt( SwFrmFmt* pNew = 0 )   { pFmt = pNew; }

    const SwTxtFlyCnt *GetTxtFlyCnt() const { return pTxtAttr; }
          SwTxtFlyCnt *GetTxtFlyCnt()       { return pTxtAttr; }

    // OD 27.06.2003 #108784#
    const bool Sw3ioExportAllowed() const;
};

#endif

<commit_msg>INTEGRATION: CWS os44 (1.2.720); FILE MERGED 2004/11/24 13:57:06 os 1.2.720.1: #i37761# sw3io files removed<commit_after>/*************************************************************************
 *
 *  $RCSfile: fmtflcnt.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-05 15:50:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser 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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FMTFLCNT_HXX
#define _FMTFLCNT_HXX

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

class SwFrmFmt;
// ATT_FLYCNT *******************************************************

class SwFmtFlyCnt : public SfxPoolItem
{
    friend class SwTxtFlyCnt;
    SwTxtFlyCnt* pTxtAttr;      // mein TextAttribut
    SwFrmFmt* pFmt;             // mein Fly/DrawFrame-Format
    // geschuetzter CopyCtor
    SwFmtFlyCnt& operator=(const SwFmtFlyCnt& rFlyCnt);

public:
    SwFmtFlyCnt( SwFrmFmt *pFrmFmt );
    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;

    inline SwFrmFmt *GetFrmFmt() const { return pFmt; }
    // fuer Undo: loesche "logisch" das FlyFrmFormat, wird sich im
    //          Undo-Object gemerkt.
    inline void SetFlyFmt( SwFrmFmt* pNew = 0 )   { pFmt = pNew; }

    const SwTxtFlyCnt *GetTxtFlyCnt() const { return pTxtAttr; }
          SwTxtFlyCnt *GetTxtFlyCnt()       { return pTxtAttr; }

    // OD 27.06.2003 #108784#
    const bool Sw3ioExportAllowed() const;
};

#endif

<|endoftext|>


<commit_before>#define _CRT_SECURE_NO_WARNINGS
#include <SWI-cpp.h>
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include "programpath.h"

#define WORLD_LEN 6

using namespace std;

enum Obstacle {abismo = FOREGROUND_GREEN, morcego = FOREGROUND_BLUE, wumpos = FOREGROUND_RED};
enum Reward {ouro = FOREGROUND_BLUE|FOREGROUND_RED };
enum Direction {NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3};
enum Sensor {NONE, WALL, BREEZE, STINK, SCREAM, GLITTER};

static const char * sensorString[] = {
	"None", "Wall", "Breeze", "Stink", "Scream", "Glitter"
};

static void initializeWorld();
static void restartWorld();
static void removeAll();
static void printWorld();
static void clearWorld();
static void getDirection();
static void printColor(char *, int);

/* Agent actions */
static void walk();
static void turn();
static void turn(int);
static void shoot();

static void getObstacle();
static void getReward();
static void getAgentPosition();
static int getScore();
static Sensor getSensor();

static bool isAlive();
static bool isSensorInAgentPosition(Sensor);
static bool isSensorInPosition(int, int, Sensor);

char world[WORLD_LEN][WORLD_LEN];
int posx = 1;
int posy = 1;
Direction direction = NORTH;

int main(void) {
	char* argv[] = {"swipl.dll", "-s", PROGRAM_PATH};  //Argumentos para a inicializao do prolog, incluindo o caminho para o
													   //arquivo do programa prolog que sera carregado (Ex: "D:\\teste.pl")

	PlEngine e(3, argv);
	restartWorld();
	turn();
	turn();
	for (int i = 0; i < 3; i++) {
		printWorld();
		walk();
		printf("\n");
	}
	_getch();
	return 1;
}

static void clearWorld() {
	for (int i = 0; i < WORLD_LEN; i++)
		for (int j = 0; j < WORLD_LEN; j++)
			world[j][i] = 0;
}

static void initializeWorld() {
	PlCall("gerarMundoRandomico", NULL);
}

static void restartWorld() {
	PlCall("reiniciarR", NULL);
}

static void removeAll() {
	PlCall("removeTudo", NULL);
}

static void getDirection() {
	PlTermv av(1);
	PlQuery q("direcao", av);
	char *dir;
	while (q.next_solution()) {
		dir = (char *)av[0];
		printf("Direcao : %s\n", dir);
		if (strcmp(dir, "norte") == 0)
			direction = NORTH;
		else if (strcmp(dir, "leste") == 0)
			direction = EAST;
		else if (strcmp(dir, "sul") == 0)
			direction = SOUTH;
		else if (strcmp(dir, "oeste") == 0)
			direction = WEST;
	}
}

static void printWorld() {
	clearWorld();
	getReward();
	getObstacle();
	getDirection();
	for (int y = 0; y < WORLD_LEN; y++) {
		for (int x = 0; x < WORLD_LEN; x++) {

			if (x == posx - 1 && y == posy - 1) {
				char d[2];
				d[1] = '\0';
				switch (direction) {
				case NORTH: d[0] = 'N';
					break;
				case EAST: d[0] = 'E';
					break;
				case SOUTH: d[0] = 'S';
					break;
				case WEST: d[0] = 'W';
					break;
				default: d[0] = 'G';
				}
				printColor(d, FOREGROUND_RED | FOREGROUND_GREEN);
				printf(" ");
				continue;
			}

			switch (world[y][x]) {
			case abismo  : printColor("A ", world[y][x]);
				break;
			case wumpos  : printColor("W ", world[y][x]);
				break;
			case morcego : printColor("M ", world[y][x]);
				break;
			case ouro    : printColor("O ", world[y][x]);
				break;
			default      : printf("X ");
			}
		}
		printf("\n");
	}
	printf("Score: %d", getScore());
	printf("\n");

	printf("Player is ");
	printColor(isAlive() ? "alive" : "dead", isAlive() ? FOREGROUND_GREEN : FOREGROUND_RED);
	printf("\n");

	printf("Current sensor: %s", sensorString[getSensor()]);
	printf("\n");
}

static void getObstacle() {
	PlTermv av(3);
	PlQuery q("obstaculo", av);
	int x, y;
	char *obs;
	Obstacle color;
	while (q.next_solution()) {
		obs = av[2];
		if (strcmp("abismo", obs) == 0) {
			color = abismo;
		}
		else if (strcmp("wumpos", obs) == 0) {
			color = wumpos;
		}
		else if (strcmp("morcego", obs) == 0) {
			color = morcego;
		}
		x = (int)av[0] - 1;
		y = (int)av[1] - 1;
		world[y][x] = color;
	}
}

static void getReward() {
	PlTermv av(3);
	PlQuery q("recompensa", av);
	int x, y;
	Reward color = ouro;
	while (q.next_solution()) {
		x = (int) av[0] - 1;
		y = (int) av[1] - 1;
		world[y][x] = color;
	}
}

static void getAgentPosition() {
	PlTermv av(2);
	PlQuery q("posicao", av);
	while (q.next_solution()) {
		posx = (int) av[0];
		posy = (int) av[1];
	}
}

static int getScore() {
	int score = 0;
	PlTermv av(1);
	PlQuery q("pontuacao", av);
	while (q.next_solution()) {
		score = (int) av[0];
	}
	return score;
}

static Sensor getSensor() {
	if (isSensorInAgentPosition(WALL)) {
		return WALL;
	}
	if (isSensorInAgentPosition(BREEZE)) {
		return BREEZE;
	}
	if (isSensorInAgentPosition(STINK)) {
		return STINK;
	}
	if (isSensorInAgentPosition(SCREAM)) {
		return SCREAM;
	}
	if (isSensorInAgentPosition(GLITTER)) {
		return GLITTER;
	}
}

static bool isSensorInAgentPosition(Sensor sensor) {
	return isSensorInPosition(posx, posy, sensor);
}

static bool isSensorInPosition(int x, int y, Sensor sensor) {
	bool result;
	char* query = "";
	switch (sensor) {
		case  WALL:
			query = "parede";
			break;
		case BREEZE:
			query = "brisa";
			break;
		case STINK:
			query = "fedor";
			break;
		case SCREAM:
			query = "grito";
			break;
		case GLITTER:
			query = "brilho";
			break;
		case NONE:
		default:
			return false;
	}
	PlTermv av(2);
	PlQuery q(query, av);
	av[0] = x;
	av[1] = y;
 	return q.next_solution();
}

static bool isAlive() {
	char *state = "";
	PlTermv av(1);
	PlQuery q("estado", av);
	while (q.next_solution()) {
		state = (char *) av[0];
	}
	return strcmp(state, "vivo") == 0;
}

static void printColor(char *txt, int color) {
	HANDLE console;
	CONSOLE_SCREEN_BUFFER_INFO info;
	console = GetStdHandle(STD_OUTPUT_HANDLE);
	GetConsoleScreenBufferInfo(console, &info);
	SetConsoleTextAttribute(console, color);
	printf("%s", txt);
	SetConsoleTextAttribute(console, info.wAttributes);
}

static void walk() {
	PlCall("andar", NULL);
	getAgentPosition();
}

static void turn() {
	PlCall("virar", NULL);
}

static void turn(int n) {
	PlTermv av(1);
	av[0] = n;
	PlCall("virar", av);
}

static void shoot() {
	PlCall("atirar", NULL);
}
<commit_msg>Allow multiple sensors to display for a position<commit_after>#define _CRT_SECURE_NO_WARNINGS
#include <SWI-cpp.h>
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include "programpath.h"

#define WORLD_LEN 6

using namespace std;

enum Obstacle {abismo = FOREGROUND_GREEN, morcego = FOREGROUND_BLUE, wumpos = FOREGROUND_RED};
enum Reward {ouro = FOREGROUND_BLUE|FOREGROUND_RED };
enum Direction {NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3};
enum Sensor {NONE, WALL, BREEZE, STINK, SCREAM, GLITTER};

static const char * sensorsStrings[] = {
	"None", "Wall", "Breeze", "Stink", "Scream", "Glitter"
};

static void initializeWorld();
static void restartWorld();
static void removeAll();
static void printWorld();
static void clearWorld();
static void getDirection();
static void printColor(char *, int);

/* Agent actions */
static void walk();
static void turn();
static void turn(int);
static void shoot();

static void getObstacle();
static void getReward();
static void getAgentPosition();
static int getScore();
static void getSensors(bool *);
static void getSensorsString(bool *, char *);

static bool isAlive();
static bool isSensorInAgentPosition(Sensor);
static bool isSensorInPosition(int, int, Sensor);

char world[WORLD_LEN][WORLD_LEN];
int posx = 1;
int posy = 1;
Direction direction = NORTH;

int main(void) {
	char* argv[] = {"swipl.dll", "-s", PROGRAM_PATH};  //Argumentos para a inicializao do prolog, incluindo o caminho para o
													   //arquivo do programa prolog que sera carregado (Ex: "D:\\teste.pl")

	PlEngine e(3, argv);
	restartWorld();
	turn();
	turn();
	for (int i = 0; i < 3; i++) {
		printWorld();
		walk();
		printf("\n");
	}
	_getch();
	return 1;
}

static void clearWorld() {
	for (int i = 0; i < WORLD_LEN; i++)
		for (int j = 0; j < WORLD_LEN; j++)
			world[j][i] = 0;
}

static void initializeWorld() {
	PlCall("gerarMundoRandomico", NULL);
}

static void restartWorld() {
	PlCall("reiniciarR", NULL);
}

static void removeAll() {
	PlCall("removeTudo", NULL);
}

static void getDirection() {
	PlTermv av(1);
	PlQuery q("direcao", av);
	char *dir;
	while (q.next_solution()) {
		dir = (char *)av[0];
		printf("Direcao : %s\n", dir);
		if (strcmp(dir, "norte") == 0)
			direction = NORTH;
		else if (strcmp(dir, "leste") == 0)
			direction = EAST;
		else if (strcmp(dir, "sul") == 0)
			direction = SOUTH;
		else if (strcmp(dir, "oeste") == 0)
			direction = WEST;
	}
}

static void printWorld() {
	clearWorld();
	getReward();
	getObstacle();
	getDirection();
	for (int y = 0; y < WORLD_LEN; y++) {
		for (int x = 0; x < WORLD_LEN; x++) {

			if (x == posx - 1 && y == posy - 1) {
				char d[2];
				d[1] = '\0';
				switch (direction) {
				case NORTH: d[0] = 'N';
					break;
				case EAST: d[0] = 'E';
					break;
				case SOUTH: d[0] = 'S';
					break;
				case WEST: d[0] = 'W';
					break;
				default: d[0] = 'G';
				}
				printColor(d, FOREGROUND_RED | FOREGROUND_GREEN);
				printf(" ");
				continue;
			}

			switch (world[y][x]) {
			case abismo  : printColor("A ", world[y][x]);
				break;
			case wumpos  : printColor("W ", world[y][x]);
				break;
			case morcego : printColor("M ", world[y][x]);
				break;
			case ouro    : printColor("O ", world[y][x]);
				break;
			default      : printf("X ");
			}
		}
		printf("\n");
	}
	printf("Score: %d", getScore());
	printf("\n");

	printf("Player is ");
	printColor(isAlive() ? "alive" : "dead", isAlive() ? FOREGROUND_GREEN : FOREGROUND_RED);
	printf("\n");

	bool sensors[6] = { false, false, false, false, false };
	char str[255] = "";
	getSensors(sensors);
	getSensorsString(sensors, str);
	printf("Current sensors: %s", str);
	printf("\n");
}

static void getObstacle() {
	PlTermv av(3);
	PlQuery q("obstaculo", av);
	int x, y;
	char *obs;
	Obstacle color;
	while (q.next_solution()) {
		obs = av[2];
		if (strcmp("abismo", obs) == 0) {
			color = abismo;
		}
		else if (strcmp("wumpos", obs) == 0) {
			color = wumpos;
		}
		else if (strcmp("morcego", obs) == 0) {
			color = morcego;
		}
		x = (int)av[0] - 1;
		y = (int)av[1] - 1;
		world[y][x] = color;
	}
}

static void getReward() {
	PlTermv av(3);
	PlQuery q("recompensa", av);
	int x, y;
	Reward color = ouro;
	while (q.next_solution()) {
		x = (int) av[0] - 1;
		y = (int) av[1] - 1;
		world[y][x] = color;
	}
}

static void getAgentPosition() {
	PlTermv av(2);
	PlQuery q("posicao", av);
	while (q.next_solution()) {
		posx = (int) av[0];
		posy = (int) av[1];
	}
}

static int getScore() {
	int score = 0;
	PlTermv av(1);
	PlQuery q("pontuacao", av);
	while (q.next_solution()) {
		score = (int) av[0];
	}
	return score;
}

void getSensorsString(bool * sensors, char * str) {
	for (int i = 0; i < 6; i++) {
		if (sensors[i]) {
			strcat(str, sensorsStrings[i]);
			strcat(str, ", ");
		}
	}
}

static void getSensors(bool *sensors) {
	if (isSensorInAgentPosition(WALL)) {
		sensors[WALL] = true;
	}
	if (isSensorInAgentPosition(BREEZE)) {
		sensors[BREEZE] = true;
	}
	if (isSensorInAgentPosition(STINK)) {
		sensors[STINK] = true;
	}
	if (isSensorInAgentPosition(SCREAM)) {
		sensors[SCREAM] = true;
	}
	if (isSensorInAgentPosition(GLITTER)) {
		sensors[GLITTER] = true;
	}
}

static bool isSensorInAgentPosition(Sensor sensor) {
	return isSensorInPosition(posx, posy, sensor);
}

static bool isSensorInPosition(int x, int y, Sensor sensor) {
	char* query = "";
	switch (sensor) {
		case  WALL:
			query = "parede";
			break;
		case BREEZE:
			query = "brisa";
			break;
		case STINK:
			query = "fedor";
			break;
		case SCREAM:
			query = "grito";
			break;
		case GLITTER:
			query = "brilho";
			break;
		case NONE:
		default:
			return false;
	}
	PlTermv av(2);
	PlQuery q(query, av);
	av[0] = x;
	av[1] = y;
 	return q.next_solution();
}

static bool isAlive() {
	char *state = "";
	PlTermv av(1);
	PlQuery q("estado", av);
	while (q.next_solution()) {
		state = (char *) av[0];
	}
	return strcmp(state, "vivo") == 0;
}

static void printColor(char *txt, int color) {
	HANDLE console;
	CONSOLE_SCREEN_BUFFER_INFO info;
	console = GetStdHandle(STD_OUTPUT_HANDLE);
	GetConsoleScreenBufferInfo(console, &info);
	SetConsoleTextAttribute(console, color);
	printf("%s", txt);
	SetConsoleTextAttribute(console, info.wAttributes);
}

static void walk() {
	PlCall("andar", NULL);
	getAgentPosition();
}

static void turn() {
	PlCall("virar", NULL);
}

static void turn(int n) {
	PlTermv av(1);
	av[0] = n;
	PlCall("virar", av);
}

static void shoot() {
	PlCall("atirar", NULL);
}
<|endoftext|>


<commit_before>#include "quadrature/factory/quadrature_factories.h"

#include "quadrature/angular/scalar_angular.h"
#include "quadrature/angular/level_symmetric_gaussian.h"
#include "quadrature/ordinate.h"
#include "quadrature/quadrature_point.h"
#include "quadrature/quadrature_set.h"
#include "quadrature/utility/quadrature_utilities.h"

#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/test_helper_functions.h"

namespace  {

using namespace bart;

/* These tests verify the operation of the functions in quadrature::factory
 * that are designed to instantiate the different implementations of all the
 * classes in the quadrature namespace. As they actually instantiate classes,
 * they are integration tests, as they require the instantiated classes to be
 * implemented in some form.
 */
template <typename DimensionWrapper>
class QuadratureFactoriesIntegrationTest : public ::testing::Test {
 public:
  static constexpr int dim = DimensionWrapper::value;
};

TYPED_TEST_CASE(QuadratureFactoriesIntegrationTest, bart::testing::AllDimensions);

/* Call to MakeOrdinate specifying default implementation of OrdinateI should
 * return the correct type.
 */
TYPED_TEST(QuadratureFactoriesIntegrationTest, MakeOrdinate) {
  constexpr int dim = this->dim;
  auto ordinate_ptr = quadrature::factory::MakeOrdinatePtr<dim>(
      quadrature::OrdinateType::kDefault);

  ASSERT_NE(nullptr, ordinate_ptr);

  using ExpectedType = quadrature::Ordinate<dim>;
  EXPECT_NE(nullptr, dynamic_cast<ExpectedType*>(ordinate_ptr.get()));
}

/* Call to MakeQuadraturePoint specifying default implementation of
 * QuadraturePoint should return the correct type.
 */
TYPED_TEST(QuadratureFactoriesIntegrationTest, MakeQuadraturePoint) {
  constexpr int dim = this->dim;
  auto quadrature_point_ptr = quadrature::factory::MakeQuadraturePointPtr<dim>(
      quadrature::QuadraturePointImpl::kDefault);

  ASSERT_NE(nullptr, quadrature_point_ptr);

  using ExpectedType = quadrature::QuadraturePoint<dim>;
  EXPECT_NE(nullptr, dynamic_cast<ExpectedType*>(quadrature_point_ptr.get()));
}

/* Call to MakeAngularQuadratureGeneratorPtr specifying no type should return
 * a runtime error. */
TYPED_TEST(QuadratureFactoriesIntegrationTest,
    MakeAngularQuadratureGenTestNoType) {
  constexpr int dim = this->dim;
  const int order_value = 4;

  EXPECT_ANY_THROW({
    quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
        quadrature::Order(order_value),
        quadrature::AngularQuadratureSetType::kNone);
  });
}

/* Call to MakeAngularQuadratureGeneratorPtr specifying a scalar quadrature
 * should return the correct type. */
TYPED_TEST(QuadratureFactoriesIntegrationTest,
           MakeAngularQuadratureGenTestScalar) {
  constexpr int dim = this->dim;
  const int order_value = 4;

  auto quadrature_generator_ptr =
      quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
          quadrature::Order(order_value),
          quadrature::AngularQuadratureSetType::kScalar);

  ASSERT_NE(nullptr, quadrature_generator_ptr);
  using ExpectedType = quadrature::angular::ScalarAngular<dim>;
  EXPECT_NE(nullptr,
      dynamic_cast<ExpectedType*>(quadrature_generator_ptr.get()));
  EXPECT_EQ(quadrature_generator_ptr->order(), 0);
}

/* Call to MakeAngularQuadratureGeneratorPtr specifying a level symmetric gaussian
 * should return the correct type. If dim !=3, should throw an error */
TYPED_TEST(QuadratureFactoriesIntegrationTest,
           MakeAngularQuadratureGenTestLSGaussian) {
  constexpr int dim = this->dim;
  const int order_value = 4;
  if (dim == 3) {
        auto quadrature_generator_ptr =
        quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
            quadrature::Order(order_value),
            quadrature::AngularQuadratureSetType::kLevelSymmetricGaussian);

    ASSERT_NE(nullptr, quadrature_generator_ptr);
    using ExpectedType = quadrature::angular::LevelSymmetricGaussian;
    EXPECT_NE(nullptr,
              dynamic_cast<ExpectedType*>(quadrature_generator_ptr.get()));
    EXPECT_EQ(quadrature_generator_ptr->order(), order_value);
  } else {
    EXPECT_ANY_THROW({
      quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
          quadrature::Order(order_value),
          quadrature::AngularQuadratureSetType::kLevelSymmetricGaussian);
    });
  }
}

/* Call to MakeQuadratureSet specifying default implementation should return
 * the correct type. */
TYPED_TEST(QuadratureFactoriesIntegrationTest, MakeQuadratureSetTest) {
  constexpr int dim = this->dim;

  auto quadrature_set_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>(
      quadrature::QuadratureSetImpl::kDefault);

  ASSERT_NE(nullptr, quadrature_set_ptr);

  using ExpectedType = quadrature::QuadratureSet<dim>;

  ASSERT_NE(nullptr,
            dynamic_cast<ExpectedType*>(quadrature_set_ptr.get()));
}

TYPED_TEST(QuadratureFactoriesIntegrationTest, FillQuadratureSet) {
  const int dim = this->dim;
  const int n_points = 3;
  const int n_quadrants = std::pow(2, dim);

  // Generate random quadrature points
  std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight>>
      quadrature_points;

  for (int i = 0; i < n_points; ++i) {
    auto random_position = btest::RandomVector(dim, 1, 10);
    auto random_weight = btest::RandomDouble(0, 2);
    std::array<double, dim> position;
    for (int j = 0; j < dim; ++j)
      position.at(j) = random_position.at(j);
    quadrature_points.emplace_back(quadrature::CartesianPosition<dim>(position),
                                quadrature::Weight(random_weight));
  }

  // Distribute in all positive X quadrants
  auto distributed_points =
      quadrature::utility::GenerateAllPositiveX<dim>(quadrature_points);

  auto quadrature_set_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>();

  quadrature::factory::FillQuadratureSet<dim>(quadrature_set_ptr.get(),
                                              distributed_points);

  EXPECT_EQ(quadrature_set_ptr->size(), n_points*n_quadrants);

  for (const auto& quadrature_point_ptr : *quadrature_set_ptr) {

    // Verify this point is in the original set of points if it is all positive,
    // need to construct a pair to do this
    quadrature::CartesianPosition<dim> position(quadrature_point_ptr->ordinate()->cartesian_position());
    quadrature::Weight weight(quadrature_point_ptr->weight());

    if (std::all_of(position.get().cbegin(),
                    position.get().cend(), [](int i) { return i >=0;})) {
      auto point_pair = std::make_pair(position, weight);
      EXPECT_EQ(1, std::count(distributed_points.cbegin(), distributed_points.cend(),
                              point_pair));
    }

    // This point should have a reflection, whose reflection should be this point
    // and the reflection should have the opposite coordinate
    auto reflection_ptr = quadrature_set_ptr->GetReflection(quadrature_point_ptr);
    ASSERT_NE(nullptr, reflection_ptr);
    auto re_reflection_ptr = quadrature_set_ptr->GetReflection(reflection_ptr);
    EXPECT_EQ(re_reflection_ptr, quadrature_point_ptr);
    EXPECT_EQ(quadrature_point_ptr->weight(), reflection_ptr->weight());

    for (int i = 0; i < dim; ++i) {
      EXPECT_EQ(quadrature_point_ptr->ordinate()->cartesian_position().at(i),
                -reflection_ptr->ordinate()->cartesian_position().at(i));
    }
  }
}

TYPED_TEST(QuadratureFactoriesIntegrationTest, FillQuadratureSetScalar) {

}

} // namespace<commit_msg>added edge case tests for functionality of quadrature::factory::FillQuadrature<commit_after>#include "quadrature/factory/quadrature_factories.h"

#include "quadrature/angular/scalar_angular.h"
#include "quadrature/angular/level_symmetric_gaussian.h"
#include "quadrature/ordinate.h"
#include "quadrature/quadrature_point.h"
#include "quadrature/quadrature_set.h"
#include "quadrature/utility/quadrature_utilities.h"

#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/test_helper_functions.h"

namespace  {

using namespace bart;

/* These tests verify the operation of the functions in quadrature::factory
 * that are designed to instantiate the different implementations of all the
 * classes in the quadrature namespace. As they actually instantiate classes,
 * they are integration tests, as they require the instantiated classes to be
 * implemented in some form.
 */
template <typename DimensionWrapper>
class QuadratureFactoriesIntegrationTest : public ::testing::Test {
 public:
  static constexpr int dim = DimensionWrapper::value;
};

TYPED_TEST_CASE(QuadratureFactoriesIntegrationTest, bart::testing::AllDimensions);

/* Call to MakeOrdinate specifying default implementation of OrdinateI should
 * return the correct type.
 */
TYPED_TEST(QuadratureFactoriesIntegrationTest, MakeOrdinate) {
  constexpr int dim = this->dim;
  auto ordinate_ptr = quadrature::factory::MakeOrdinatePtr<dim>(
      quadrature::OrdinateType::kDefault);

  ASSERT_NE(nullptr, ordinate_ptr);

  using ExpectedType = quadrature::Ordinate<dim>;
  EXPECT_NE(nullptr, dynamic_cast<ExpectedType*>(ordinate_ptr.get()));
}

/* Call to MakeQuadraturePoint specifying default implementation of
 * QuadraturePoint should return the correct type.
 */
TYPED_TEST(QuadratureFactoriesIntegrationTest, MakeQuadraturePoint) {
  constexpr int dim = this->dim;
  auto quadrature_point_ptr = quadrature::factory::MakeQuadraturePointPtr<dim>(
      quadrature::QuadraturePointImpl::kDefault);

  ASSERT_NE(nullptr, quadrature_point_ptr);

  using ExpectedType = quadrature::QuadraturePoint<dim>;
  EXPECT_NE(nullptr, dynamic_cast<ExpectedType*>(quadrature_point_ptr.get()));
}

/* Call to MakeAngularQuadratureGeneratorPtr specifying no type should return
 * a runtime error. */
TYPED_TEST(QuadratureFactoriesIntegrationTest,
    MakeAngularQuadratureGenTestNoType) {
  constexpr int dim = this->dim;
  const int order_value = 4;

  EXPECT_ANY_THROW({
    quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
        quadrature::Order(order_value),
        quadrature::AngularQuadratureSetType::kNone);
  });
}

/* Call to MakeAngularQuadratureGeneratorPtr specifying a scalar quadrature
 * should return the correct type. */
TYPED_TEST(QuadratureFactoriesIntegrationTest,
           MakeAngularQuadratureGenTestScalar) {
  constexpr int dim = this->dim;
  const int order_value = 4;

  auto quadrature_generator_ptr =
      quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
          quadrature::Order(order_value),
          quadrature::AngularQuadratureSetType::kScalar);

  ASSERT_NE(nullptr, quadrature_generator_ptr);
  using ExpectedType = quadrature::angular::ScalarAngular<dim>;
  EXPECT_NE(nullptr,
      dynamic_cast<ExpectedType*>(quadrature_generator_ptr.get()));
  EXPECT_EQ(quadrature_generator_ptr->order(), 0);
}

/* Call to MakeAngularQuadratureGeneratorPtr specifying a level symmetric gaussian
 * should return the correct type. If dim !=3, should throw an error */
TYPED_TEST(QuadratureFactoriesIntegrationTest,
           MakeAngularQuadratureGenTestLSGaussian) {
  constexpr int dim = this->dim;
  const int order_value = 4;
  if (dim == 3) {
        auto quadrature_generator_ptr =
        quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
            quadrature::Order(order_value),
            quadrature::AngularQuadratureSetType::kLevelSymmetricGaussian);

    ASSERT_NE(nullptr, quadrature_generator_ptr);
    using ExpectedType = quadrature::angular::LevelSymmetricGaussian;
    EXPECT_NE(nullptr,
              dynamic_cast<ExpectedType*>(quadrature_generator_ptr.get()));
    EXPECT_EQ(quadrature_generator_ptr->order(), order_value);
  } else {
    EXPECT_ANY_THROW({
      quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(
          quadrature::Order(order_value),
          quadrature::AngularQuadratureSetType::kLevelSymmetricGaussian);
    });
  }
}

/* Call to MakeQuadratureSet specifying default implementation should return
 * the correct type. */
TYPED_TEST(QuadratureFactoriesIntegrationTest, MakeQuadratureSetTest) {
  constexpr int dim = this->dim;

  auto quadrature_set_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>(
      quadrature::QuadratureSetImpl::kDefault);

  ASSERT_NE(nullptr, quadrature_set_ptr);

  using ExpectedType = quadrature::QuadratureSet<dim>;

  ASSERT_NE(nullptr,
            dynamic_cast<ExpectedType*>(quadrature_set_ptr.get()));
}

TYPED_TEST(QuadratureFactoriesIntegrationTest, FillQuadratureSet) {
  const int dim = this->dim;
  const int n_points = 3;
  const int n_quadrants = std::pow(2, dim);

  // Generate random quadrature points
  std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight>>
      quadrature_points;

  for (int i = 0; i < n_points; ++i) {
    auto random_position = btest::RandomVector(dim, 1, 10);
    auto random_weight = btest::RandomDouble(0, 2);
    std::array<double, dim> position;
    for (int j = 0; j < dim; ++j)
      position.at(j) = random_position.at(j);
    quadrature_points.emplace_back(quadrature::CartesianPosition<dim>(position),
                                quadrature::Weight(random_weight));
  }

  // Distribute in all positive X quadrants
  auto distributed_points =
      quadrature::utility::GenerateAllPositiveX<dim>(quadrature_points);

  auto quadrature_set_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>();

  quadrature::factory::FillQuadratureSet<dim>(quadrature_set_ptr.get(),
                                              distributed_points);

  EXPECT_EQ(quadrature_set_ptr->size(), n_points*n_quadrants);

  for (const auto& quadrature_point_ptr : *quadrature_set_ptr) {

    // Verify this point is in the original set of points if it is all positive,
    // need to construct a pair to do this
    quadrature::CartesianPosition<dim> position(quadrature_point_ptr->ordinate()->cartesian_position());
    quadrature::Weight weight(quadrature_point_ptr->weight());

    if (std::all_of(position.get().cbegin(),
                    position.get().cend(), [](int i) { return i >=0;})) {
      auto point_pair = std::make_pair(position, weight);
      EXPECT_EQ(1, std::count(distributed_points.cbegin(), distributed_points.cend(),
                              point_pair));
    }

    // This point should have a reflection, whose reflection should be this point
    // and the reflection should have the opposite coordinate
    auto reflection_ptr = quadrature_set_ptr->GetReflection(quadrature_point_ptr);
    ASSERT_NE(nullptr, reflection_ptr);
    auto re_reflection_ptr = quadrature_set_ptr->GetReflection(reflection_ptr);
    EXPECT_EQ(re_reflection_ptr, quadrature_point_ptr);
    EXPECT_EQ(quadrature_point_ptr->weight(), reflection_ptr->weight());

    for (int i = 0; i < dim; ++i) {
      EXPECT_EQ(quadrature_point_ptr->ordinate()->cartesian_position().at(i),
                -reflection_ptr->ordinate()->cartesian_position().at(i));
    }
  }
}

TYPED_TEST(QuadratureFactoriesIntegrationTest, FillQuadratureSetScalar) {
  const int dim = this->dim;
  std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight >>
      quadrature_points;

  std::array<double, dim> zero_position;
  zero_position.fill(0);

  quadrature_points.emplace_back(quadrature::CartesianPosition<dim>(zero_position),
                                 quadrature::Weight(1.0));

  auto quadrature_set_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>();

  quadrature::factory::FillQuadratureSet<dim>(quadrature_set_ptr.get(),
                                              quadrature_points);

  ASSERT_EQ(quadrature_set_ptr->size(), 1);
  auto quadrature_point_ptr = *quadrature_set_ptr->begin();

  for (int i = 0; i < dim; ++i) {
    EXPECT_EQ(0, quadrature_point_ptr->ordinate()->cartesian_position().at(i));
  }

  EXPECT_EQ(quadrature_set_ptr->GetReflection(quadrature_point_ptr),
            quadrature_point_ptr);
}

/* If a point is already in a quadrature set, FillQuadratureSet should not make
 * a new one, but just set them as reflections.
 */
TYPED_TEST(QuadratureFactoriesIntegrationTest, FillQuadratureSetDuplicatePoint) {
  const int dim = this->dim;
  std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight >>
      quadrature_points;

  const auto random_vector = btest::RandomVector(dim, 1, 10);
  std::array<double, dim> random_position, negative_position;

  for (int i = 0; i < dim; ++i) {
    random_position.at(i) = random_vector.at(i);
    negative_position.at(i) = -random_vector.at(i);
  }

  quadrature_points.emplace_back(quadrature::CartesianPosition<dim>(random_position),
                                 quadrature::Weight(1.0));
  quadrature_points.emplace_back(quadrature::CartesianPosition<dim>(negative_position),
                                 quadrature::Weight(1.0));

  auto quadrature_set_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>();

  quadrature::factory::FillQuadratureSet<dim>(quadrature_set_ptr.get(),
                                              quadrature_points);

  ASSERT_EQ(quadrature_set_ptr->size(), 2);

  for (const auto& quadrature_point_ptr : *quadrature_set_ptr) {
    auto reflection_ptr =
        quadrature_set_ptr->GetReflection(quadrature_point_ptr);
    ASSERT_NE(nullptr, reflection_ptr);
    auto re_reflection_ptr =
        quadrature_set_ptr->GetReflection(reflection_ptr);
    ASSERT_NE(nullptr, re_reflection_ptr);
    EXPECT_EQ(re_reflection_ptr, quadrature_point_ptr);
  }
}

/* If a point and its reflection are already in a quadrature set,
 * FillQuadratureSet should do nothing.
 */
TYPED_TEST(QuadratureFactoriesIntegrationTest, FillQuadratureSetAlreadySetup) {
  const int dim = this->dim;
  std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight >>
      quadrature_points;

  const auto random_vector = btest::RandomVector(dim, 1, 10);
  std::array<double, dim> random_position, negative_position;

  for (int i = 0; i < dim; ++i) {
    random_position.at(i) = random_vector.at(i);
    negative_position.at(i) = -random_vector.at(i);
  }

  quadrature_points.emplace_back(quadrature::CartesianPosition<dim>(random_position),
                                 quadrature::Weight(1.0));
  quadrature_points.emplace_back(quadrature::CartesianPosition<dim>(negative_position),
                                 quadrature::Weight(1.0));

  auto quadrature_set_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>();

  quadrature::factory::FillQuadratureSet<dim>(quadrature_set_ptr.get(),
                                              quadrature_points);
  quadrature::factory::FillQuadratureSet<dim>(quadrature_set_ptr.get(),
                                              quadrature_points);

  ASSERT_EQ(quadrature_set_ptr->size(), 2);

  for (const auto& quadrature_point_ptr : *quadrature_set_ptr) {
    auto reflection_ptr =
        quadrature_set_ptr->GetReflection(quadrature_point_ptr);
    ASSERT_NE(nullptr, reflection_ptr);
    auto re_reflection_ptr =
        quadrature_set_ptr->GetReflection(reflection_ptr);
    ASSERT_NE(nullptr, re_reflection_ptr);
    EXPECT_EQ(re_reflection_ptr, quadrature_point_ptr);
  }
}

} // namespace<|endoftext|>