<commit_before>// This program is free software licenced under MIT Licence. You can
// find a copy of this licence in LICENCE.txt in the top directory of
// source code.
//

// Self
#include "Bot.h"

// Project
#include "utils.h"
#include "StringManipulation.h"
#include "Parser.h"
#include "Region.h"
#include "SuperRegion.h"
#include "QuickPickStrategy.h"
#include "GreedyRoundStrategy.h"

// C++
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <memory>

namespace warlightAi {

Bot::Bot()
    : m_pickStrategy(nullptr)
    , m_roundStrategy(nullptr)
{
}

void Bot::play()
{
    Parser(*this).parseInput();
}

void Bot::handleRequest(Request request)
{
    if (request == Request::CHECK_STARTING_REGIONS) {
        checkStartingRegions();
    } else if (request == Request::PICK_STARTING_REGION) {
        pick();
        m_pickableRegions.clear();
    } else if (request == Request::PLACE_ARMIES) {
        m_roundStrategy.reset(
            new GreedyRoundStrategy(m_world, m_availableArmies)
        );
        deploy();
    } else if (request == Request::ATTACK_TRANSFER) {
        attack();
    } else if (request == Request::CHECK_OPPONENT_STARTING_REGIONS) {
        checkOpponentStartingRegions();
    } else if (request == Request::CHECK_OPPONENT_MOVES) {
        checkOpponentMoves();
    }
}

void Bot::pick()
{
    std::cout << m_pickStrategy->pickNext(m_pickableRegions)->id() << std::endl;
}

void Bot::deploy()
{
    std::vector<std::string> deployments;
    for (auto &entry : m_roundStrategy->getDeployments()) {
        std::stringstream ss;
        ss << m_name << " place_armies " << entry.first->id() << " "
           << entry.second;

        deployments.emplace_back(ss.str());
    }

    std::cout << StringManipulation::comma_join(deployments) << std::endl;
}

void Bot::attack()
{
    std::vector<std::string> attacks;
    for (auto &attack : m_roundStrategy->getAttacks()) {
        std::stringstream ss;
        ss << m_name << " attack/transfer " << std::get<0>(attack)->id()
           << " " << std::get<1>(attack)->id() << " "
           << std::get<2>(attack);

        attacks.emplace_back(ss.str());
    }

    std::cout << StringManipulation::comma_join(attacks) << std::endl;
}

void Bot::checkStartingRegions()
{
    m_pickStrategy.reset(new QuickPickStrategy(m_startingRegions));
}

void Bot::checkOpponentStartingRegions()
{
    // Correctness guaranteed by commands order. Just because it's not needed
    // anymore.
    m_pickStrategy.reset();
    m_startingRegions.clear();
    m_pickableRegions.clear();

    // TODO
}

void Bot::checkOpponentMoves()
{
    // TODO
}

void Bot::addRegion(int newRegion, int superOfRegion)
{
    m_world.addRegion(newRegion, superOfRegion);
}

void Bot::addSuperRegion(int superRegion, int superRegionReward)
{
    m_world.addSuperRegion(superRegion, superRegionReward);
}

void Bot::addNeighbor(int region, int regionNeigh)
{
    m_world.addLink(region, regionNeigh);
}

void Bot::addWasteland(int targetRegion)
{
    m_world.addWasteland(targetRegion);
}

void Bot::addStartingRegion(int startingRegion)
{
    m_startingRegions.emplace_back(m_world.getRegionById(startingRegion));
}

void Bot::addPickableRegion(int pickableRegion)
{
    m_pickableRegions.emplace_back(m_world.getRegionById(pickableRegion));
}

void Bot::addOpponentAttack(int fromRegion, int toRegion, int armiesCount)
{
    m_opponentAttacks.emplace_back(
                        m_world.getRegionById(fromRegion),
                        m_world.getRegionById(toRegion),
                        armiesCount
    );
}

void Bot::addOpponentDeployment(int destRegion, int armiesCount)
{
    m_opponentDeployments.emplace_back(
                        m_world.getRegionById(destRegion),
                        armiesCount
    );
}

void Bot::addOpponentStartingRegion(int startingRegion)
{
    m_opponentStartingRegions.emplace_back(
                        m_world.getRegionById(startingRegion)
    );
}

void Bot::setName(const std::string &name)
{
    m_name = name;
}

void Bot::setOppName(const std::string &oppName)
{
    m_oppName = oppName;
}

void Bot::setAvailableArmies(int availableArmies)
{
    m_availableArmies = availableArmies;
}

void Bot::setTimebank(int timebank)
{
    m_timebank = timebank;
}

void Bot::setTimePerMove(int timePerMove)
{
    m_timePerMove = timePerMove;
}

void Bot::setMaxRounds(int maxRounds)
{
    m_maxRounds = maxRounds;
}

void Bot::startDelay(int delay)
{
    UNUSED(delay);
}

void Bot::updateRegion(int region, const std::string &playerName, int armiesCnt)
{
    Player p = playerName == m_name ?
                                Player::ME :
                                playerName == m_oppName ?
                                                    Player::OPPONENT :
                                                    Player::NEUTRAL;
    m_world.updateRegion(region, p, armiesCnt);
}

} // namespace warlightAi
<commit_msg>Fix bug which led our bot think that it has a region.<commit_after>// This program is free software licenced under MIT Licence. You can
// find a copy of this licence in LICENCE.txt in the top directory of
// source code.
//

// Self
#include "Bot.h"

// Project
#include "utils.h"
#include "StringManipulation.h"
#include "Parser.h"
#include "Region.h"
#include "SuperRegion.h"
#include "QuickPickStrategy.h"
#include "GreedyRoundStrategy.h"

// C++
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <memory>

namespace warlightAi {

Bot::Bot()
    : m_pickStrategy(nullptr)
    , m_roundStrategy(nullptr)
{
}

void Bot::play()
{
    Parser(*this).parseInput();
}

void Bot::handleRequest(Request request)
{
    if (request == Request::CHECK_STARTING_REGIONS) {
        checkStartingRegions();
    } else if (request == Request::PICK_STARTING_REGION) {
        pick();
        m_pickableRegions.clear();
    } else if (request == Request::PLACE_ARMIES) {
        m_roundStrategy.reset(
            new GreedyRoundStrategy(m_world, m_availableArmies)
        );
        deploy();
    } else if (request == Request::ATTACK_TRANSFER) {
        attack();
    } else if (request == Request::CHECK_OPPONENT_STARTING_REGIONS) {
        checkOpponentStartingRegions();
    } else if (request == Request::CHECK_OPPONENT_MOVES) {
        checkOpponentMoves();
    }
}

void Bot::pick()
{
    std::cout << m_pickStrategy->pickNext(m_pickableRegions)->id() << std::endl;
}

void Bot::deploy()
{
    std::vector<std::string> deployments;
    for (auto &entry : m_roundStrategy->getDeployments()) {
        std::stringstream ss;
        ss << m_name << " place_armies " << entry.first->id() << " "
           << entry.second;

        deployments.emplace_back(ss.str());
    }

    std::cout << StringManipulation::comma_join(deployments) << std::endl;
}

void Bot::attack()
{
    std::vector<std::string> attacks;
    for (auto &attack : m_roundStrategy->getAttacks()) {
        std::stringstream ss;
        ss << m_name << " attack/transfer " << std::get<0>(attack)->id()
           << " " << std::get<1>(attack)->id() << " "
           << std::get<2>(attack);

        attacks.emplace_back(ss.str());
    }

    std::cout << StringManipulation::comma_join(attacks) << std::endl;
}

void Bot::checkStartingRegions()
{
    m_pickStrategy.reset(new QuickPickStrategy(m_startingRegions));
}

void Bot::checkOpponentStartingRegions()
{
    // Correctness guaranteed by commands order. Just because it's not needed
    // anymore.
    m_pickStrategy.reset();
    m_startingRegions.clear();
    m_pickableRegions.clear();

    // TODO
}

void Bot::checkOpponentMoves()
{
    // TODO
}

void Bot::addRegion(int newRegion, int superOfRegion)
{
    m_world.addRegion(newRegion, superOfRegion);
}

void Bot::addSuperRegion(int superRegion, int superRegionReward)
{
    m_world.addSuperRegion(superRegion, superRegionReward);
}

void Bot::addNeighbor(int region, int regionNeigh)
{
    m_world.addLink(region, regionNeigh);
}

void Bot::addWasteland(int targetRegion)
{
    m_world.addWasteland(targetRegion);
}

void Bot::addStartingRegion(int startingRegion)
{
    m_startingRegions.emplace_back(m_world.getRegionById(startingRegion));
}

void Bot::addPickableRegion(int pickableRegion)
{
    m_pickableRegions.emplace_back(m_world.getRegionById(pickableRegion));
}

void Bot::addOpponentAttack(int fromRegion, int toRegion, int armiesCount)
{
    m_opponentAttacks.emplace_back(
                        m_world.getRegionById(fromRegion),
                        m_world.getRegionById(toRegion),
                        armiesCount
    );
}

void Bot::addOpponentDeployment(int destRegion, int armiesCount)
{
    m_opponentDeployments.emplace_back(
                        m_world.getRegionById(destRegion),
                        armiesCount
    );
}

void Bot::addOpponentStartingRegion(int startingRegion)
{
    m_opponentStartingRegions.emplace_back(
                        m_world.getRegionById(startingRegion)
    );
}

void Bot::setName(const std::string &name)
{
    m_name = name;
}

void Bot::setOppName(const std::string &oppName)
{
    m_oppName = oppName;
}

void Bot::setAvailableArmies(int availableArmies)
{
    m_availableArmies = availableArmies;

    // Safe to do this here as "settings starting_armies" is always given before
    // the "update_map" command which updates our visible map.
    for (auto &mine : m_world.getRegionsOwnedBy(Player::ME))
        mine->setOwner(Player::OPPONENT);
}

void Bot::setTimebank(int timebank)
{
    m_timebank = timebank;
}

void Bot::setTimePerMove(int timePerMove)
{
    m_timePerMove = timePerMove;
}

void Bot::setMaxRounds(int maxRounds)
{
    m_maxRounds = maxRounds;
}

void Bot::startDelay(int delay)
{
    UNUSED(delay);
}

void Bot::updateRegion(int region, const std::string &playerName, int armiesCnt)
{
    Player p = playerName == m_name ?
                                Player::ME :
                                playerName == m_oppName ?
                                                    Player::OPPONENT :
                                                    Player::NEUTRAL;
    m_world.updateRegion(region, p, armiesCnt);
}

} // namespace warlightAi
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <random>
#include <chrono>
#include <arc_utilities/eigen_helpers.hpp>
#include <arc_utilities/aligned_eigen_types.hpp>
#include <arc_utilities/pretty_print.hpp>

inline void TestVector3d(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    std::chrono::time_point<std::chrono::steady_clock> vector3_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Vector3d test_vector(1.0 * (double)idx, 2.0 * (double)idx, 3.0 * (double)idx);
        results.block<3, 1>(idx * 4, 0) = base_transform * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> vector3_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> vector3_test_time(vector3_end_time - vector3_start_time);
    std::cout << "Isometry3d * Vector3d test - " << vector3_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

inline void TestVector4d(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    std::chrono::time_point<std::chrono::steady_clock> vector4_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Vector4d test_vector(1.0 * (double)idx, 2.0 * (double)idx, 3.0 * (double)idx, 1.0);
        results.block<4, 1>(idx * 4, 0) = base_transform * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> vector4_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> vector4_test_time(vector4_end_time - vector4_start_time);
    std::cout << "Isometry3d * Vector4d test - " << vector4_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

inline void TestAlignedVector3d(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    std::chrono::time_point<std::chrono::steady_clock> alignedvector3_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Aligned4Vector3<double> test_vector(1.0 * (double)idx, 2.0 * (double)idx, 3.0 * (double)idx);
        results.block<3, 1>(idx * 4, 0) = base_transform * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> alignedvector3_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> alignedvector3_test_time(alignedvector3_end_time - alignedvector3_start_time);
    std::cout << "Isometry3d * AlignedVector3d test - " << alignedvector3_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

inline void TestManual(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    const Eigen::Matrix4d& base_transform_matrix = base_transform.matrix();
    std::chrono::time_point<std::chrono::steady_clock> manual_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Vector4d test_vector(1.0 * (double)idx, 2.0 * (double)idx, 3.0 * (double)idx, 1.0);
        results.block<4, 1>(idx * 4, 0) = base_transform_matrix * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> manual_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> manual_test_time(manual_end_time - manual_start_time);
    std::cout << "Matrix4d * Vector4d test - " << manual_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

int main(int argc, char** argv)
{
    printf("%d arguments\n", argc);
    for (int idx = 0; idx < argc; idx++)
    {
        printf("Argument %d: %s\n", idx, argv[idx]);
    }
    const ssize_t iterations = 100000000;
    const Eigen::Isometry3d base_transform = Eigen::Translation3d(10.0, 10.0, 10.0) * EigenHelpers::QuaternionFromRPY(0.25, 0.5, 0.75);
    Eigen::MatrixXd results = Eigen::MatrixXd::Ones(iterations * 4, 1);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    //
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    //
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    //
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    return 0;
}
<commit_msg>Updated cast style to C++<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <random>
#include <chrono>
#include <arc_utilities/eigen_helpers.hpp>
#include <arc_utilities/aligned_eigen_types.hpp>
#include <arc_utilities/pretty_print.hpp>

inline void TestVector3d(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    std::chrono::time_point<std::chrono::steady_clock> vector3_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Vector3d test_vector(1.0 * static_cast<double>(idx), 2.0 * static_cast<double>(idx), 3.0 * static_cast<double>(idx));
        results.block<3, 1>(idx * 4, 0) = base_transform * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> vector3_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> vector3_test_time(vector3_end_time - vector3_start_time);
    std::cout << "Isometry3d * Vector3d test - " << vector3_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

inline void TestVector4d(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    std::chrono::time_point<std::chrono::steady_clock> vector4_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Vector4d test_vector(1.0 * static_cast<double>(idx), 2.0 * static_cast<double>(idx), 3.0 * static_cast<double>(idx), 1.0);
        results.block<4, 1>(idx * 4, 0) = base_transform * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> vector4_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> vector4_test_time(vector4_end_time - vector4_start_time);
    std::cout << "Isometry3d * Vector4d test - " << vector4_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

inline void TestAlignedVector3d(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    std::chrono::time_point<std::chrono::steady_clock> alignedvector3_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Aligned4Vector3<double> test_vector(1.0 * static_cast<double>(idx), 2.0 * static_cast<double>(idx), 3.0 * static_cast<double>(idx));
        results.block<3, 1>(idx * 4, 0) = base_transform * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> alignedvector3_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> alignedvector3_test_time(alignedvector3_end_time - alignedvector3_start_time);
    std::cout << "Isometry3d * AlignedVector3d test - " << alignedvector3_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

inline void TestManual(const ssize_t iterations, const Eigen::Isometry3d& base_transform, Eigen::MatrixXd& results)
{
    const Eigen::Matrix4d& base_transform_matrix = base_transform.matrix();
    std::chrono::time_point<std::chrono::steady_clock> manual_start_time = std::chrono::steady_clock::now();
    for (ssize_t idx = 0; idx < iterations; idx++)
    {
        Eigen::Vector4d test_vector(1.0 * static_cast<double>(idx), 2.0 * static_cast<double>(idx), 3.0 * static_cast<double>(idx), 1.0);
        results.block<4, 1>(idx * 4, 0) = base_transform_matrix * test_vector;
    }
    std::chrono::time_point<std::chrono::steady_clock> manual_end_time = std::chrono::steady_clock::now();
    std::chrono::duration<double> manual_test_time(manual_end_time - manual_start_time);
    std::cout << "Matrix4d * Vector4d test - " << manual_test_time.count() << "s for " << iterations << " iterations to produce " << results.block<4, 1>(100000, 0) << std::endl;
}

int main(int argc, char** argv)
{
    printf("%d arguments\n", argc);
    for (int idx = 0; idx < argc; idx++)
    {
        printf("Argument %d: %s\n", idx, argv[idx]);
    }
    const ssize_t iterations = 100000000;
    const Eigen::Isometry3d base_transform = Eigen::Translation3d(10.0, 10.0, 10.0) * EigenHelpers::QuaternionFromRPY(0.25, 0.5, 0.75);
    Eigen::MatrixXd results = Eigen::MatrixXd::Ones(iterations * 4, 1);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    TestVector3d(iterations, base_transform, results);
    //
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    TestVector4d(iterations, base_transform, results);
    //
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    TestAlignedVector3d(iterations, base_transform, results);
    //
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    TestManual(iterations, base_transform, results);
    return 0;
}
<|endoftext|>


<commit_before>#ifndef CZAR_HH_
#define CZAR_HH_

//#define DEBUG
#ifdef DEBUG
#  define D(x) x
#else
#  define D(x)
#endif

#include <Arduino.h>

#include <arduino-lwm/sys/sysConfig.h>
#include <lwm/phy/phy.h>
#include <lwm/hal/hal.h>
#include <lwm/sys/sys.h>
#include <lwm/nwk/nwk.h>
#include <lwm/sys/sysTimer.h>
#include <lwm/phy/atmegarfr2.h>

class Czar {

  public:
    Czar();
    Czar();

    void setup();
    void loop();

  protected:
    // Name of the sketch (e.g. "Bootstrap")
    const char *sketchName;
};

#endif
<commit_msg>Commit from xCode<commit_after>#ifndef CZAR_HH_
#define CZAR_HH_

//#define DEBUG
#ifdef DEBUG
#  define D(x) x
#else
#  define D(x)
#endif

#include <Arduino.h>

#include <lwm/sys/sysConfig.h>
#include <lwm/phy/phy.h>
#include <lwm/hal/hal.h>
#include <lwm/sys/sys.h>
#include <lwm/nwk/nwk.h>
#include <lwm/sys/sysTimer.h>
#include <lwm/phy/atmegarfr2.h>

class Czar {

  public:
    Czar();
    Czar();

    void setup();
    void loop();

  protected:
    // Name of the sketch (e.g. "Bootstrap")
    const char *sketchName;
};

#endif
<|endoftext|>


<commit_before>
// NetworkInterfaceEnum.cpp

// Implements the cNetwork::EnumLocalIPAddresses() interface enumeration function

#include "Globals.h"
#include "Network.h"
#include "event2/util.h"
#ifdef _WIN32
	#include <IPHlpApi.h>
	#pragma comment(lib, "IPHLPAPI.lib")
#else  // _WIN32
#endif  // else _WIN32

#ifdef SELF_TEST

static class cEnumIPAddressTest
{
public:
	cEnumIPAddressTest(void)
	{
		printf("Enumerating all IP addresses...\n");
		auto IPs = cNetwork::EnumLocalIPAddresses();
		for (auto & ip: IPs)
		{
			printf("  %s\n", ip.c_str());
		}
		printf("done.\n");
	}
} g_EnumIPAddressTest;

#endif  // SELF_TEST

#ifdef _WIN32

/** Converts the SOCKET_ADDRESS structure received from the OS into an IP address string. */
static AString PrintAddress(SOCKET_ADDRESS & a_Addr)
{
	char IP[128];
	switch (a_Addr.lpSockaddr->sa_family)
	{
		case AF_INET:
		{
			auto sin = reinterpret_cast<const sockaddr_in *>(a_Addr.lpSockaddr);
			evutil_inet_ntop(a_Addr.lpSockaddr->sa_family, &(sin->sin_addr), IP, sizeof(IP));
			break;
		}
		case AF_INET6:
		{
			auto sin = reinterpret_cast<const sockaddr_in6 *>(a_Addr.lpSockaddr);
			evutil_inet_ntop(a_Addr.lpSockaddr->sa_family, &(sin->sin6_addr), IP, sizeof(IP));
			break;
		}
		default:
		{
			IP[0] = 0;
			break;
		}
	}
	return AString(IP);
}

#endif  // _WIN32

AStringVector cNetwork::EnumLocalIPAddresses(void)
{
	AStringVector res;

	#ifdef _WIN32

		// Query the OS for all adapters' addresses:
		char buffer[64 KiB];  // A buffer backing the address list
		PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(&buffer);
		ULONG outBufLen = sizeof(buffer);
		DWORD dwRetVal = GetAdaptersAddresses(
			AF_UNSPEC,
			GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, nullptr,
			pAddresses, &outBufLen
		);
		if (dwRetVal != ERROR_SUCCESS)
		{
			LOG("GetAdaptersAddresses() failed: %u", dwRetVal);
			return res;
		}

		// Enumerate all active adapters
		for (auto pCurrAddresses = pAddresses; pCurrAddresses != nullptr; pCurrAddresses = pCurrAddresses->Next)
		{
			if (pCurrAddresses->OperStatus != 1)
			{
				// Adapter not active, skip it:
				continue;
			}

			// Collect all IP addresses on this adapter:
			for (auto pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != nullptr; pUnicast = pUnicast->Next)
			{
				auto Address = PrintAddress(pUnicast->Address);
				if (!Address.empty())
				{
					res.push_back(Address);
				}
			}  // for pUnicast
		}  // for pCurrAddresses

	#else  // _WIN32

		// TODO: Enumerate network interfaces on Linux

	#endif  // else _WIN32

	return res;
}

<commit_msg>Network: Replaced magic number with named constant.<commit_after>
// NetworkInterfaceEnum.cpp

// Implements the cNetwork::EnumLocalIPAddresses() interface enumeration function

#include "Globals.h"
#include "Network.h"
#include "event2/util.h"
#ifdef _WIN32
	#include <IPHlpApi.h>
	#pragma comment(lib, "IPHLPAPI.lib")
#else  // _WIN32
#endif  // else _WIN32

#ifdef SELF_TEST

static class cEnumIPAddressTest
{
public:
	cEnumIPAddressTest(void)
	{
		printf("Enumerating all IP addresses...\n");
		auto IPs = cNetwork::EnumLocalIPAddresses();
		for (auto & ip: IPs)
		{
			printf("  %s\n", ip.c_str());
		}
		printf("done.\n");
	}
} g_EnumIPAddressTest;

#endif  // SELF_TEST

#ifdef _WIN32

/** Converts the SOCKET_ADDRESS structure received from the OS into an IP address string. */
static AString PrintAddress(SOCKET_ADDRESS & a_Addr)
{
	char IP[128];
	switch (a_Addr.lpSockaddr->sa_family)
	{
		case AF_INET:
		{
			auto sin = reinterpret_cast<const sockaddr_in *>(a_Addr.lpSockaddr);
			evutil_inet_ntop(a_Addr.lpSockaddr->sa_family, &(sin->sin_addr), IP, sizeof(IP));
			break;
		}
		case AF_INET6:
		{
			auto sin = reinterpret_cast<const sockaddr_in6 *>(a_Addr.lpSockaddr);
			evutil_inet_ntop(a_Addr.lpSockaddr->sa_family, &(sin->sin6_addr), IP, sizeof(IP));
			break;
		}
		default:
		{
			IP[0] = 0;
			break;
		}
	}
	return AString(IP);
}

#endif  // _WIN32

AStringVector cNetwork::EnumLocalIPAddresses(void)
{
	AStringVector res;

	#ifdef _WIN32

		// Query the OS for all adapters' addresses:
		char buffer[64 KiB];  // A buffer backing the address list
		PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(&buffer);
		ULONG outBufLen = sizeof(buffer);
		DWORD dwRetVal = GetAdaptersAddresses(
			AF_UNSPEC,
			GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, nullptr,
			pAddresses, &outBufLen
		);
		if (dwRetVal != ERROR_SUCCESS)
		{
			LOG("GetAdaptersAddresses() failed: %u", dwRetVal);
			return res;
		}

		// Enumerate all active adapters
		for (auto pCurrAddresses = pAddresses; pCurrAddresses != nullptr; pCurrAddresses = pCurrAddresses->Next)
		{
			if (pCurrAddresses->OperStatus != IfOperStatusUp)
			{
				// Adapter not active, skip it:
				continue;
			}

			// Collect all IP addresses on this adapter:
			for (auto pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != nullptr; pUnicast = pUnicast->Next)
			{
				auto Address = PrintAddress(pUnicast->Address);
				if (!Address.empty())
				{
					res.push_back(Address);
				}
			}  // for pUnicast
		}  // for pCurrAddresses

	#else  // _WIN32

		// TODO: Enumerate network interfaces on Linux

	#endif  // else _WIN32

	return res;
}

<|endoftext|>


<commit_before><commit_msg>Don't call atexit() functions from signal handler<commit_after><|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <iterator>
#include <miopen/config.h>
#include <miopen/kernel_warnings.hpp>
#include <miopen/stringutils.hpp>
#include <numeric>
#include <sstream>

namespace miopen {

std::vector<std::string> KernelWarnings()
{
    return {
        "-Weverything",
        "-Wno-shorten-64-to-32",
        "-Wno-unused-macros",
        "-Wno-unused-function",
        "-Wno-sign-compare",
        "-Wno-reserved-id-macro",
        "-Wno-sign-conversion",
        "-Wno-missing-prototypes",
        "-Wno-cast-qual",
        "-Wno-cast-align",
        "-Wno-conversion",
        "-Wno-double-promotion",
        "-Wno-float-equal",
    };
}

std::string MakeKernelWarningsString()
{
#if MIOPEN_BACKEND_OPENCL
    std::string prefix = " -Wf,";

#else
    std::string prefix = " ";
#endif
    return prefix + JoinStrings(KernelWarnings(), prefix);
}

const std::string& KernelWarningsString()
{
    static const std::string result = MakeKernelWarningsString();
    return result;
}

} // namespace miopen
<commit_msg>workaround-no-warn-pass-failed(01) Added "-Wno-pass-failed" to suppress "loop not unrolled" warnings. (#1744)<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <iterator>
#include <miopen/config.h>
#include <miopen/kernel_warnings.hpp>
#include <miopen/stringutils.hpp>
#include <numeric>
#include <sstream>

namespace miopen {

std::vector<std::string> KernelWarnings()
{
    return {
        "-Weverything",
        "-Wno-shorten-64-to-32",
        "-Wno-unused-macros",
        "-Wno-unused-function",
        "-Wno-sign-compare",
        "-Wno-reserved-id-macro",
        "-Wno-sign-conversion",
        "-Wno-missing-prototypes",
        "-Wno-cast-qual",
        "-Wno-cast-align",
        "-Wno-conversion",
        "-Wno-double-promotion",
        "-Wno-float-equal",
        "-Wno-pass-failed", // Disable "loop not unrolled" warnings. See #1735.
    };
}

std::string MakeKernelWarningsString()
{
#if MIOPEN_BACKEND_OPENCL
    std::string prefix = " -Wf,";

#else
    std::string prefix = " ";
#endif
    return prefix + JoinStrings(KernelWarnings(), prefix);
}

const std::string& KernelWarningsString()
{
    static const std::string result = MakeKernelWarningsString();
    return result;
}

} // namespace miopen
<|endoftext|>


<commit_before>/*
*
*  Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*/

#include "ReasoningPredicateMinimization.h"
#include "WaspFacade.h"
#include "outputBuilders/OutputBuilder.h"
#include "util/WaspErrorMessage.h"

#include <vector>
#include <iostream>
using namespace std;

void ReasoningPredicateMinimization::enumeration() {
    assert( wasp::Options::predMinimizationAlgorithm != NO_PREDMINIMIZATION );
    for(unsigned int j = 1; j <= waspFacade.numberOfVariables(); j++) {
        if(VariableNames::isHidden(j)) { continue; }
        const string& name = VariableNames::getName(j);
        for( unsigned int i = 0; i < wasp::Options::predicatesToMinimize.size(); i++ ) {
            if(Utils::startsWith(name, wasp::Options::predicatesToMinimize[i])) {
                waspFacade.freeze(j);
                candidates.insert(j);
                originalCandidates.push_back(j);
                lastOriginalVar = j;
                break;
            }
        }
    }

    if(wasp::Options::predMinimizationAlgorithm==PREDMIN_PREFERENCES)
        enumerationPreferences();
    else
        enumerationUnsatCores();

    if(numberOfModels == 0)
        waspFacade.printIncoherence();
}

void ReasoningPredicateMinimization::enumerationPreferences() {
    vector<Literal> preferences;
    for(unordered_set<Var>::iterator it = candidates.begin(); it != candidates.end(); ++it)
        preferences.push_back(Literal(*it, NEGATIVE));
    waspFacade.setPreferredChoices(preferences);
    while(true) {
        vector<Literal> assumptions;
        vector<Literal> conflict;
        unsigned int result = waspFacade.solve(assumptions, conflict);
        if(result == INCOHERENT)
            break;
        vector<Literal> all;
        vector<Literal> clause;
        for(unsigned int i = 0; i < originalCandidates.size(); i++)
            if(waspFacade.isTrue(originalCandidates[i])) {
                all.push_back(Literal(originalCandidates[i], POSITIVE));
                clause.push_back(Literal(originalCandidates[i], NEGATIVE));
            }
            else {
                all.push_back(Literal(originalCandidates[i], NEGATIVE));
            }

        enumerationBacktracking(all);
        waspFacade.addClause(clause);
    }
}

void ReasoningPredicateMinimization::enumerationUnsatCores() {
    while(true) {
        vector<Literal> assumptions;
        vector<Literal> conflict;

        for(unordered_set<Var>::iterator it = candidates.begin(); it != candidates.end(); ++it)
            assumptions.push_back(Literal(*it, NEGATIVE));
        unsigned int result = waspFacade.solve(assumptions, conflict);
        if(result == COHERENT) {
            vector<Literal> all;
            vector<Literal> clause;
            for(unsigned int i = 0; i < originalCandidates.size(); i++)
                if(waspFacade.isTrue(originalCandidates[i])) {
                    all.push_back(Literal(originalCandidates[i], POSITIVE));
                    clause.push_back(Literal(originalCandidates[i], NEGATIVE));
                }
                else {
                    all.push_back(Literal(originalCandidates[i], NEGATIVE));
                }
            for(unordered_set<Var>::iterator it = candidates.begin(); it != candidates.end(); ++it) {
                if(*it > lastOriginalVar) //Only for aux
                    all.push_back(Literal(*it, POSITIVE));
            }
            enumerationBacktracking(all);
            waspFacade.addClause(clause);
        }
        else {
            if(conflict.empty()) break;
            vector<Literal> constraint;
            Var previousVar = 0;
            for(unsigned int i = 0; i < conflict.size(); i++) {
                constraint.push_back(conflict[i]);
                candidates.erase(conflict[i].getVariable());
                if(i != 0) {
                    Var id = waspFacade.addVariable();
                    constraint.push_back(Literal(id, POSITIVE));
                    candidates.insert(id);
                    if(previousVar != 0)
                        waspFacade.addClause(Literal(previousVar,NEGATIVE), Literal(id, POSITIVE));
                    previousVar = id;
                }
            }
            waspFacade.addCardinalityConstraint(constraint, conflict.size()-1);
        }
    }
}

void ReasoningPredicateMinimization::enumerationBacktracking(const vector<Literal>& assums) {
    vector< bool > checked;
    vector<Literal> assumptions;
    for(unsigned int i = 0; i < assums.size(); i++) {
        if(waspFacade.isTrue(assums[i]) && waspFacade.decisionLevel(assums[i]) == 0) continue;
        assumptions.push_back(assums[i]);
        checked.push_back(true);
    }

    vector<Literal> conflict;
    unsigned int result = waspFacade.solve(assumptions, conflict);
    assert(result != INCOHERENT);

    if(!foundModel()) return;
    Solver& solver = const_cast<Solver&>(waspFacade.getSolver());
    solver.getChoicesWithoutAssumptions(assumptions);
    while(checked.size() < assumptions.size()) checked.push_back(false);

    flipLatestChoice(assumptions, checked);
    if(assumptions.empty()) return;
    solver.setComputeUnsatCores(true);
    begin:;
    solver.unrollToZero();
    solver.clearConflictStatus();
    result = solver.solve(assumptions);
    if(result == INCOHERENT) {
        const Clause* c = solver.getUnsatCore();
        if(c->size()==0) return;
        assert(!assumptions.empty());
        assert(!checked.empty());
        if(solver.getCurrentDecisionLevel()==0 || c->size()==1) {
            unsigned int k=0;
            assert(assumptions.size() == checked.size());
            for(unsigned int i=0; i < assumptions.size(); i++) {
                assumptions[k] = assumptions[i];
                checked[k] = checked[i];
                if(solver.getDecisionLevel(assumptions[i]) != 0) k++;
            }
            assert(assumptions.size() == checked.size());
            assumptions.resize(k);
            checked.resize(k);
        }
        else {
            if(wasp::Options::enumerationStrategy == ENUMERATION_BTO) {
                unordered_set<int> core;
                assert(c != NULL);
                for(unsigned int i = 0; i < c->size(); i++) core.insert(c->getAt(i).getId());
                unsigned int i = assumptions.size()-1;
                assert(core.find(assumptions[i].getId()) != core.end());
                while(i>0) {
                    if(core.find(assumptions[i-1].getId()) != core.end()) {
                        assumptions[i] = assumptions[i].getOppositeLiteral();
                        checked[i] = true;
                        break;
                    }
                    swap(assumptions[i], assumptions[i-1]);
                    swap(checked[i], checked[i-1]);
                    i--;
                }
            }
        }
    }
    else {
        if(!foundModel()) return;
        solver.getChoicesWithoutAssumptions(assumptions);
        while(checked.size() < assumptions.size()) checked.push_back(false);
    }

    flipLatestChoice(assumptions, checked);
    if(assumptions.empty()) return;
    goto begin;
}

void ReasoningPredicateMinimization::flipLatestChoice(vector<Literal>& choices, vector<bool>& checked) {
    unsigned int size;
    while(true) {
        size = choices.size();
        if(size == 0) return;
        if(checked[size-1]) { choices.pop_back(); checked.pop_back(); }
        else break;
    }

    choices[size-1]=choices[size-1].getOppositeLiteral();
    checked[size-1]=true;
}

bool ReasoningPredicateMinimization::foundModel() {
    waspFacade.printAnswerSet();
    trace_msg( enumeration, 1, "Model number: " << numberOfModels + 1 );
    if(++numberOfModels >= wasp::Options::maxModels) { trace_msg( enumeration, 1, "Enumerated " << wasp::Options::maxModels << "." ); return false; }
    return true;
}
<commit_msg>Fixed bug in enumeration with core.<commit_after>/*
*
*  Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*/

#include "ReasoningPredicateMinimization.h"
#include "WaspFacade.h"
#include "outputBuilders/OutputBuilder.h"
#include "util/WaspErrorMessage.h"

#include <vector>
#include <iostream>
using namespace std;

void ReasoningPredicateMinimization::enumeration() {
    assert( wasp::Options::predMinimizationAlgorithm != NO_PREDMINIMIZATION );
    for(unsigned int j = 1; j <= waspFacade.numberOfVariables(); j++) {
        if(VariableNames::isHidden(j)) { continue; }
        const string& name = VariableNames::getName(j);
        for( unsigned int i = 0; i < wasp::Options::predicatesToMinimize.size(); i++ ) {
            if(Utils::startsWith(name, wasp::Options::predicatesToMinimize[i])) {
                waspFacade.freeze(j);
                candidates.insert(j);
                originalCandidates.push_back(j);
                break;
            }
        }
    }

    if(wasp::Options::predMinimizationAlgorithm==PREDMIN_PREFERENCES)
        enumerationPreferences();
    else
        enumerationUnsatCores();

    if(numberOfModels == 0)
        waspFacade.printIncoherence();
}

void ReasoningPredicateMinimization::enumerationPreferences() {
    vector<Literal> preferences;
    for(unordered_set<Var>::iterator it = candidates.begin(); it != candidates.end(); ++it)
        preferences.push_back(Literal(*it, NEGATIVE));
    waspFacade.setPreferredChoices(preferences);
    while(true) {
        vector<Literal> assumptions;
        vector<Literal> conflict;
        unsigned int result = waspFacade.solve(assumptions, conflict);
        if(result == INCOHERENT)
            break;
        vector<Literal> all;
        vector<Literal> clause;
        for(unsigned int i = 0; i < originalCandidates.size(); i++)
            if(waspFacade.isTrue(originalCandidates[i])) {
                all.push_back(Literal(originalCandidates[i], POSITIVE));
                clause.push_back(Literal(originalCandidates[i], NEGATIVE));
            }
            else {
                all.push_back(Literal(originalCandidates[i], NEGATIVE));
            }

        enumerationBacktracking(all);
        waspFacade.addClause(clause);
    }
}

void ReasoningPredicateMinimization::enumerationUnsatCores() {
    lastOriginalVar = waspFacade.numberOfVariables();
    while(true) {
        vector<Literal> assumptions;
        vector<Literal> conflict;

        for(unordered_set<Var>::iterator it = candidates.begin(); it != candidates.end(); ++it)
            assumptions.push_back(Literal(*it, NEGATIVE));
        unsigned int result = waspFacade.solve(assumptions, conflict);
        if(result == COHERENT) {
            vector<Literal> all;
            vector<Literal> clause;
            for(unsigned int i = 0; i < originalCandidates.size(); i++)
                if(waspFacade.isTrue(originalCandidates[i])) {
                    all.push_back(Literal(originalCandidates[i], POSITIVE));
                    clause.push_back(Literal(originalCandidates[i], NEGATIVE));
                }
                else {
                    all.push_back(Literal(originalCandidates[i], NEGATIVE));
                }
            for(unsigned int var = lastOriginalVar+1; var <= waspFacade.numberOfVariables(); var++) {
                if(waspFacade.isTrue(var))
                    all.push_back(Literal(var, POSITIVE));
                else
                    all.push_back(Literal(var, NEGATIVE));
            }
            enumerationBacktracking(all);
            waspFacade.addClause(clause);
        }
        else {
            if(conflict.empty()) break;
            vector<Literal> constraint;
            Var previousVar = 0;
            for(unsigned int i = 0; i < conflict.size(); i++) {
                constraint.push_back(conflict[i]);
                candidates.erase(conflict[i].getVariable());
                if(i != 0) {
                    Var id = waspFacade.addVariable();
                    constraint.push_back(Literal(id, POSITIVE));
                    candidates.insert(id);
                    if(previousVar != 0)
                        waspFacade.addClause(Literal(previousVar,NEGATIVE), Literal(id, POSITIVE));
                    previousVar = id;
                }
            }
            waspFacade.addCardinalityConstraint(constraint, conflict.size()-1);
        }
    }
}

void ReasoningPredicateMinimization::enumerationBacktracking(const vector<Literal>& assums) {
    vector< bool > checked;
    vector<Literal> assumptions;
    for(unsigned int i = 0; i < assums.size(); i++) {
        if(waspFacade.isTrue(assums[i]) && waspFacade.decisionLevel(assums[i]) == 0) continue;
        assumptions.push_back(assums[i]);
        checked.push_back(true);
    }

    vector<Literal> conflict;
    unsigned int result = waspFacade.solve(assumptions, conflict);
    assert(result != INCOHERENT);

    if(!foundModel()) return;
    Solver& solver = const_cast<Solver&>(waspFacade.getSolver());
    solver.getChoicesWithoutAssumptions(assumptions);
    while(checked.size() < assumptions.size()) checked.push_back(false);

    flipLatestChoice(assumptions, checked);
    if(assumptions.empty()) return;
    solver.setComputeUnsatCores(true);
    begin:;
    solver.unrollToZero();
    solver.clearConflictStatus();
    result = solver.solve(assumptions);
    if(result == INCOHERENT) {
        const Clause* c = solver.getUnsatCore();
        if(c->size()==0) return;
        assert(!assumptions.empty());
        assert(!checked.empty());
        if(solver.getCurrentDecisionLevel()==0 || c->size()==1) {
            unsigned int k=0;
            assert(assumptions.size() == checked.size());
            for(unsigned int i=0; i < assumptions.size(); i++) {
                assumptions[k] = assumptions[i];
                checked[k] = checked[i];
                if(solver.getDecisionLevel(assumptions[i]) != 0) k++;
            }
            assert(assumptions.size() == checked.size());
            assumptions.resize(k);
            checked.resize(k);
        }
        else {
            if(wasp::Options::enumerationStrategy == ENUMERATION_BTO) {
                unordered_set<int> core;
                assert(c != NULL);
                for(unsigned int i = 0; i < c->size(); i++) core.insert(c->getAt(i).getId());
                unsigned int i = assumptions.size()-1;
                assert(core.find(assumptions[i].getId()) != core.end());
                while(i>0) {
                    if(core.find(assumptions[i-1].getId()) != core.end()) {
                        assumptions[i] = assumptions[i].getOppositeLiteral();
                        checked[i] = true;
                        break;
                    }
                    swap(assumptions[i], assumptions[i-1]);
                    swap(checked[i], checked[i-1]);
                    i--;
                }
            }
        }
    }
    else {
        if(!foundModel()) return;
        solver.getChoicesWithoutAssumptions(assumptions);
        while(checked.size() < assumptions.size()) checked.push_back(false);
    }

    flipLatestChoice(assumptions, checked);
    if(assumptions.empty()) return;
    goto begin;
}

void ReasoningPredicateMinimization::flipLatestChoice(vector<Literal>& choices, vector<bool>& checked) {
    unsigned int size;
    while(true) {
        size = choices.size();
        if(size == 0) return;
        if(checked[size-1]) { choices.pop_back(); checked.pop_back(); }
        else break;
    }

    choices[size-1]=choices[size-1].getOppositeLiteral();
    checked[size-1]=true;
}

bool ReasoningPredicateMinimization::foundModel() {
    waspFacade.printAnswerSet();
    trace_msg( enumeration, 1, "Model number: " << numberOfModels + 1 );
    if(++numberOfModels >= wasp::Options::maxModels) { trace_msg( enumeration, 1, "Enumerated " << wasp::Options::maxModels << "." ); return false; }
    return true;
}
<|endoftext|>


<commit_before>#include "Log.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <iostream>

Log m_globalLog;

Log* Log::instance()
{
	return &m_globalLog;
}

Log::Log()
: m_fd(-1)
{
}

Log::~Log()
{
	close(m_fd);
}

void Log::open(const std::string& path)
{
	m_fd = ::open(path.c_str(),S_IRUSR);
}

void Log::write(Type type, const char* text)
{
	std::cerr << "log " << text << std::endl;
	::write(m_fd,text,strlen(text));
}

<commit_msg>Add entry type information at the start of each log file entry.<commit_after>#include "Log.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <iostream>

Log m_globalLog;

Log* Log::instance()
{
	return &m_globalLog;
}

Log::Log()
: m_fd(-1)
{
}

Log::~Log()
{
	close(m_fd);
}

void Log::open(const std::string& path)
{
	m_fd = ::open(path.c_str(),S_IRUSR);
}

void Log::write(Type type, const char* text)
{
	switch (type)
	{
		case Info:
			std::cerr << "INFO  ";
			break;
		case Warn:
			std::cerr << "WARN  ";
			break;
		case Error:
			std::cerr << "ERROR ";
			break;
	}
	std::cerr << text << std::endl;

	if (m_fd >= 0)
	{
		::write(m_fd,text,strlen(text));
	}
}

<|endoftext|>


<commit_before>/***********************************************************************
 * This Source Code Form is subject to the terms of the Mozilla Public *
 * License, v. 2.0. If a copy of the MPL was not distributed with this *
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.            *
 ***********************************************************************/

#include <Map.hpp>

/*Map::Map : function to create with parametre the map for the game.
 * All the parametre must be different of undefined.
 * x : the lenght of the map.
 * y : the width of the map.
 * texture : array of texture wich contain all the texture needed to print the map.
 * egg_sprite : texture of the egg.
 * return the map created.
 */

Map::Map(const unsigned int x, const unsigned int y, std::vector< std::vector<Area> > smap, sf::Texture texture[NB_TEXTURE], sf::Texture* egg_texture) : x_size(x), y_size(y)
{
	srand(static_cast<unsigned int>(time(NULL)));
	for (unsigned int i = 0; i < x; i++){
		map.push_back(std::vector<Area>());
		for (unsigned int j = 0; j < y; j++){
			map[i].push_back(smap[i][j]);
		}
	}

	for (unsigned int i = 0; i < NB_TEXTURE; i++){
		sprites[i].setTexture(texture[i]);
	}
	egg_sprite.setTexture(*egg_texture);
}

/*printAll : procedure to print all the map.
 */
void Map::print (sf::RenderWindow& window){

	Coord tile;

	for (tile.x = 0; tile.x < x_size; ++tile.x){
		for (tile.y = 0; tile.y < y_size; ++tile.y){
			this->print(tile, window);
		}
	}
	egg_sprite.setPosition(static_cast<float>(coordinate_egg.x * RESOLUTION_X_IMAGE),static_cast<float>( coordinate_egg.y * RESOLUTION_Y_IMAGE));
	window.draw(egg_sprite);
}

/*print : print a tile of the map.
 * tile : coordinate of the tile we want to print.
 */

void Map::print (Coord tile, sf::RenderWindow& window){

	sprites[map[tile.x][tile.y]].setPosition(static_cast<float>(tile.x*RESOLUTION_X_IMAGE), static_cast<float>(tile.y*RESOLUTION_Y_IMAGE));
	window.draw(sprites[map[tile.x][tile.y]]);

}

void Map::init(){

	for (unsigned int i = x_size ; i-- ;){
		for (unsigned int j = y_size ; j-- ;){
			if (map[i][j] != OBSTACLE){
				free_tile.push_back(Coord(i, j));
				if (map[i][j] == WARP){
					warp.push_back(Coord(i, j));
				}
			}
		}
	}
}

void Map::popEgg (sf::RenderWindow& window){

	if (free_tile.size() != 0)
		coordinate_egg = free_tile[rand()%free_tile.size()];
	else{
		std::cout << "Bad map : full of obstacles" << std::endl;
		coordinate_egg = Coord(0,0);
	}
	egg_sprite.setPosition(static_cast<float>(coordinate_egg.x * RESOLUTION_X_IMAGE),static_cast<float>( coordinate_egg.y * RESOLUTION_Y_IMAGE));
	window.draw(egg_sprite);

}

bool Map::isWarp(Coord tile){

	for (unsigned int i = static_cast<unsigned int>(warp.size()); i-- ;)
		if (warp[i] == tile)
			return true;
	return false;
}

Coord Map::getWarp(Coord current_tile){
	std::vector<Coord> possible_warp;

	for (unsigned int i = static_cast<unsigned int>(warp.size()) ; i-- ;)
		if (warp[i] != current_tile)
			possible_warp.push_back(warp[i]);
	if (possible_warp.size() == 0) {
		std::cout << "Bad map : only one warp" << std::endl;
		return current_tile;
	}
	return possible_warp[rand()%possible_warp.size()];
}

Map& Map::operator=(const Map& mymap){
	x_size = mymap.x_size;
	y_size = mymap.y_size;
	for (unsigned int i = NB_TEXTURE ; i-- ;) {
		sprites[i] = mymap.sprites[i];
	}
	egg_sprite = mymap.egg_sprite;
	map = mymap.map;
	return *this;
}
<commit_msg>Modifying map's 'verbosity'<commit_after>/***********************************************************************
 * This Source Code Form is subject to the terms of the Mozilla Public *
 * License, v. 2.0. If a copy of the MPL was not distributed with this *
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.            *
 ***********************************************************************/

#include <Map.hpp>

/*Map::Map : function to create with parametre the map for the game.
 * All the parametre must be different of undefined.
 * x : the lenght of the map.
 * y : the width of the map.
 * texture : array of texture wich contain all the texture needed to print the map.
 * egg_sprite : texture of the egg.
 * return the map created.
 */

Map::Map(const unsigned int x, const unsigned int y, std::vector< std::vector<Area> > smap, sf::Texture texture[NB_TEXTURE], sf::Texture* egg_texture) : x_size(x), y_size(y)
{
	srand(static_cast<unsigned int>(time(NULL)));
	for (unsigned int i = 0; i < x; i++){
		map.push_back(std::vector<Area>());
		for (unsigned int j = 0; j < y; j++){
			map[i].push_back(smap[i][j]);
		}
	}

	for (unsigned int i = 0; i < NB_TEXTURE; i++){
		sprites[i].setTexture(texture[i]);
	}
	egg_sprite.setTexture(*egg_texture);
}

/*printAll : procedure to print all the map.
 */
void Map::print (sf::RenderWindow& window){

	Coord tile;

	for (tile.x = 0; tile.x < x_size; ++tile.x){
		for (tile.y = 0; tile.y < y_size; ++tile.y){
			this->print(tile, window);
		}
	}
	egg_sprite.setPosition(static_cast<float>(coordinate_egg.x * RESOLUTION_X_IMAGE),static_cast<float>( coordinate_egg.y * RESOLUTION_Y_IMAGE));
	window.draw(egg_sprite);
}

/*print : print a tile of the map.
 * tile : coordinate of the tile we want to print.
 */

void Map::print (Coord tile, sf::RenderWindow& window){

	sprites[map[tile.x][tile.y]].setPosition(static_cast<float>(tile.x*RESOLUTION_X_IMAGE), static_cast<float>(tile.y*RESOLUTION_Y_IMAGE));
	window.draw(sprites[map[tile.x][tile.y]]);

}

void Map::init(){

	for (unsigned int i = x_size ; i-- ;){
		for (unsigned int j = y_size ; j-- ;){
			if (map[i][j] != OBSTACLE){
				free_tile.push_back(Coord(i, j));
				if (map[i][j] == WARP){
					warp.push_back(Coord(i, j));
				}
			}
		}
	}
	if (free_tile.size() == 0)
		std::cout << "Bad map : Full of obstacles" << std::endl;
	if (warp.size() == 1)
		std::cout << "Bad map : you should have no warps or at least 2" << std::endl;
}

void Map::popEgg (sf::RenderWindow& window){

	if (free_tile.size() != 0)
		coordinate_egg = free_tile[rand()%free_tile.size()];
	else{
		coordinate_egg = Coord(0,0);
	}
	egg_sprite.setPosition(static_cast<float>(coordinate_egg.x * RESOLUTION_X_IMAGE),static_cast<float>( coordinate_egg.y * RESOLUTION_Y_IMAGE));
	window.draw(egg_sprite);

}

bool Map::isWarp(Coord tile){

	for (unsigned int i = static_cast<unsigned int>(warp.size()); i-- ;)
		if (warp[i] == tile)
			return true;
	return false;
}

Coord Map::getWarp(Coord current_tile){
	if (warp.size() <= 1) {
		return current_tile;
	}

	std::vector<Coord> possible_warp;
	for (unsigned int i = static_cast<unsigned int>(warp.size()) ; i-- ;)
		if (warp[i] != current_tile)
			possible_warp.push_back(warp[i]);
	return possible_warp[rand()%possible_warp.size()];
}

Map& Map::operator=(const Map& mymap){
	x_size = mymap.x_size;
	y_size = mymap.y_size;
	for (unsigned int i = NB_TEXTURE ; i-- ;) {
		sprites[i] = mymap.sprites[i];
	}
	egg_sprite = mymap.egg_sprite;
	map = mymap.map;
	return *this;
}
<|endoftext|>


<commit_before>/*! @file stats.cc
 *  @brief Statistical measures calculation.
 *  @author Markovtsev Vadim <v.markovtsev@samsung.com>
 *  @version 1.0
 *
 *  @section Notes
 *  This code partially conforms to Google C++ Style Guide.
 *
 *  @section Copyright
 *  Copyright 2013 Samsung R&D Institute Russia
 */

#include "src/transforms/stats.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <boost/regex.hpp>
#pragma GCC diagnostic pop
#include <math.h>
#ifdef __AVX__
#include <simd/avx_extra.h>
#elif defined(__ARM_NEON__)
#include <arm_neon.h>
#endif

namespace SoundFeatureExtraction {
namespace Transforms {

const std::unordered_map<std::string, StatsType> Stats::kStatsTypesMap {
  { "average", STATS_TYPE_AVERAGE },
  { "dispersion", STATS_TYPE_DISPERSION },
  { "skew", STATS_TYPE_SKEW},
  { "kurtosis", STATS_TYPE_KURTOSIS }
};

const std::unordered_map<int, Stats::CalculateFunc> Stats::kStatsFuncs {
  { STATS_TYPE_AVERAGE, Stats::CalculateAverage },
  { STATS_TYPE_DISPERSION, Stats::CalculateDispersion },
  { STATS_TYPE_SKEW, Stats::CalculateSkew },
  { STATS_TYPE_KURTOSIS, Stats::CalculateKurtosis }
};

Stats::Stats()
    : types_({ STATS_TYPE_AVERAGE, STATS_TYPE_DISPERSION,
               STATS_TYPE_SKEW, STATS_TYPE_KURTOSIS}),
      interval_(0) {
  RegisterSetter("types", [&](const std::string& value) {
    static const boost::regex allRegex("^\\s*(\\w+\\s*(\\s|$))+");
    boost::smatch match;
    if (!boost::regex_match(value, match, allRegex)) {
      return false;
    }
    static const boost::regex typesRegex("\\s*(\\w+)\\s*");
    static const boost::sregex_token_iterator empty;
    boost::sregex_token_iterator typesIterator(
          value.begin(), value.end(), typesRegex, 1);
    assert(typesIterator != empty);
    while (typesIterator != empty) {
      auto type_name = *typesIterator++;
      if (type_name == "all") {
        for (auto tmp : kStatsTypesMap) {
          types_.insert(tmp.second);
        }
      } else {
        auto mtypeit = kStatsTypesMap.find(type_name);
        if (mtypeit == kStatsTypesMap.end()) {
          return false;
        }
        types_.insert(mtypeit->second);
      }
    }
    return true;
  });
  RegisterSetter("interval", [&](const std::string& value) {
    int iv = Parse<int>("interval", value);
    if (iv < 2) {
      return false;
    }
    interval_ = iv;
    return true;
  });
}

size_t Stats::OnInputFormatChanged(size_t buffersCount) {
  if (interval_ != 0) {
    auto ratio = inputFormat_->Size() / interval_;
    if ((inputFormat_->Size() % interval_) == 0) {
      outputFormat_->SetSize(ratio);
      return buffersCount * ratio;
    }
    outputFormat_->SetSize(ratio + 1);
    return buffersCount * (ratio + 1);
  } else {
    outputFormat_->SetSize(1);
    return buffersCount;
  }
}

void Stats::Do(const float* in, StatsArray* out) const noexcept {
  float rawMoments[4];
  if (interval_ == 0) {
    CalculateRawMoments(true, in, 0, inputFormat_->Size(), rawMoments);
    Calculate(rawMoments, 0, out);
  } else {
    size_t i;
    for (i = 0; i < inputFormat_->Size() - interval_ + 1; i+= interval_) {
      CalculateRawMoments(true, in, i, interval_, rawMoments);
      Calculate(rawMoments, i / interval_, out);
    }
    if (inputFormat_->Size() % interval_ != 0) {
      CalculateRawMoments(true, in, i, inputFormat_->Size() - i, rawMoments);
      Calculate(rawMoments, i / interval_, out);
    }
  }
}

void Stats::Calculate(const float* rawMoments, int index,
                      StatsArray* out) const noexcept {
  for (auto stat : types_) {
    int sind = 0;
    int istat = stat;
    while (istat >>= 1) {
      sind++;
    }
    out[index][sind] = kStatsFuncs.find(stat)->second(rawMoments);
  }
}

void Stats::CalculateRawMoments(bool simd, const float* in, int startIndex,
                                int length, float* rawMoments) noexcept {
  float avg1 = 0, avg2 = 0, avg3 = 0, avg4 = 0;
  auto end_index = startIndex + length;
  if (simd) {
#ifdef __AVX__
    __m256 avg1vec = _mm256_set1_ps(0);
    __m256 avg2vec = _mm256_set1_ps(0);
    __m256 avg3vec = _mm256_set1_ps(0);
    __m256 avg4vec = _mm256_set1_ps(0);
    for (int i = startIndex; i < end_index - 7; i+=8) {
      __m256 val = _mm256_loadu_ps(in + i);
      avg1vec = _mm256_add_ps(avg1vec, val);
      __m256 val2 = _mm256_mul_ps(val, val);
      avg2vec = _mm256_add_ps(avg2vec, val2);
      val = _mm256_mul_ps(val2, val);
      avg3vec = _mm256_add_ps(avg3vec, val);
      val2 = _mm256_mul_ps(val2, val2);
      avg4vec = _mm256_add_ps(avg4vec, val2);
    }
    avg1vec = _mm256_hadd_ps(avg1vec, avg1vec);
    avg1vec = _mm256_hadd_ps(avg1vec, avg1vec);
    avg1 += ElementAt(avg1vec, 0);
    avg1 += ElementAt(avg1vec, 4);
    avg2vec = _mm256_hadd_ps(avg2vec, avg2vec);
    avg2vec = _mm256_hadd_ps(avg2vec, avg2vec);
    avg2 += ElementAt(avg2vec, 0);
    avg2 += ElementAt(avg2vec, 4);
    avg3vec = _mm256_hadd_ps(avg3vec, avg3vec);
    avg3vec = _mm256_hadd_ps(avg3vec, avg3vec);
    avg3 += ElementAt(avg3vec, 0);
    avg3 += ElementAt(avg3vec, 4);
    avg4vec = _mm256_hadd_ps(avg4vec, avg4vec);
    avg4vec = _mm256_hadd_ps(avg4vec, avg4vec);
    avg4 += ElementAt(avg4vec, 0);
    avg4 += ElementAt(avg4vec, 4);
    for (int i = ((end_index) & ~0x7); i < end_index; i++) {
      float v = in[i];
      avg1 += v;
      float v2 = v * v;
      avg2 += v2;
      v *= v2;
      avg3 += v;
      v2 *= v2;
      avg4 += v2;
    }
  } else {
#elif defined(__ARM_NEON__)
    float32x4_t avg1vec = vdupq_f32(0);
    float32x4_t avg2vec = vdupq_f32(0);
    float32x4_t avg3vec = vdupq_f32(0);
    float32x4_t avg4vec = vdupq_f32(0);
    for (int i = startIndex; i < end_index - 3; i+=4) {
      float32x4_t val = vld1q_f32(in + i);
      avg1vec = vaddq_f32(avg1vec, val);
      float32x4_t val2 = vmulq_f32(val, val);
      avg2vec = vaddq_f32(avg2vec, val2);
      val = vmulq_f32(val2, val);
      avg3vec = vaddq_f32(avg3vec, val);
      val2 = vmulq_f32(val2, val2);
      avg4vec = vaddq_f32(avg4vec, val2);
    }
    avg1 += vgetq_lane_f32(avg1vec, 0);
    avg1 += vgetq_lane_f32(avg1vec, 1);
    avg1 += vgetq_lane_f32(avg1vec, 2);
    avg1 += vgetq_lane_f32(avg1vec, 3);
    avg2 += vgetq_lane_f32(avg2vec, 0);
    avg2 += vgetq_lane_f32(avg2vec, 1);
    avg2 += vgetq_lane_f32(avg2vec, 2);
    avg2 += vgetq_lane_f32(avg2vec, 3);
    avg3 += vgetq_lane_f32(avg3vec, 0);
    avg3 += vgetq_lane_f32(avg3vec, 1);
    avg3 += vgetq_lane_f32(avg3vec, 2);
    avg3 += vgetq_lane_f32(avg3vec, 3);
    avg4 += vgetq_lane_f32(avg4vec, 0);
    avg4 += vgetq_lane_f32(avg4vec, 1);
    avg4 += vgetq_lane_f32(avg4vec, 2);
    avg4 += vgetq_lane_f32(avg4vec, 3);
    for (int i = ((end_index) & ~0x3); i < end_index; i++) {
      float v = in[i];
      avg1 += v;
      float v2 = v * v;
      avg2 += v2;
      v *= v2;
      avg3 += v;
      v2 *= v2;
      avg4 += v2;
    }
  } else {
#else
  } {
#endif
    for (int i = startIndex; i < end_index; i++) {
      float v = in[i];
      avg1 += v;
      float v2 = v * v;
      avg2 += v2;
      v *= v2;
      avg3 += v;
      v2 *= v2;
      avg4 += v2;
    }
  }
  avg1 /= length;
  avg2 /= length;
  avg3 /= length;
  avg4 /= length;
  rawMoments[0] = avg1;
  rawMoments[1] = avg2;
  rawMoments[2] = avg3;
  rawMoments[3] = avg4;
}

float Stats::CalculateAverage(const float* rawMoments) noexcept {
  return rawMoments[0];
}

float Stats::CalculateDispersion(const float* rawMoments) noexcept {
  return rawMoments[1] - rawMoments[0] * rawMoments[0];
}

float Stats::CalculateSkew(const float* rawMoments) noexcept {
  float avg1 = rawMoments[0];
  float avg2 = rawMoments[1];
  float avg3 = rawMoments[2];
  double u2 = avg2 - avg1 * avg1;
  if (u2 == 0) {
    return 0;
  }
  double u3 = avg3 - 3 * avg2 * avg1 + 2 * avg1 * avg1 * avg1;
  return u3 / (sqrt(u2) * u2);
}

float Stats::CalculateKurtosis(const float* rawMoments) noexcept {
  float avg1 = rawMoments[0];
  float avg2 = rawMoments[1];
  float avg3 = rawMoments[2];
  float avg4 = rawMoments[3];
  double u2 = avg2 - avg1 * avg1;
  if (u2 == 0) {
    return 1e10f;
  }
  double u4 = avg4 - 4 * avg3 * avg1 + 6 * avg2 * avg1 * avg1
      - 3 * avg1 * avg1 * avg1 * avg1;
  return u4 / (u2 * u2) - 3;
}

REGISTER_TRANSFORM(Stats);

}  // namespace Transforms
}  // namespace SoundFeatureExtraction
<commit_msg>Fixed ARM NEON miscompilation<commit_after>/*! @file stats.cc
 *  @brief Statistical measures calculation.
 *  @author Markovtsev Vadim <v.markovtsev@samsung.com>
 *  @version 1.0
 *
 *  @section Notes
 *  This code partially conforms to Google C++ Style Guide.
 *
 *  @section Copyright
 *  Copyright 2013 Samsung R&D Institute Russia
 */

#include "src/transforms/stats.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <boost/regex.hpp>
#pragma GCC diagnostic pop
#include <math.h>
#ifdef __AVX__
#include <simd/avx_extra.h>
#elif defined(__ARM_NEON__)
#include <arm_neon.h>
#endif

namespace SoundFeatureExtraction {
namespace Transforms {

const std::unordered_map<std::string, StatsType> Stats::kStatsTypesMap {
  { "average", STATS_TYPE_AVERAGE },
  { "dispersion", STATS_TYPE_DISPERSION },
  { "skew", STATS_TYPE_SKEW},
  { "kurtosis", STATS_TYPE_KURTOSIS }
};

const std::unordered_map<int, Stats::CalculateFunc> Stats::kStatsFuncs {
  { STATS_TYPE_AVERAGE, Stats::CalculateAverage },
  { STATS_TYPE_DISPERSION, Stats::CalculateDispersion },
  { STATS_TYPE_SKEW, Stats::CalculateSkew },
  { STATS_TYPE_KURTOSIS, Stats::CalculateKurtosis }
};

Stats::Stats()
    : types_({ STATS_TYPE_AVERAGE, STATS_TYPE_DISPERSION,
               STATS_TYPE_SKEW, STATS_TYPE_KURTOSIS}),
      interval_(0) {
  RegisterSetter("types", [&](const std::string& value) {
    static const boost::regex allRegex("^\\s*(\\w+\\s*(\\s|$))+");
    boost::smatch match;
    if (!boost::regex_match(value, match, allRegex)) {
      return false;
    }
    static const boost::regex typesRegex("\\s*(\\w+)\\s*");
    static const boost::sregex_token_iterator empty;
    boost::sregex_token_iterator typesIterator(
          value.begin(), value.end(), typesRegex, 1);
    assert(typesIterator != empty);
    while (typesIterator != empty) {
      auto type_name = *typesIterator++;
      if (type_name == "all") {
        for (auto tmp : kStatsTypesMap) {
          types_.insert(tmp.second);
        }
      } else {
        auto mtypeit = kStatsTypesMap.find(type_name);
        if (mtypeit == kStatsTypesMap.end()) {
          return false;
        }
        types_.insert(mtypeit->second);
      }
    }
    return true;
  });
  RegisterSetter("interval", [&](const std::string& value) {
    int iv = Parse<int>("interval", value);
    if (iv < 2) {
      return false;
    }
    interval_ = iv;
    return true;
  });
}

size_t Stats::OnInputFormatChanged(size_t buffersCount) {
  if (interval_ != 0) {
    auto ratio = inputFormat_->Size() / interval_;
    if ((inputFormat_->Size() % interval_) == 0) {
      outputFormat_->SetSize(ratio);
      return buffersCount * ratio;
    }
    outputFormat_->SetSize(ratio + 1);
    return buffersCount * (ratio + 1);
  } else {
    outputFormat_->SetSize(1);
    return buffersCount;
  }
}

void Stats::Do(const float* in, StatsArray* out) const noexcept {
  float rawMoments[4];
  if (interval_ == 0) {
    CalculateRawMoments(true, in, 0, inputFormat_->Size(), rawMoments);
    Calculate(rawMoments, 0, out);
  } else {
    size_t i;
    for (i = 0; i < inputFormat_->Size() - interval_ + 1; i+= interval_) {
      CalculateRawMoments(true, in, i, interval_, rawMoments);
      Calculate(rawMoments, i / interval_, out);
    }
    if (inputFormat_->Size() % interval_ != 0) {
      CalculateRawMoments(true, in, i, inputFormat_->Size() - i, rawMoments);
      Calculate(rawMoments, i / interval_, out);
    }
  }
}

void Stats::Calculate(const float* rawMoments, int index,
                      StatsArray* out) const noexcept {
  for (auto stat : types_) {
    int sind = 0;
    int istat = stat;
    while (istat >>= 1) {
      sind++;
    }
    out[index][sind] = kStatsFuncs.find(stat)->second(rawMoments);
  }
}

void Stats::CalculateRawMoments(bool simd, const float* in, int startIndex,
                                int length, float* rawMoments) noexcept {
  float avg1 = 0, avg2 = 0, avg3 = 0, avg4 = 0;
  auto end_index = startIndex + length;
  if (simd) {
#ifdef __AVX__
    __m256 avg1vec = _mm256_set1_ps(0);
    __m256 avg2vec = _mm256_set1_ps(0);
    __m256 avg3vec = _mm256_set1_ps(0);
    __m256 avg4vec = _mm256_set1_ps(0);
    for (int i = startIndex; i < end_index - 7; i+=8) {
      __m256 val = _mm256_loadu_ps(in + i);
      avg1vec = _mm256_add_ps(avg1vec, val);
      __m256 val2 = _mm256_mul_ps(val, val);
      avg2vec = _mm256_add_ps(avg2vec, val2);
      val = _mm256_mul_ps(val2, val);
      avg3vec = _mm256_add_ps(avg3vec, val);
      val2 = _mm256_mul_ps(val2, val2);
      avg4vec = _mm256_add_ps(avg4vec, val2);
    }
    avg1vec = _mm256_hadd_ps(avg1vec, avg1vec);
    avg1vec = _mm256_hadd_ps(avg1vec, avg1vec);
    avg1 += ElementAt(avg1vec, 0);
    avg1 += ElementAt(avg1vec, 4);
    avg2vec = _mm256_hadd_ps(avg2vec, avg2vec);
    avg2vec = _mm256_hadd_ps(avg2vec, avg2vec);
    avg2 += ElementAt(avg2vec, 0);
    avg2 += ElementAt(avg2vec, 4);
    avg3vec = _mm256_hadd_ps(avg3vec, avg3vec);
    avg3vec = _mm256_hadd_ps(avg3vec, avg3vec);
    avg3 += ElementAt(avg3vec, 0);
    avg3 += ElementAt(avg3vec, 4);
    avg4vec = _mm256_hadd_ps(avg4vec, avg4vec);
    avg4vec = _mm256_hadd_ps(avg4vec, avg4vec);
    avg4 += ElementAt(avg4vec, 0);
    avg4 += ElementAt(avg4vec, 4);
    for (int i = ((end_index) & ~0x7); i < end_index; i++) {
      float v = in[i];
      avg1 += v;
      float v2 = v * v;
      avg2 += v2;
      v *= v2;
      avg3 += v;
      v2 *= v2;
      avg4 += v2;
    }
  } else {
#elif defined(__ARM_NEON__)
    float32x4_t avg1vec = vdupq_n_f32(0);
    float32x4_t avg2vec = vdupq_n_f32(0);
    float32x4_t avg3vec = vdupq_n_f32(0);
    float32x4_t avg4vec = vdupq_n_f32(0);
    for (int i = startIndex; i < end_index - 3; i+=4) {
      float32x4_t val = vld1q_f32(in + i);
      avg1vec = vaddq_f32(avg1vec, val);
      float32x4_t val2 = vmulq_f32(val, val);
      avg2vec = vaddq_f32(avg2vec, val2);
      val = vmulq_f32(val2, val);
      avg3vec = vaddq_f32(avg3vec, val);
      val2 = vmulq_f32(val2, val2);
      avg4vec = vaddq_f32(avg4vec, val2);
    }
    avg1 += vgetq_lane_f32(avg1vec, 0);
    avg1 += vgetq_lane_f32(avg1vec, 1);
    avg1 += vgetq_lane_f32(avg1vec, 2);
    avg1 += vgetq_lane_f32(avg1vec, 3);
    avg2 += vgetq_lane_f32(avg2vec, 0);
    avg2 += vgetq_lane_f32(avg2vec, 1);
    avg2 += vgetq_lane_f32(avg2vec, 2);
    avg2 += vgetq_lane_f32(avg2vec, 3);
    avg3 += vgetq_lane_f32(avg3vec, 0);
    avg3 += vgetq_lane_f32(avg3vec, 1);
    avg3 += vgetq_lane_f32(avg3vec, 2);
    avg3 += vgetq_lane_f32(avg3vec, 3);
    avg4 += vgetq_lane_f32(avg4vec, 0);
    avg4 += vgetq_lane_f32(avg4vec, 1);
    avg4 += vgetq_lane_f32(avg4vec, 2);
    avg4 += vgetq_lane_f32(avg4vec, 3);
    for (int i = ((end_index) & ~0x3); i < end_index; i++) {
      float v = in[i];
      avg1 += v;
      float v2 = v * v;
      avg2 += v2;
      v *= v2;
      avg3 += v;
      v2 *= v2;
      avg4 += v2;
    }
  } else {
#else
  } {
#endif
    for (int i = startIndex; i < end_index; i++) {
      float v = in[i];
      avg1 += v;
      float v2 = v * v;
      avg2 += v2;
      v *= v2;
      avg3 += v;
      v2 *= v2;
      avg4 += v2;
    }
  }
  avg1 /= length;
  avg2 /= length;
  avg3 /= length;
  avg4 /= length;
  rawMoments[0] = avg1;
  rawMoments[1] = avg2;
  rawMoments[2] = avg3;
  rawMoments[3] = avg4;
}

float Stats::CalculateAverage(const float* rawMoments) noexcept {
  return rawMoments[0];
}

float Stats::CalculateDispersion(const float* rawMoments) noexcept {
  return rawMoments[1] - rawMoments[0] * rawMoments[0];
}

float Stats::CalculateSkew(const float* rawMoments) noexcept {
  float avg1 = rawMoments[0];
  float avg2 = rawMoments[1];
  float avg3 = rawMoments[2];
  double u2 = avg2 - avg1 * avg1;
  if (u2 == 0) {
    return 0;
  }
  double u3 = avg3 - 3 * avg2 * avg1 + 2 * avg1 * avg1 * avg1;
  return u3 / (sqrt(u2) * u2);
}

float Stats::CalculateKurtosis(const float* rawMoments) noexcept {
  float avg1 = rawMoments[0];
  float avg2 = rawMoments[1];
  float avg3 = rawMoments[2];
  float avg4 = rawMoments[3];
  double u2 = avg2 - avg1 * avg1;
  if (u2 == 0) {
    return 1e10f;
  }
  double u4 = avg4 - 4 * avg3 * avg1 + 6 * avg2 * avg1 * avg1
      - 3 * avg1 * avg1 * avg1 * avg1;
  return u4 / (u2 * u2) - 3;
}

REGISTER_TRANSFORM(Stats);

}  // namespace Transforms
}  // namespace SoundFeatureExtraction
<|endoftext|>


<commit_before>#include "MMU.hpp"

#include <algorithm>
#include <iterator>
#include <limits>
#include <vector>

namespace Core8 {

bool MMU::operator==(const MMU& mmu) const {
  return memory == mmu.memory;
}

Chip8::BYTE MMU::readByte(const std::size_t address) const {
  const auto byte = memory.at(address);

  return byte;
}

Chip8::WORD MMU::readWord(const std::size_t address) const {
  const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits;
  const auto lsb = memory.at(address + 1);

  return msb | lsb;
}

void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) {
  memory.at(address) = byte;
}

void MMU::load(std::istream& rom, const std::size_t address) {
  std::noskipws(rom);

  const std::vector<Chip8::BYTE> data{std::istream_iterator<Chip8::BYTE>(rom),
                                      std::istream_iterator<Chip8::BYTE>()};

  const auto availableMemory = memory.size() - address;
  const auto dataSize = data.size();
  const auto length = dataSize > availableMemory ? availableMemory : dataSize;

  std::copy_n(std::begin(data), length,
              std::next(std::begin(memory), address));
}

void MMU::clear() {
  memory.fill(0x0);
}

} // namespace Core8<commit_msg>Use std::min for load rom length<commit_after>#include "MMU.hpp"

#include <algorithm>
#include <iterator>
#include <limits>
#include <vector>

namespace Core8 {

bool MMU::operator==(const MMU& mmu) const {
  return memory == mmu.memory;
}

Chip8::BYTE MMU::readByte(const std::size_t address) const {
  const auto byte = memory.at(address);

  return byte;
}

Chip8::WORD MMU::readWord(const std::size_t address) const {
  const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits;
  const auto lsb = memory.at(address + 1);

  return msb | lsb;
}

void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) {
  memory.at(address) = byte;
}

void MMU::load(std::istream& rom, const std::size_t address) {
  std::noskipws(rom);

  const std::vector<Chip8::BYTE> data{std::istream_iterator<Chip8::BYTE>(rom),
                                      std::istream_iterator<Chip8::BYTE>()};

  const auto availableMemory = memory.size() - address;
  const auto dataSize = data.size();
  const auto length = std::min(availableMemory, dataSize);

  std::copy_n(std::begin(data), length,
              std::next(std::begin(memory), address));
}

void MMU::clear() {
  memory.fill(0x0);
}

} // namespace Core8<|endoftext|>


<commit_before>/***************************************************************************
                          DFA.cpp  -  Deterministic Finite Automata
                          -------------------
    begin                : Sun Jun 2 2002
    copyright            : (C) 2002 by Manuel Astudillo
    email                : d00mas@efd.lth.se
 ***************************************************************************/

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

 #include "DFA.h"

 DFA::DFA (const DFAStateTable *stateTable, const SymbolTable *symbolTable,
 const CharacterSetTable *characterSetTable, integer startState, bool caseSensitive) {
   this->startState = startState;
   this->stateTable = stateTable;
   this->symbolTable = symbolTable;
   this->characterSetTable = characterSetTable;
   this->caseSensitive = caseSensitive;

   errorTab = NULL;
 }

 DFA::~DFA () {
   for (integer j = 0; j < tokens.size(); j++) {
		delete tokens[j];
   }

   delete errorTab;
 }

 bool DFA::scan (char *text) {
	   wchar_t *wtext = new wchar_t [strlen(text)+1];
	   mbstowcs (wtext, text, strlen(text)+1);

	   bool res = scan (wtext);

	   delete [] wtext;

	   return res;
 }

 bool DFA::scan (wchar_t *text) {

   bool commentBlock = false;
   bool commentLine = false;
   integer currentLine = 1, currentCol = 1, tokenBeginCol = 1;

   Token *t = NULL;

   wstring tmpImage;
   wstring tokenSymbol, tokenImage;
   wchar_t currentChar;
   integer currentState = startState;
   int i=0//, imgIndex = 0; //Unused variable
   integer j;

   // Free the memory for every token that might be stored in this vector
   for (j = 0; j < tokens.size(); j++) {
		delete tokens[j];
   }

   tokens.clear();

   delete errorTab;
   errorTab = new ErrorTable();

   bool run = true;

   while (run) {
	 if (text[i] == 0) {
         // Check if Comment Block not ended
         if (commentBlock) {
		    // Set error and return
            errorTab->addError (ERROR_SCAN, END_COMMENT_NOT_FOUND,
                                NULL, currentLine, tokenBeginCol);
            currentState = startState;

            tmpImage = L"";
			return false;
         } else {
            run = false;
         }
	 }
     if (text[i] == L'\n') {
       currentLine++;
       currentCol = 1;
       if (commentLine) {
         commentLine = false;

         if (text[i] == 0) {
           break;
         }
       }
     }

     if (!caseSensitive) {
       currentChar = (wchar_t) towlower (text[i]);
     } else {
       currentChar = (wchar_t) text[i];
     }

     if (!commentLine) {

	   tmpImage.append (1,text[i]);

       // Check which is the next state
       integer e;
       bool changedState = false;
       for (e = 0; e < stateTable->states[currentState].edges.size(); e++) {

         integer index = stateTable->states[currentState].
         edges[e].characterSetIndex;
         // Check if the current character matchs one of the edge string
         wstring edgeString = characterSetTable->characters[index];
         integer s = 0;
         while (edgeString[s] != 0) {
           if (currentChar == edgeString[s]) {
             currentState = stateTable->states[currentState].edges[e].targetIndex;
             changedState = true;
             break;
           }
           s++;
         }
         if (changedState) break;

       }

       if (!changedState) {

		 // Check if it is an Accept state
         if (stateTable->states[currentState].accept) {
           i--;
		   currentCol--;
           // If the current character was a \n we have to decrement the line
           // counter
           if (text[i+1] == L'\n') {
             currentLine--;
           }

           // Check for type of symbol
           integer index2 = stateTable->states[currentState].acceptIndex;
           switch (symbolTable->symbols[index2].kind) {
             // Non terminal symbol
             case 0:
             // Cannot be
             break;

             // Terminal symbol
             case 1 :
             if (!commentBlock) {
              // tmpImage[imgIndex-1] = 0;
               tokenSymbol = symbolTable->symbols[index2].name;
               tokenImage = tmpImage;

             //  wcscpy (tokenSymbol, symbolTable->symbols[index2].name);
             //  wcscpy (tokenImage, tmpImage.c_str());

               t = new Token();
               t->symbol = tokenSymbol;
               t->image = tokenImage;
               t->symbolIndex = index2;
               t->kind = TERMINAL;

               t->line = currentLine;
               t->col = tokenBeginCol;

               tokens.push_back(t);
             }
			   tokenBeginCol = currentCol;
             break;

             // Whitespaces
             case 2:
             // Just dont do anything or generate error for token not accepted
				tokenBeginCol = currentCol;
             break;

             // End symbol
             case 3:
             wprintf (L"EOF SYMBOL");
             break;

             // Comment Start
             case 4:
             commentBlock = true;
             break;

             // Comment End
             case 5:
             commentBlock = false;
             break;

             case 6:
             commentLine = true;
             break;
           }
           currentState = startState;

		   tmpImage = L"";
		 } else {
           if (!commentBlock) {
             // Set error and return
             errorTab->addError (ERROR_SCAN, UNKNOWN_TOKEN, NULL, currentLine, tokenBeginCol);
             currentState = startState;

			 tmpImage = L"";
			 return false;
           }
           tokenBeginCol = currentCol;
         }
       }

     }
     i++;
     currentCol++;
   }

   // Generate EOF token
   t = new Token ();
   t->line = currentLine;
   t->col = currentCol;

   t->symbol = L"EOF";
   t->image = L"EOF";
   tokens.push_back(t);

   return true;
 }

 vector <Token*> &DFA::getTokens () {
    // preliminar stuff here
    return tokens;

 }

 ErrorTable *DFA::getErrors () {
   return errorTab;
 }

<commit_msg>Deleted unused variable imgIndex<commit_after>/***************************************************************************
                          DFA.cpp  -  Deterministic Finite Automata
                          -------------------
    begin                : Sun Jun 2 2002
    copyright            : (C) 2002 by Manuel Astudillo
    email                : d00mas@efd.lth.se
 ***************************************************************************/

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

 #include "DFA.h"

 DFA::DFA (const DFAStateTable *stateTable, const SymbolTable *symbolTable,
 const CharacterSetTable *characterSetTable, integer startState, bool caseSensitive) {
   this->startState = startState;
   this->stateTable = stateTable;
   this->symbolTable = symbolTable;
   this->characterSetTable = characterSetTable;
   this->caseSensitive = caseSensitive;

   errorTab = NULL;
 }

 DFA::~DFA () {
   for (integer j = 0; j < tokens.size(); j++) {
		delete tokens[j];
   }

   delete errorTab;
 }

 bool DFA::scan (char *text) {
	   wchar_t *wtext = new wchar_t [strlen(text)+1];
	   mbstowcs (wtext, text, strlen(text)+1);

	   bool res = scan (wtext);

	   delete [] wtext;

	   return res;
 }

 bool DFA::scan (wchar_t *text) {

   bool commentBlock = false;
   bool commentLine = false;
   integer currentLine = 1, currentCol = 1, tokenBeginCol = 1;

   Token *t = NULL;

   wstring tmpImage;
   wstring tokenSymbol, tokenImage;
   wchar_t currentChar;
   integer currentState = startState;
   int i=0;//, imgIndex = 0; //Unused variable
   integer j;

   // Free the memory for every token that might be stored in this vector
   for (j = 0; j < tokens.size(); j++) {
		delete tokens[j];
   }

   tokens.clear();

   delete errorTab;
   errorTab = new ErrorTable();

   bool run = true;

   while (run) {
	 if (text[i] == 0) {
         // Check if Comment Block not ended
         if (commentBlock) {
		    // Set error and return
            errorTab->addError (ERROR_SCAN, END_COMMENT_NOT_FOUND,
                                NULL, currentLine, tokenBeginCol);
            currentState = startState;

            tmpImage = L"";
			return false;
         } else {
            run = false;
         }
	 }
     if (text[i] == L'\n') {
       currentLine++;
       currentCol = 1;
       if (commentLine) {
         commentLine = false;

         if (text[i] == 0) {
           break;
         }
       }
     }

     if (!caseSensitive) {
       currentChar = (wchar_t) towlower (text[i]);
     } else {
       currentChar = (wchar_t) text[i];
     }

     if (!commentLine) {

	   tmpImage.append (1,text[i]);

       // Check which is the next state
       integer e;
       bool changedState = false;
       for (e = 0; e < stateTable->states[currentState].edges.size(); e++) {

         integer index = stateTable->states[currentState].
         edges[e].characterSetIndex;
         // Check if the current character matchs one of the edge string
         wstring edgeString = characterSetTable->characters[index];
         integer s = 0;
         while (edgeString[s] != 0) {
           if (currentChar == edgeString[s]) {
             currentState = stateTable->states[currentState].edges[e].targetIndex;
             changedState = true;
             break;
           }
           s++;
         }
         if (changedState) break;

       }

       if (!changedState) {

		 // Check if it is an Accept state
         if (stateTable->states[currentState].accept) {
           i--;
		   currentCol--;
           // If the current character was a \n we have to decrement the line
           // counter
           if (text[i+1] == L'\n') {
             currentLine--;
           }

           // Check for type of symbol
           integer index2 = stateTable->states[currentState].acceptIndex;
           switch (symbolTable->symbols[index2].kind) {
             // Non terminal symbol
             case 0:
             // Cannot be
             break;

             // Terminal symbol
             case 1 :
             if (!commentBlock) {
              // tmpImage[imgIndex-1] = 0;
               tokenSymbol = symbolTable->symbols[index2].name;
               tokenImage = tmpImage;

             //  wcscpy (tokenSymbol, symbolTable->symbols[index2].name);
             //  wcscpy (tokenImage, tmpImage.c_str());

               t = new Token();
               t->symbol = tokenSymbol;
               t->image = tokenImage;
               t->symbolIndex = index2;
               t->kind = TERMINAL;

               t->line = currentLine;
               t->col = tokenBeginCol;

               tokens.push_back(t);
             }
			   tokenBeginCol = currentCol;
             break;

             // Whitespaces
             case 2:
             // Just dont do anything or generate error for token not accepted
				tokenBeginCol = currentCol;
             break;

             // End symbol
             case 3:
             wprintf (L"EOF SYMBOL");
             break;

             // Comment Start
             case 4:
             commentBlock = true;
             break;

             // Comment End
             case 5:
             commentBlock = false;
             break;

             case 6:
             commentLine = true;
             break;
           }
           currentState = startState;

		   tmpImage = L"";
		 } else {
           if (!commentBlock) {
             // Set error and return
             errorTab->addError (ERROR_SCAN, UNKNOWN_TOKEN, NULL, currentLine, tokenBeginCol);
             currentState = startState;

			 tmpImage = L"";
			 return false;
           }
           tokenBeginCol = currentCol;
         }
       }

     }
     i++;
     currentCol++;
   }

   // Generate EOF token
   t = new Token ();
   t->line = currentLine;
   t->col = currentCol;

   t->symbol = L"EOF";
   t->image = L"EOF";
   tokens.push_back(t);

   return true;
 }

 vector <Token*> &DFA::getTokens () {
    // preliminar stuff here
    return tokens;

 }

 ErrorTable *DFA::getErrors () {
   return errorTab;
 }

<|endoftext|>