<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "bmp_heightmap_loader.hpp"
#include "bmp_loader.hpp"
#include "code/ylikuutio/geometry/spherical_terrain_struct.hpp"
#include "code/ylikuutio/triangulation/triangulate_quads_struct.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/common/pi.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstddef>  // std::size_t
#include <cstring>  // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory>   // std::make_shared, std::shared_ptr
#include <string>   // std::string
#include <vector>   // std::vector

namespace yli
{
    namespace load
    {
        bool load_BMP_terrain(
                const std::string& filename,
                std::vector<glm::vec3>& out_vertices,
                std::vector<glm::vec2>& out_UVs,
                std::vector<glm::vec3>& out_normals,
                std::size_t& image_width,
                std::size_t& image_height,
                const std::string& color_channel,
                const std::size_t x_step,
                const std::size_t z_step,
                const std::string& triangulation_type,
                const bool should_ylikuutio_use_real_texture_coordinates)
        {
            if (x_step < 1)
            {
                std::cerr << "ERROR: x_step is less than 1.\n";
                return false;
            }

            if (z_step < 1)
            {
                std::cerr << "ERROR: z_step is less than 1.\n";
                return false;
            }

            std::size_t image_size;

            std::shared_ptr<std::vector<uint8_t>> image_data = load_BMP_file(filename, image_width, image_height, image_size);

            if (image_width < 2 || image_height < 2)
            {
                return false;
            }

            // Define terrain size.
            const std::size_t terrain_size = image_width * image_height;

            const std::size_t line_size_in_bytes = image_size / image_height;

            std::vector<float> vertex_data;
            vertex_data.reserve(terrain_size);

            float* vertex_pointer = &vertex_data[0];

            const char* char_color_channel = color_channel.c_str();

            // start processing image_data.
            for (std::size_t z = 0; z < image_height; z++)
            {
                const uint8_t* image_pointer = &(*image_data)[0] + z * line_size_in_bytes;

                for (std::size_t x = 0; x < image_width; x++)
                {
                    std::size_t y;

                    if (std::strcmp(char_color_channel, "blue") == 0)
                    {
                        y = static_cast<float>(*image_pointer);       // y-coordinate is the blue (B) value.
                    }
                    else if (std::strcmp(char_color_channel, "green") == 0)
                    {
                        y = static_cast<float>(*(image_pointer + 1)); // y-coordinate is the green (G) value.
                    }
                    else if (std::strcmp(char_color_channel, "red") == 0)
                    {
                        y = static_cast<float>(*(image_pointer + 2)); // y-coordinate is the red (R) value.
                    }

                    // y-coordinate is the mean of R, G, & B.
                    else if ((std::strcmp(char_color_channel, "mean") == 0) || (std::strcmp(char_color_channel, "all") == 0))
                    {
                        y = (static_cast<float>(*image_pointer) + static_cast<float>(*(image_pointer + 1)) + static_cast<float>(*(image_pointer + 2))) / 3.0f;
                    }
                    else
                    {
                        std::cerr << "ERROR: invalid color channel.\n";
                        return false;
                    }

                    *vertex_pointer++ = y;
                    image_pointer += 3; // R, G, & B.
                }
            }

            std::cout << "color channel in use: " << color_channel << "\n";

            yli::triangulation::TriangulateQuadsStruct triangulate_quads_struct;
            triangulate_quads_struct.image_width = image_width;
            triangulate_quads_struct.image_height = image_height;
            triangulate_quads_struct.x_step = x_step;
            triangulate_quads_struct.z_step = z_step;
            triangulate_quads_struct.triangulation_type = triangulation_type;
            triangulate_quads_struct.should_ylikuutio_use_real_texture_coordinates = should_ylikuutio_use_real_texture_coordinates;

            return yli::triangulation::triangulate_quads(&vertex_data[0], triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        }
    }
}
<commit_msg>`yli::load::load_BMP_terrain`: cleaning up code.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "bmp_heightmap_loader.hpp"
#include "bmp_loader.hpp"
#include "code/ylikuutio/geometry/spherical_terrain_struct.hpp"
#include "code/ylikuutio/triangulation/triangulate_quads_struct.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/common/pi.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstddef>  // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory>   // std::make_shared, std::shared_ptr
#include <string>   // std::string
#include <vector>   // std::vector

namespace yli
{
    namespace load
    {
        bool load_BMP_terrain(
                const std::string& filename,
                std::vector<glm::vec3>& out_vertices,
                std::vector<glm::vec2>& out_UVs,
                std::vector<glm::vec3>& out_normals,
                std::size_t& image_width,
                std::size_t& image_height,
                const std::string& color_channel,
                const std::size_t x_step,
                const std::size_t z_step,
                const std::string& triangulation_type,
                const bool should_ylikuutio_use_real_texture_coordinates)
        {
            if (x_step < 1)
            {
                std::cerr << "ERROR: x_step is less than 1.\n";
                return false;
            }

            if (z_step < 1)
            {
                std::cerr << "ERROR: z_step is less than 1.\n";
                return false;
            }

            std::size_t image_size;

            std::shared_ptr<std::vector<uint8_t>> image_data = load_BMP_file(filename, image_width, image_height, image_size);

            if (image_width < 2 || image_height < 2)
            {
                return false;
            }

            // Define terrain size.
            const std::size_t terrain_size = image_width * image_height;

            const std::size_t line_size_in_bytes = image_size / image_height;

            std::vector<float> vertex_data;
            vertex_data.reserve(terrain_size);

            float* vertex_pointer = &vertex_data[0];

            // start processing image_data.
            for (std::size_t z = 0; z < image_height; z++)
            {
                const uint8_t* image_pointer = &(*image_data)[0] + z * line_size_in_bytes;

                for (std::size_t x = 0; x < image_width; x++)
                {
                    std::size_t y;

                    if (color_channel == "blue")
                    {
                        y = static_cast<float>(*image_pointer);       // y-coordinate is the blue (B) value.
                    }
                    else if (color_channel == "green")
                    {
                        y = static_cast<float>(*(image_pointer + 1)); // y-coordinate is the green (G) value.
                    }
                    else if (color_channel == "red")
                    {
                        y = static_cast<float>(*(image_pointer + 2)); // y-coordinate is the red (R) value.
                    }

                    // y-coordinate is the mean of R, G, & B.
                    else if (color_channel == "mean" || color_channel == "all")
                    {
                        y = (static_cast<float>(*image_pointer) + static_cast<float>(*(image_pointer + 1)) + static_cast<float>(*(image_pointer + 2))) / 3.0f;
                    }
                    else
                    {
                        std::cerr << "ERROR: invalid color channel.\n";
                        return false;
                    }

                    *vertex_pointer++ = y;
                    image_pointer += 3; // R, G, & B.
                }
            }

            std::cout << "color channel in use: " << color_channel << "\n";

            yli::triangulation::TriangulateQuadsStruct triangulate_quads_struct;
            triangulate_quads_struct.image_width = image_width;
            triangulate_quads_struct.image_height = image_height;
            triangulate_quads_struct.x_step = x_step;
            triangulate_quads_struct.z_step = z_step;
            triangulate_quads_struct.triangulation_type = triangulation_type;
            triangulate_quads_struct.should_ylikuutio_use_real_texture_coordinates = should_ylikuutio_use_real_texture_coordinates;

            return yli::triangulation::triangulate_quads(&vertex_data[0], triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        }
    }
}
<|endoftext|>


<commit_before>#pragma once

#include <WinSock2.h>
#include <thread>
#include <future>
#include <iostream>

namespace common {

class Copyable {
protected:
  Copyable() noexcept = default;
  ~Copyable() noexcept = default;
  Copyable(const Copyable&) noexcept = default;
  Copyable(Copyable&&) noexcept = default;
  Copyable& operator=(const Copyable&) noexcept = default;
  Copyable& operator=(Copyable&&) noexcept = default;
};

class UnCopyable {
  UnCopyable(const UnCopyable&) noexcept = delete;
  UnCopyable(UnCopyable&&) noexcept = delete;
  UnCopyable& operator=(const UnCopyable&) noexcept = delete;
  UnCopyable& operator=(UnCopyable&&) noexcept = delete;
protected:
  UnCopyable() noexcept = default;
  ~UnCopyable() noexcept = default;
};

template <typename T> class Singleton : private UnCopyable {
public:
  static T& get_instance() noexcept {
    static T _ins;
    return _ins;
  }
};

class WSGuarder final : private UnCopyable {
public:
  WSGuarder() noexcept;
  ~WSGuarder() noexcept;
};

class UniqueSocket final : private UnCopyable {
  SOCKET sockfd_{};
public:
  UniqueSocket(SOCKET fd) noexcept : sockfd_(fd) {}
  ~UniqueSocket() noexcept;

  inline operator SOCKET() const { return sockfd_; }
  inline operator bool() const { return sockfd_ != INVALID_SOCKET; }
};

template <typename Fn, typename... Args>
inline auto async(Fn&& fn, Args&&... args) {
  return std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Args>(args)...);
}

}<commit_msg>:construction: chore(thread-pool): add an easy thread-pool<commit_after>#pragma once

#include <WinSock2.h>
#include <deque>
#include <functional>
#include <memory>
#include <thread>
#include <future>
#include <condition_variable>
#include <iostream>

namespace common {

class Copyable {
protected:
  Copyable() noexcept = default;
  ~Copyable() noexcept = default;
  Copyable(const Copyable&) noexcept = default;
  Copyable(Copyable&&) noexcept = default;
  Copyable& operator=(const Copyable&) noexcept = default;
  Copyable& operator=(Copyable&&) noexcept = default;
};

class UnCopyable {
  UnCopyable(const UnCopyable&) noexcept = delete;
  UnCopyable(UnCopyable&&) noexcept = delete;
  UnCopyable& operator=(const UnCopyable&) noexcept = delete;
  UnCopyable& operator=(UnCopyable&&) noexcept = delete;
protected:
  UnCopyable() noexcept = default;
  ~UnCopyable() noexcept = default;
};

template <typename T> class Singleton : private UnCopyable {
public:
  static T& get_instance() noexcept {
    static T _ins;
    return _ins;
  }
};

class WSGuarder final : private UnCopyable {
public:
  WSGuarder() noexcept;
  ~WSGuarder() noexcept;
};

class UniqueSocket final : private UnCopyable {
  SOCKET sockfd_{};
public:
  UniqueSocket(SOCKET fd) noexcept : sockfd_(fd) {}
  ~UniqueSocket() noexcept;

  inline operator SOCKET() const { return sockfd_; }
  inline operator bool() const { return sockfd_ != INVALID_SOCKET; }
};

template <typename Fn, typename... Args>
inline auto async(Fn&& fn, Args&&... args) {
  return std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Args>(args)...);
}

class ThreadPool final : private UnCopyable {
  using TaskEntity = std::function<void ()>;
  using ThreadEntity = std::unique_ptr<std::thread>;

  bool running_{true};
  mutable std::mutex mtx_;
  std::condition_variable non_empty_;
  std::vector<ThreadEntity> threads_;
  std::deque<TaskEntity> tasks_;

  TaskEntity fetch_task() {
    std::unique_lock<std::mutex> guard(mtx_);
    while (tasks_.empty() && running_)
      non_empty_.wait(guard);

    TaskEntity t;
    if (!tasks_.empty()) {
      t = tasks_.front();
      tasks_.pop_front();
    }
    return t;
  }
public:
  ThreadPool(int thread_num = 4) noexcept {
    threads_.reserve(thread_num);
    for (int i = 0; i < thread_num; ++i)
      threads_.emplace_back(new std::thread([this] {
          while (running_) {
            auto t = fetch_task();
            if (t)
              t();
          }
        }));
  }

  ~ThreadPool() noexcept {
    if (running_) {
      {
        std::unique_lock<std::mutex> guard(mtx_);
        running_ = false;
        non_empty_.notify_all();
      }

      for (auto& t : threads_)
        t->join();
    }
  }

  template <typename Fn, typename... Args>
  void run_task(Fn&& fn, Args&&... args) {
    if (threads_.empty()) {
      fn(std::forward<Args>(args)...);
    }
    else {
      using ReturnType = typename std::result_of<Fn (Args&&...)>::type;
      auto task = std::make_shared<std::packaged_task<ReturnType ()>>(
        std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...));

      {
        std::unique_lock<std::mutex> guard(mtx_);
        tasks_.emplace_back([task] { (*task)(); });
      }
      non_empty_.notify_one();
    }
  }
};

}<|endoftext|>


<commit_before>#include "schedulers/wojtek_throttle_scheduler.h"

#include <chrono>
#include <cstdio>
#include <cmath>

#include "gflags/gflags.h"
#include "utils/stopwatch.h"

DEFINE_bool(log_schedule, true, "");

namespace {
  template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
  }
}

namespace schedulers {

using game::CarState;

const vector<int> WojtekThrottleScheduler::DEFAULT_GROUPS {1,1,4,2,2,4,1,8,8,4,4,2};
const vector<int> WojtekThrottleScheduler::QUICK_GROUPS {1,1,2,2,2,4};

const vector<double> WojtekThrottleScheduler::values{0.0, 1.0}; // Values must be increasing

WojtekThrottleScheduler::WojtekThrottleScheduler(const game::Race& race,
    game::CarTracker& car_tracker, int time_limit, const vector<int>& groups)
  : race_(race), car_tracker_(car_tracker),
    groups_(groups),
    horizon_(std::accumulate(groups.begin(), groups.end(), 0)),
    best_schedule_(&car_tracker, horizon_),
    branch_and_bound_(&car_tracker, horizon_, groups_, values), log_file_("wojtek_data_log.csv", std::ofstream::out), time_limit_(time_limit)
{
   //Watchout: executing two WojtekThrottleSchedulers in pararell could be risky becase of log file (TODO)
   log_file_ << "tick," << "x," << "turbo," << "switch," << "a," << "v," << "dir," << "rad," << "piece_no," << "start_lane," << "end_land," << "schedule_time," << "initial_schedule_safe," << "nodes_visited," << "leafs_visited," << "unsafe_cuts," << "ub_cuts," << "solution_improvements," << "schedule," << "predicted_angles," << "0_throttle_predictions" << std::endl;
}

WojtekThrottleScheduler::~WojtekThrottleScheduler() {
    log_file_.close();
}

void WojtekThrottleScheduler::Schedule(const game::CarState& state, int game_tick) {
  utils::StopWatch stopwatch;

  // We want to use the last best_schedule_ if possible. Generally always
  // tick_diff should always be 1, but I take extra care if
  // (for some unknown reason) this is not the case
  int tick_diff = game_tick - last_game_tick_;
  if (1 <= tick_diff && tick_diff <= 4) {
    for (int i = 0; i < tick_diff; ++i)
      best_schedule_.ShiftLeftFillSafe(state);
  } else {
    // We will still try to use the old schedule, but, it could be not safe.
    // This will be checked subsequently
  }
  // Must do it, because we could have unpredicted turbo/switches, etc. ahead
  best_schedule_.UpdateDistance(state);

  // Initial schedule should be safe normally. Not safe only if future predictions
  // have changed
  initial_schedule_safe_ = best_schedule_.IsSafe(state);
  if (!initial_schedule_safe_) {
    best_schedule_.Reset(state);
  }

  branch_and_bound_.Improve(state, best_schedule_);
  local_improver_.Improve(state, best_schedule_, 0.1);

  // Once again, just to be 200% sure check for safety
  if (!best_schedule_.IsSafe(state)) {
    // This should never happen
    std::cerr << "Schedule is not safe. This should not happen" << std::endl;
    best_schedule_.Reset(state);
  }

  last_game_tick_ = game_tick;
  last_schedule_time_ = stopwatch.elapsed();
  Log(state);
}

void WojtekThrottleScheduler::PrintSchedule(const game::CarState& state, const Sched& schedule, int len) {
  for (int i=0; i<len; ++i)
    printf("%.2f ", schedule[i]);
  printf("\n");

  CarState next = state;
  for (int i=0; i<len; ++i) {
    next = car_tracker_.Predict(next, game::Command(schedule[i]));
    printf("%.1f ", next.position().angle());
  }
  printf("\n");
}

void WojtekThrottleScheduler::Log(const game::CarState& state) {
  if (FLAGS_log_schedule) {
    PrintSchedule(state, best_schedule_, std::min(horizon_, 20));
  }

  game::Piece piece = race_.track().pieces()[state.position().piece()];
  log_file_ << last_game_tick_
            << ',' << throttle()
            << ',' << state.turbo_state().is_on()
            << ',' << (int)state.switch_state()
            << ',' << state.position().angle()
            << ',' << state.velocity()
            << ',' << -sgn(piece.angle())
            << ',' << piece.radius()
            << ',' << state.position().piece()
            << ',' << state.position().start_lane()
            << ',' << state.position().end_lane()
            << ',' << last_schedule_time_
            << ',' << initial_schedule_safe_
            << ',' << branch_and_bound_.stats().nodes_visited
            << ',' << branch_and_bound_.stats().leafs_visited
            << ',' << branch_and_bound_.stats().unsafe_cuts
            << ',' << branch_and_bound_.stats().ub_cuts
            << ',' << branch_and_bound_.stats().solution_improvements
            << ',';
  for (int i = 0; i < best_schedule_.size(); ++i)
    log_file_ << std::setprecision (2) << best_schedule_[i] << " ";
  log_file_ << ',';
  CarState next = state;
  for (int i = 0; i < best_schedule_.size(); ++i) {
    next = car_tracker_.Predict(next, game::Command(best_schedule_[i]));
    log_file_ << std::setprecision(2) << next.position().angle() << ' ';
  }
  log_file_ << ',';
  next = state;
  for (int i = 0; i < best_schedule_.size(); ++i) {
    next = car_tracker_.Predict(next, game::Command(0));
    log_file_ << std::setprecision(2) << next.position().angle() << ' ';
  }
  log_file_ << std::endl;
  log_file_.flush();
}

}  // namespace schedulers
<commit_msg>Added a quick version of groups with a short horizon. It makes WojtekThrottleScheduler blazingly fast at making decisions, while making it 0.16s slower on an average lap. Could be used for different purposes (like emergency or safety checking in extream situations).<commit_after>#include "schedulers/wojtek_throttle_scheduler.h"

#include <chrono>
#include <cstdio>
#include <cmath>

#include "gflags/gflags.h"
#include "utils/stopwatch.h"

DEFINE_bool(log_schedule, true, "");

namespace {
  template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
  }
}

namespace schedulers {

using game::CarState;

const vector<int> WojtekThrottleScheduler::DEFAULT_GROUPS {1,1,4,2,2,4,1,8,8,4,4,2};
const vector<int> WojtekThrottleScheduler::QUICK_GROUPS {1,2,4,4,2};

const vector<double> WojtekThrottleScheduler::values{0.0, 1.0}; // Values must be increasing

WojtekThrottleScheduler::WojtekThrottleScheduler(const game::Race& race,
    game::CarTracker& car_tracker, int time_limit, const vector<int>& groups)
  : race_(race), car_tracker_(car_tracker),
    groups_(groups),
    horizon_(std::accumulate(groups.begin(), groups.end(), 0)),
    best_schedule_(&car_tracker, horizon_),
    branch_and_bound_(&car_tracker, horizon_, groups_, values), log_file_("wojtek_data_log.csv", std::ofstream::out), time_limit_(time_limit)
{
   //Watchout: executing two WojtekThrottleSchedulers in pararell could be risky becase of log file (TODO)
   log_file_ << "tick," << "x," << "turbo," << "switch," << "a," << "v," << "dir," << "rad," << "piece_no," << "start_lane," << "end_land," << "schedule_time," << "initial_schedule_safe," << "nodes_visited," << "leafs_visited," << "unsafe_cuts," << "ub_cuts," << "solution_improvements," << "schedule," << "predicted_angles," << "0_throttle_predictions" << std::endl;
}

WojtekThrottleScheduler::~WojtekThrottleScheduler() {
    log_file_.close();
}

void WojtekThrottleScheduler::Schedule(const game::CarState& state, int game_tick) {
  utils::StopWatch stopwatch;

  // We want to use the last best_schedule_ if possible. Generally always
  // tick_diff should always be 1, but I take extra care if
  // (for some unknown reason) this is not the case
  int tick_diff = game_tick - last_game_tick_;
  if (1 <= tick_diff && tick_diff <= 4) {
    for (int i = 0; i < tick_diff; ++i)
      best_schedule_.ShiftLeftFillSafe(state);
  } else {
    // We will still try to use the old schedule, but, it could be not safe.
    // This will be checked subsequently
  }
  // Must do it, because we could have unpredicted turbo/switches, etc. ahead
  best_schedule_.UpdateDistance(state);

  // Initial schedule should be safe normally. Not safe only if future predictions
  // have changed
  initial_schedule_safe_ = best_schedule_.IsSafe(state);
  if (!initial_schedule_safe_) {
    best_schedule_.Reset(state);
  }

  branch_and_bound_.Improve(state, best_schedule_);
  local_improver_.Improve(state, best_schedule_, 0.1);

  // Once again, just to be 200% sure check for safety
  if (!best_schedule_.IsSafe(state)) {
    // This should never happen
    std::cerr << "Schedule is not safe. This should not happen" << std::endl;
    best_schedule_.Reset(state);
  }

  last_game_tick_ = game_tick;
  last_schedule_time_ = stopwatch.elapsed();
  Log(state);
}

void WojtekThrottleScheduler::PrintSchedule(const game::CarState& state, const Sched& schedule, int len) {
  for (int i=0; i<len; ++i)
    printf("%.2f ", schedule[i]);
  printf("\n");

  CarState next = state;
  for (int i=0; i<len; ++i) {
    next = car_tracker_.Predict(next, game::Command(schedule[i]));
    printf("%.1f ", next.position().angle());
  }
  printf("\n");
}

void WojtekThrottleScheduler::Log(const game::CarState& state) {
  if (FLAGS_log_schedule) {
    PrintSchedule(state, best_schedule_, std::min(horizon_, 20));
  }

  game::Piece piece = race_.track().pieces()[state.position().piece()];
  log_file_ << last_game_tick_
            << ',' << throttle()
            << ',' << state.turbo_state().is_on()
            << ',' << (int)state.switch_state()
            << ',' << state.position().angle()
            << ',' << state.velocity()
            << ',' << -sgn(piece.angle())
            << ',' << piece.radius()
            << ',' << state.position().piece()
            << ',' << state.position().start_lane()
            << ',' << state.position().end_lane()
            << ',' << last_schedule_time_
            << ',' << initial_schedule_safe_
            << ',' << branch_and_bound_.stats().nodes_visited
            << ',' << branch_and_bound_.stats().leafs_visited
            << ',' << branch_and_bound_.stats().unsafe_cuts
            << ',' << branch_and_bound_.stats().ub_cuts
            << ',' << branch_and_bound_.stats().solution_improvements
            << ',';
  for (int i = 0; i < best_schedule_.size(); ++i)
    log_file_ << std::setprecision (2) << best_schedule_[i] << " ";
  log_file_ << ',';
  CarState next = state;
  for (int i = 0; i < best_schedule_.size(); ++i) {
    next = car_tracker_.Predict(next, game::Command(best_schedule_[i]));
    log_file_ << std::setprecision(2) << next.position().angle() << ' ';
  }
  log_file_ << ',';
  next = state;
  for (int i = 0; i < best_schedule_.size(); ++i) {
    next = car_tracker_.Predict(next, game::Command(0));
    log_file_ << std::setprecision(2) << next.position().angle() << ' ';
  }
  log_file_ << std::endl;
  log_file_.flush();
}

}  // namespace schedulers
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: servicefactory.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 09:20:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_
#define _CPPUHELPER_SERVICEFACTORY_HXX_

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>

namespace cppu
{

/** Deprecated.  Use cppuhelper/bootstrap.hxx functions instead.

    This bootstraps an initial service factory working on a registry. If the first or both
    parameters contain a value then the service factory is initialized with a simple registry
    or a nested registry. Otherwise the service factory must be initialized later with a valid
    registry.

    @param rWriteRegistryFile
    file name of the simple registry or the first registry file of
    the nested registry which will be opened with read/write rights. This
    file will be created if necessary.
    @param rReadRegistryFile
    file name of the second registry file of the nested registry
    which will be opened with readonly rights.
    @param bReadOnly
    flag which specify that the first registry file will be opened with
    readonly rights. Default is FALSE. If this flag is used the registry
    will not be created if not exist.
    @param rBootstrapPath
    specifies a path where the bootstrap components could be find. If this
    parameter is an empty string the compoents will be searched in the system
    path.
    @deprecated
*/
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > SAL_CALL
createRegistryServiceFactory(
    const ::rtl::OUString & rWriteRegistryFile,
    const ::rtl::OUString & rReadRegistryFile,
    sal_Bool bReadOnly = sal_False,
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) );

/** Deprecated.  Use cppuhelper/bootstrap.hxx functions instead.

    This bootstraps an initial service factory working on a registry file.

    @param rRegistryFile
    file name of the registry to use/ create; if this is an empty
    string, the default registry is used instead
    @param bReadOnly
    flag which specify that the registry file will be opened with
    readonly rights. Default is FALSE. If this flag is used the registry
    will not be created if not exist.
    @param rBootstrapPath
    specifies a path where the bootstrap components could be find. If this
    parameter is an empty string the compoents will be searched in the system
    path.
    @deprecated
*/
inline ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > SAL_CALL
createRegistryServiceFactory(
    const ::rtl::OUString & rRegistryFile,
    sal_Bool bReadOnly = sal_False,
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) )
{
    return ::cppu::createRegistryServiceFactory(
        rRegistryFile, ::rtl::OUString(), bReadOnly, rBootstrapPath );
}

/** Deprecated.  Use cppuhelper/bootstrap.hxx functions instead.

    This bootstraps a service factory without initialize a registry.

    @param rBootstrapPath
    specifies a path where the bootstrap components could be find. If this
    parameter is an empty string the compoents will be searched in the system
    path.
    @deprecated
*/
inline ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > SAL_CALL
createServiceFactory(
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) )
{
    return ::cppu::createRegistryServiceFactory(
        ::rtl::OUString(), ::rtl::OUString(), sal_False, rBootstrapPath );
}

} // end namespace cppu

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.8.140); FILE MERGED 2008/04/01 15:10:53 thb 1.8.140.2: #i85898# Stripping all external header guards 2008/03/28 15:25:21 rt 1.8.140.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: servicefactory.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_
#define _CPPUHELPER_SERVICEFACTORY_HXX_

#include <rtl/ustring.hxx>

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>

namespace cppu
{

/** Deprecated.  Use cppuhelper/bootstrap.hxx functions instead.

    This bootstraps an initial service factory working on a registry. If the first or both
    parameters contain a value then the service factory is initialized with a simple registry
    or a nested registry. Otherwise the service factory must be initialized later with a valid
    registry.

    @param rWriteRegistryFile
    file name of the simple registry or the first registry file of
    the nested registry which will be opened with read/write rights. This
    file will be created if necessary.
    @param rReadRegistryFile
    file name of the second registry file of the nested registry
    which will be opened with readonly rights.
    @param bReadOnly
    flag which specify that the first registry file will be opened with
    readonly rights. Default is FALSE. If this flag is used the registry
    will not be created if not exist.
    @param rBootstrapPath
    specifies a path where the bootstrap components could be find. If this
    parameter is an empty string the compoents will be searched in the system
    path.
    @deprecated
*/
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > SAL_CALL
createRegistryServiceFactory(
    const ::rtl::OUString & rWriteRegistryFile,
    const ::rtl::OUString & rReadRegistryFile,
    sal_Bool bReadOnly = sal_False,
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) );

/** Deprecated.  Use cppuhelper/bootstrap.hxx functions instead.

    This bootstraps an initial service factory working on a registry file.

    @param rRegistryFile
    file name of the registry to use/ create; if this is an empty
    string, the default registry is used instead
    @param bReadOnly
    flag which specify that the registry file will be opened with
    readonly rights. Default is FALSE. If this flag is used the registry
    will not be created if not exist.
    @param rBootstrapPath
    specifies a path where the bootstrap components could be find. If this
    parameter is an empty string the compoents will be searched in the system
    path.
    @deprecated
*/
inline ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > SAL_CALL
createRegistryServiceFactory(
    const ::rtl::OUString & rRegistryFile,
    sal_Bool bReadOnly = sal_False,
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) )
{
    return ::cppu::createRegistryServiceFactory(
        rRegistryFile, ::rtl::OUString(), bReadOnly, rBootstrapPath );
}

/** Deprecated.  Use cppuhelper/bootstrap.hxx functions instead.

    This bootstraps a service factory without initialize a registry.

    @param rBootstrapPath
    specifies a path where the bootstrap components could be find. If this
    parameter is an empty string the compoents will be searched in the system
    path.
    @deprecated
*/
inline ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > SAL_CALL
createServiceFactory(
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) )
{
    return ::cppu::createRegistryServiceFactory(
        ::rtl::OUString(), ::rtl::OUString(), sal_False, rBootstrapPath );
}

} // end namespace cppu

#endif

<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/hwaccelrated/iaccelrated.h>
#include <vespa/vespalib/stllike/string.h>
#include <vespa/vespalib/stllike/hash_map.h>
#include <iostream>
#include <vector>
#include <thread>

using namespace vespalib;
using vespalib::hwaccelrated::IAccelrated;

class Benchmark {
public:
    virtual ~Benchmark() { }
    virtual void compute(size_t docId) const = 0;
};

void
runThread(size_t count, size_t docs, const Benchmark & benchmark, size_t stride)
{
    for (size_t i(0); i < count; i++) {
        for (size_t docId(0); docId < docs; docId++) {
            benchmark.compute((docId*stride)%docs);
        }
    }
}

void
runBenchmark(size_t numThreads, size_t count, size_t docs, const Benchmark & benchmark, size_t stride) {
    std::vector<std::thread> threads;
    threads.reserve(numThreads);
    for (size_t i(0); i < numThreads; i++) {
        threads.emplace_back(runThread, count, docs, benchmark, stride);
    }
    for (auto & thread : threads) {
        thread.join();
    }
}

template <typename T>
class FullBenchmark : public Benchmark
{
public:
    FullBenchmark(size_t numDocs, size_t numValue);
    ~FullBenchmark();
    void compute(size_t docId) const override {
        _dp->dotProduct(&_query[0], &_values[docId * _query.size()], _query.size());
    }
private:
    std::vector<T> _values;
    std::vector<T> _query;
    IAccelrated::UP _dp;
};

template <typename T>
FullBenchmark<T>::FullBenchmark(size_t numDocs, size_t numValues)
    : _values(numDocs*numValues),
      _query(numValues),
      _dp(IAccelrated::getAccelrator())
{
    for (size_t i(0); i < numDocs; i++) {
        for (size_t j(0); j < numValues; j++) {
            _values[i*numValues + j] = j;
        }
    }
    for (size_t j(0); j < numValues; j++) {
        _query[j] = j;
    }
}

template <typename T>
FullBenchmark<T>::~FullBenchmark() = default;

class SparseBenchmark : public Benchmark
{
public:
    SparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues);
    ~SparseBenchmark();
protected:
    struct P {
        P(uint32_t key=0, int32_t value=0) :
            _key(key),
            _value(value)
        { }
        uint32_t _key;
        int32_t  _value;
    };
    size_t _numValues;
    std::vector<P> _values;
};

SparseBenchmark::SparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues)
    : _numValues(numValues),
      _values(numDocs*numValues)
{
    for (size_t i(0); i < numDocs; i++) {
        for (size_t j(0); j < numValues; j++) {
            size_t k(numValues < numQueryValues ?  (j*numQueryValues)/numValues : j);
            _values[i*numValues + j] = P(k, k);
        }
    }
}
SparseBenchmark::~SparseBenchmark() = default;

class UnorderedSparseBenchmark : public SparseBenchmark
{
private:
    typedef hash_map<uint32_t, int32_t> map;
public:
    UnorderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues);
    ~UnorderedSparseBenchmark();
private:
    void compute(size_t docId) const override {
        int64_t sum(0);
        size_t offset(docId*_numValues);
        const auto e(_query.end());
        for (size_t i(0); i < _numValues; i++) {
            auto it = _query.find(_values[offset + i]._key);
            if (it != e) {
                sum += static_cast<int64_t>(_values[offset + i]._value) * it->second;
            }
        }
    }
    map _query;
};

UnorderedSparseBenchmark::UnorderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues)
    : SparseBenchmark(numDocs, numValues, numQueryValues)
{
    for (size_t j(0); j < numQueryValues; j++) {
        _query[j] = j;
    }
}
UnorderedSparseBenchmark::~UnorderedSparseBenchmark() = default;

class OrderedSparseBenchmark : public SparseBenchmark
{
private:
public:
    OrderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues);
    ~OrderedSparseBenchmark();
private:
    void compute(size_t docId) const override {
        int64_t sum(0);
        size_t offset(docId*_numValues);

        for (size_t a(0), b(0); a < _query.size() && b < _numValues; b++) {
            for (; a < _query.size() && (_query[a]._key <= _values[offset + b]._key); a++);
            if (_query[a]._key == _values[offset + b]._key) {
                sum += static_cast<int64_t>(_values[offset + b]._value) * _query[a]._value;
            }
        }
    }
    std::vector<P> _query;
};

OrderedSparseBenchmark::OrderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues)
    : SparseBenchmark(numDocs, numValues, numQueryValues),
      _query(numQueryValues)
{
    for (size_t j(0); j < numQueryValues; j++) {
        size_t k(numValues > numQueryValues ?  j*numValues/numQueryValues : j);
        _query[j] = P(k, k);
    }
}
OrderedSparseBenchmark::~OrderedSparseBenchmark() = default;

int main(int argc, char *argv[])
{
    size_t numDocs(1);
    size_t numValues(1000);
    size_t numQueries(1000000);
    size_t stride(1);
    string type("full");
    if ( argc > 1) {
        type = argv[1];
    }
    if ( argc > 2) {
        numQueries = strtoul(argv[2], nullptr, 0);
    }
    if ( argc > 3) {
        numDocs = strtoul(argv[3], nullptr, 0);
    }
    if ( argc > 4) {
        numValues = strtoul(argv[4], nullptr, 0);
    }
    if (argc > 5) {
        stride = strtoul(argv[5], nullptr, 0);
    }
    size_t numQueryValues = ( argc > 6) : numQueryValues = strtoul(argv[6], nullptr, 0) : numValues;
    std::cout << "type = " << type << std::endl;
    std::cout << "numQueries = " << numQueries << std::endl;
    std::cout << "numDocs = " << numDocs << std::endl;
    std::cout << "numValues = " << numValues << std::endl;
    std::cout << "numQueryValues = " << numQueryValues << std::endl;
    std::cout << "stride =" << stride << std::endl;
    if (type == "full") {
        FullBenchmark<int32_t> bm(numDocs, numValues);
        runBenchmark(numQueries, numDocs, bm, stride);
    } else if (type == "sparse-ordered") {
        OrderedSparseBenchmark bm(numDocs, numValues, numQueryValues);
        runBenchmark(numQueries, numDocs, bm, stride);
    } else if (type == "sparse-unordered") {
        UnorderedSparseBenchmark bm(numDocs, numValues, numQueryValues);
        runBenchmark(numQueries, numDocs, bm, stride);
    } else {
        std::cerr << "type '" << type << "' is unknown." << std::endl;
    }

    return 0;
}

<commit_msg>Make stride and numThreads work<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/hwaccelrated/iaccelrated.h>
#include <vespa/vespalib/stllike/string.h>
#include <vespa/vespalib/stllike/hash_map.h>
#include <iostream>
#include <vector>
#include <thread>

using namespace vespalib;
using vespalib::hwaccelrated::IAccelrated;

class Benchmark {
public:
    virtual ~Benchmark() { }
    virtual void compute(size_t docId) const = 0;
};

void
runThread(size_t count, size_t docs, const Benchmark * benchmark, size_t stride)
{
    for (size_t i(0); i < count; i++) {
        for (size_t docId(0); docId < docs; docId++) {
            benchmark->compute((docId*stride)%docs);
        }
    }
}

void
runBenchmark(size_t numThreads, size_t count, size_t docs, const Benchmark & benchmark, size_t stride) {
    std::vector<std::thread> threads;
    threads.reserve(numThreads);
    for (size_t i(0); i < numThreads; i++) {
        threads.emplace_back(runThread, count, docs, &benchmark, stride);
    }
    for (auto & thread : threads) {
        thread.join();
    }
}

template <typename T>
class FullBenchmark : public Benchmark
{
public:
    FullBenchmark(size_t numDocs, size_t numValue);
    ~FullBenchmark();
    void compute(size_t docId) const override {
        _dp->dotProduct(&_query[0], &_values[docId * _query.size()], _query.size());
    }
private:
    std::vector<T> _values;
    std::vector<T> _query;
    IAccelrated::UP _dp;
};

template <typename T>
FullBenchmark<T>::FullBenchmark(size_t numDocs, size_t numValues)
    : _values(numDocs*numValues),
      _query(numValues),
      _dp(IAccelrated::getAccelrator())
{
    for (size_t i(0); i < numDocs; i++) {
        for (size_t j(0); j < numValues; j++) {
            _values[i*numValues + j] = j;
        }
    }
    for (size_t j(0); j < numValues; j++) {
        _query[j] = j;
    }
}

template <typename T>
FullBenchmark<T>::~FullBenchmark() = default;

class SparseBenchmark : public Benchmark
{
public:
    SparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues);
    ~SparseBenchmark();
protected:
    struct P {
        P(uint32_t key=0, int32_t value=0) :
            _key(key),
            _value(value)
        { }
        uint32_t _key;
        int32_t  _value;
    };
    size_t _numValues;
    std::vector<P> _values;
};

SparseBenchmark::SparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues)
    : _numValues(numValues),
      _values(numDocs*numValues)
{
    for (size_t i(0); i < numDocs; i++) {
        for (size_t j(0); j < numValues; j++) {
            size_t k(numValues < numQueryValues ?  (j*numQueryValues)/numValues : j);
            _values[i*numValues + j] = P(k, k);
        }
    }
}
SparseBenchmark::~SparseBenchmark() = default;

class UnorderedSparseBenchmark : public SparseBenchmark
{
private:
    typedef hash_map<uint32_t, int32_t> map;
public:
    UnorderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues);
    ~UnorderedSparseBenchmark();
private:
    void compute(size_t docId) const override {
        int64_t sum(0);
        size_t offset(docId*_numValues);
        const auto e(_query.end());
        for (size_t i(0); i < _numValues; i++) {
            auto it = _query.find(_values[offset + i]._key);
            if (it != e) {
                sum += static_cast<int64_t>(_values[offset + i]._value) * it->second;
            }
        }
    }
    map _query;
};

UnorderedSparseBenchmark::UnorderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues)
    : SparseBenchmark(numDocs, numValues, numQueryValues)
{
    for (size_t j(0); j < numQueryValues; j++) {
        _query[j] = j;
    }
}
UnorderedSparseBenchmark::~UnorderedSparseBenchmark() = default;

class OrderedSparseBenchmark : public SparseBenchmark
{
private:
public:
    OrderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues);
    ~OrderedSparseBenchmark();
private:
    void compute(size_t docId) const override {
        int64_t sum(0);
        size_t offset(docId*_numValues);

        for (size_t a(0), b(0); a < _query.size() && b < _numValues; b++) {
            for (; a < _query.size() && (_query[a]._key <= _values[offset + b]._key); a++);
            if (_query[a]._key == _values[offset + b]._key) {
                sum += static_cast<int64_t>(_values[offset + b]._value) * _query[a]._value;
            }
        }
    }
    std::vector<P> _query;
};

OrderedSparseBenchmark::OrderedSparseBenchmark(size_t numDocs, size_t numValues, size_t numQueryValues)
    : SparseBenchmark(numDocs, numValues, numQueryValues),
      _query(numQueryValues)
{
    for (size_t j(0); j < numQueryValues; j++) {
        size_t k(numValues > numQueryValues ?  j*numValues/numQueryValues : j);
        _query[j] = P(k, k);
    }
}
OrderedSparseBenchmark::~OrderedSparseBenchmark() = default;

int main(int argc, char *argv[])
{
    size_t numThreads(1);
    size_t numDocs(1);
    size_t numValues(1000);
    size_t numQueries(1000000);
    size_t stride(1);
    string type("full");
    if ( argc > 1) {
        type = argv[1];
    }
    if ( argc > 2) {
        numThreads = strtoul(argv[2], nullptr, 0);
    }
    if ( argc > 3) {
        numQueries = strtoul(argv[3], nullptr, 0);
    }
    if ( argc > 4) {
        numDocs = strtoul(argv[4], nullptr, 0);
    }
    if ( argc > 5) {
        numValues = strtoul(argv[5], nullptr, 0);
    }
    if (argc > 6) {
        stride = strtoul(argv[6], nullptr, 0);
    }
    size_t numQueryValues = ( argc > 7) ? strtoul(argv[7], nullptr, 0) : numValues;
    std::cout << "type = " << type << std::endl;
    std::cout << "numQueries = " << numQueries << std::endl;
    std::cout << "numDocs = " << numDocs << std::endl;
    std::cout << "numValues = " << numValues << std::endl;
    std::cout << "numQueryValues = " << numQueryValues << std::endl;
    std::cout << "stride =" << stride << std::endl;
    if (type == "full") {
        FullBenchmark<float> bm(numDocs, numValues);
        runBenchmark(numThreads, numQueries, numDocs, bm, stride);
    } else if (type == "sparse-ordered") {
        OrderedSparseBenchmark bm(numDocs, numValues, numQueryValues);
        runBenchmark(numThreads, numQueries, numDocs, bm, stride);
    } else if (type == "sparse-unordered") {
        UnorderedSparseBenchmark bm(numDocs, numValues, numQueryValues);
        runBenchmark(numThreads, numQueries, numDocs, bm, stride);
    } else {
        std::cerr << "type '" << type << "' is unknown." << std::endl;
    }

    return 0;
}

<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich 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 "views/MainView.h"
#include "Scene.h"
#include "Logger/src/Timer.h"
#include "cursor/Cursor.h"
#include "items/Item.h"

#include <items/RootItem.h>

namespace Visualization {

MainView::MainView(Scene *scene) :
	View(scene, nullptr), miniMap(new MiniMap(scene, this)), scaleLevel(SCALING_FACTOR)
{
	setRenderHint(QPainter::Antialiasing);
	setRenderHint(QPainter::TextAntialiasing);

	setTransformationAnchor(QGraphicsView::AnchorUnderMouse);

	setMiniMapSize(MINIMAP_DEFAULT_WIDTH, MINIMAP_DEFAULT_HEIGHT);
}

MainView::~MainView()
{
	SAFE_DELETE(miniMap);
}

void MainView::setMiniMapSize(int width, int height)
{
	if ( miniMap )
	{
		miniMap->resize(width, height);
		miniMap->sceneRectChanged(scene()->sceneRect());
	}
}

bool MainView::event( QEvent *event )
{
	bool result = false;

	switch (event->type())
	{
		case QEvent::KeyPress :
		{
			QKeyEvent *k = (QKeyEvent *)event;
			keyPressEvent(k);
			if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept();
			result = true;
		}
		break;
		case QEvent::KeyRelease :
		{
			QKeyEvent *k = (QKeyEvent *)event;
			keyReleaseEvent(k);
			if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept();
			result = true;
		}
		break;
		default: result = View::event( event );
		break;
	}

	// The checks below are necessary to avoid infinite recursion.
	if ( event->type() != QEvent::ChildAdded
			&& event->type() != QEvent::ChildRemoved
			&& event->type() != QEvent::ChildPolished) updateInfoLabels();
	return result;
}

void MainView::resizeEvent(QResizeEvent *event)
{
	View::resizeEvent(event);
	if ( miniMap )
	{
		miniMap->updatePosition();
		miniMap->visibleRectChanged();
	}
}

void MainView::wheelEvent(QWheelEvent *event)
{
	// Zoom
	if (event->modifiers() == Qt::ControlModifier)
	{
		if ( event->delta() > 0 ) scaleLevel--;
		else scaleLevel++;

		if ( scaleLevel <= 0 ) scaleLevel = 1;
		qreal factor = scaleFactor();
		setTransform(QTransform::fromScale(factor, factor));

		if ( miniMap ) miniMap->visibleRectChanged();

		scene()->setMainViewScalingFactor(factor);
	}
	// Scroll
	else if (event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ShiftModifier)
	{
		auto bar = event->orientation() == Qt::Vertical && event->modifiers() == Qt::NoModifier
				? verticalScrollBar() : horizontalScrollBar();

		bar->setValue( bar->value() - event->delta() );
	}

	View::wheelEvent(event);
}

qreal MainView::scaleFactor() const
{
	if (scaleLevel < SCALING_FACTOR)
		return SCALING_FACTOR / (qreal) scaleLevel;
	else return std::pow(2, SCALING_FACTOR - scaleLevel);
}

void MainView::scrollContentsBy(int dx, int dy)
{
	View::scrollContentsBy(dx, dy);
	if ( miniMap ) miniMap->visibleRectChanged();
}

void MainView::keyPressEvent(QKeyEvent *event)
{
	if ( (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::ShiftModifier)
			&& event->key() == Qt::Key_Print)
	{
		event->accept();
		scene()->setHiddenItemCategories(0);

		QPrinter printer;
		printer.setOutputFormat(QPrinter::PdfFormat);
		printer.setFullPage(true);
		printer.setResolution(300);

		QSvgGenerator svggen;
		svggen.setResolution(90);

		bool ownerIgnoresScale = setCursorAndOwnerIgnoreScaleForScreenShot(false, false);

		if (event->modifiers() & Qt::ShiftModifier)
		{
			// Print scene
			printer.setOutputFileName("screenshot-scene.pdf");
			printer.setPaperSize(scene()->sceneRect().size().toSize(), QPrinter::Point);
			QPainter painter(&printer);
			painter.setRenderHint(QPainter::Antialiasing);
			scene()->render( &painter );

			svggen.setFileName("screenshot-scene.svg");
			svggen.setSize(scene()->sceneRect().size().toSize());
			QPainter svgPainter(&svggen);
			svgPainter.setRenderHint(QPainter::Antialiasing);
			scene()->render(&svgPainter);

			QImage image(PNG_SCREENSHOT_SCALE * scene()->sceneRect().size().toSize(), QImage::Format_ARGB32);
			image.fill(Qt::transparent);
			QPainter pmapPainter(&image);
			pmapPainter.setRenderHint(QPainter::Antialiasing);
			//pmapPainter.scale(2,2);
			scene()->render(&pmapPainter);
			image.save("screenshot-scene.png");
		}
		else
		{
			// Print view
			printer.setOutputFileName("screenshot-view.pdf");
			printer.setPaperSize(viewport()->rect().size(), QPrinter::Point);
			QPainter painter(&printer);
			painter.setRenderHint(QPainter::Antialiasing);
			render(&painter);

			svggen.setFileName("screenshot-view.svg");
			svggen.setSize(viewport()->rect().size());
			QPainter svgPainter(&svggen);
			svgPainter.setRenderHint(QPainter::Antialiasing);
			render(&svgPainter);

			QImage image(PNG_SCREENSHOT_SCALE * viewport()->rect().size(), QImage::Format_ARGB32);
			image.fill(Qt::transparent);
			QPainter pmapPainter(&image);
			pmapPainter.setRenderHint(QPainter::Antialiasing);
			render(&pmapPainter);
			image.save("screenshot-view.png");
		}

		setCursorAndOwnerIgnoreScaleForScreenShot(true, ownerIgnoresScale);
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F11)
	{
		event->accept();
		QWidget* window = this;
		while (window->parentWidget()) window = window->parentWidget();

		if (window->isFullScreen()) window->showNormal();
		else window->showFullScreen();
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F10)
	{
		event->accept();
		if (miniMap->width() == MINIMAP_DEFAULT_WIDTH && miniMap->height() ==  MINIMAP_DEFAULT_HEIGHT)
			setMiniMapSize(width(), height());
		else setMiniMapSize(MINIMAP_DEFAULT_WIDTH, MINIMAP_DEFAULT_HEIGHT);
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F9)
	{
		event->accept();
		if (miniMap->isVisible()) miniMap->hide();
		else miniMap->show();
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F7)
	{
		event->accept();
		showTimers_ = ~showTimers_;
		updateInfoLabels();
	}
	else View::keyPressEvent(event);
}

void MainView::updateInfoLabels()
{
	if (!showTimers_)
	{
		if (!infoLabels_.isEmpty())
		{
			for (auto l : infoLabels_) SAFE_DELETE(l);
			infoLabels_.clear();
		}
		return;
	}

	int labelIndex = 0;
	int yPos = 10;

	// Add timers
	for (auto name : Logger::Timer::timerNames())
	{
		QLabel* label{};

		if (infoLabels_.size() <= labelIndex)
		{
			label = new QLabel(this);
			label->setAttribute(Qt::WA_TransparentForMouseEvents);
			infoLabels_.append(label);
			label->show();
			label->setStyleSheet("QLabel { color : red; }");
		}
		else label = infoLabels_.at(labelIndex);

		// Set the position of the label
		label->move(10, yPos);

		// Construct label text
		auto info = name + ":  ";
		for (auto val : Logger::Timer::timer(name)->values())
			info += QString::number(val) + "  ";

		label->setText(info);
		label->adjustSize();

		++labelIndex;
		yPos+=label->height();
	}

	// Remove unnecessary labels
	while (labelIndex < infoLabels_.size() )
	{
		SAFE_DELETE(infoLabels_.last());
		infoLabels_.removeLast();
	}
}

void MainView::paintEvent(QPaintEvent* event)
{
	auto t = Logger::Timer::start("Main view paint");
	View::paintEvent(event);
	t->tick();
}

void MainView::mouseMoveEvent(QMouseEvent *event)
{
	if (!isPanning_) return View::mouseMoveEvent(event);

	event->accept();
	horizontalScrollBar()->setValue(horizontalScrollBar()->value() - (event->x() - panStartPos_.x()));
	verticalScrollBar()->setValue(verticalScrollBar()->value() - (event->y() - panStartPos_.y()));
	panStartPos_ = event->pos();
}

void MainView::mousePressEvent(QMouseEvent *event)
{
	if (event->modifiers() != Qt::ControlModifier) return View::mousePressEvent(event);

	event->accept();
	isPanning_ = true;
	panStartPos_ = event->pos();
	setCursor(Qt::ClosedHandCursor);
}

void MainView::mouseReleaseEvent(QMouseEvent *event)
{
	if (!isPanning_) return View::mouseReleaseEvent(event);

	event->accept();
	setCursor(Qt::ArrowCursor);
	isPanning_ = false;
}

bool MainView::setCursorAndOwnerIgnoreScaleForScreenShot(bool ignore, bool modifyOwner)
{
	bool ownerIgnoresScale = false;

	auto cursor = scene()->mainCursor();
	if (cursor)
	{
		if ( auto vis = cursor->visualization() ) vis->setFlag(Item::ItemIgnoresTransformations, ignore);
		auto owner = cursor->owner();
		if (owner)
		{
			while (owner->parent()) owner = owner->parent();
			if (!ignore)
			{
				ownerIgnoresScale = owner->flags() & Item::ItemIgnoresTransformations;
				if (ownerIgnoresScale) owner->setFlag(Item::ItemIgnoresTransformations, false);
			}
			else if (modifyOwner) owner->setFlag(Item::ItemIgnoresTransformations, true);
		}
	}

	return ownerIgnoresScale;
}

}
<commit_msg>Change geometric zoom step to be smaller<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich 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 "views/MainView.h"
#include "Scene.h"
#include "Logger/src/Timer.h"
#include "cursor/Cursor.h"
#include "items/Item.h"

#include <items/RootItem.h>

namespace Visualization {

MainView::MainView(Scene *scene) :
	View(scene, nullptr), miniMap(new MiniMap(scene, this)), scaleLevel(SCALING_FACTOR)
{
	setRenderHint(QPainter::Antialiasing);
	setRenderHint(QPainter::TextAntialiasing);

	setTransformationAnchor(QGraphicsView::AnchorUnderMouse);

	setMiniMapSize(MINIMAP_DEFAULT_WIDTH, MINIMAP_DEFAULT_HEIGHT);
}

MainView::~MainView()
{
	SAFE_DELETE(miniMap);
}

void MainView::setMiniMapSize(int width, int height)
{
	if ( miniMap )
	{
		miniMap->resize(width, height);
		miniMap->sceneRectChanged(scene()->sceneRect());
	}
}

bool MainView::event( QEvent *event )
{
	bool result = false;

	switch (event->type())
	{
		case QEvent::KeyPress :
		{
			QKeyEvent *k = (QKeyEvent *)event;
			keyPressEvent(k);
			if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept();
			result = true;
		}
		break;
		case QEvent::KeyRelease :
		{
			QKeyEvent *k = (QKeyEvent *)event;
			keyReleaseEvent(k);
			if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept();
			result = true;
		}
		break;
		default: result = View::event( event );
		break;
	}

	// The checks below are necessary to avoid infinite recursion.
	if ( event->type() != QEvent::ChildAdded
			&& event->type() != QEvent::ChildRemoved
			&& event->type() != QEvent::ChildPolished) updateInfoLabels();
	return result;
}

void MainView::resizeEvent(QResizeEvent *event)
{
	View::resizeEvent(event);
	if ( miniMap )
	{
		miniMap->updatePosition();
		miniMap->visibleRectChanged();
	}
}

void MainView::wheelEvent(QWheelEvent *event)
{
	// Zoom
	if (event->modifiers() == Qt::ControlModifier)
	{
		if ( event->delta() > 0 ) scaleLevel--;
		else scaleLevel++;

		if ( scaleLevel <= 0 ) scaleLevel = 1;
		qreal factor = scaleFactor();
		setTransform(QTransform::fromScale(factor, factor));

		if ( miniMap ) miniMap->visibleRectChanged();

		scene()->setMainViewScalingFactor(factor);
	}
	// Scroll
	else if (event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ShiftModifier)
	{
		auto bar = event->orientation() == Qt::Vertical && event->modifiers() == Qt::NoModifier
				? verticalScrollBar() : horizontalScrollBar();

		bar->setValue( bar->value() - event->delta() );
	}

	View::wheelEvent(event);
}

qreal MainView::scaleFactor() const
{
	if (scaleLevel < SCALING_FACTOR)
		return SCALING_FACTOR / (qreal) scaleLevel;
	else return std::pow(1.1, SCALING_FACTOR - scaleLevel);
}

void MainView::scrollContentsBy(int dx, int dy)
{
	View::scrollContentsBy(dx, dy);
	if ( miniMap ) miniMap->visibleRectChanged();
}

void MainView::keyPressEvent(QKeyEvent *event)
{
	if ( (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::ShiftModifier)
			&& event->key() == Qt::Key_Print)
	{
		event->accept();
		scene()->setHiddenItemCategories(0);

		QPrinter printer;
		printer.setOutputFormat(QPrinter::PdfFormat);
		printer.setFullPage(true);
		printer.setResolution(300);

		QSvgGenerator svggen;
		svggen.setResolution(90);

		bool ownerIgnoresScale = setCursorAndOwnerIgnoreScaleForScreenShot(false, false);

		if (event->modifiers() & Qt::ShiftModifier)
		{
			// Print scene
			printer.setOutputFileName("screenshot-scene.pdf");
			printer.setPaperSize(scene()->sceneRect().size().toSize(), QPrinter::Point);
			QPainter painter(&printer);
			painter.setRenderHint(QPainter::Antialiasing);
			scene()->render( &painter );

			svggen.setFileName("screenshot-scene.svg");
			svggen.setSize(scene()->sceneRect().size().toSize());
			QPainter svgPainter(&svggen);
			svgPainter.setRenderHint(QPainter::Antialiasing);
			scene()->render(&svgPainter);

			QImage image(PNG_SCREENSHOT_SCALE * scene()->sceneRect().size().toSize(), QImage::Format_ARGB32);
			image.fill(Qt::transparent);
			QPainter pmapPainter(&image);
			pmapPainter.setRenderHint(QPainter::Antialiasing);
			//pmapPainter.scale(2,2);
			scene()->render(&pmapPainter);
			image.save("screenshot-scene.png");
		}
		else
		{
			// Print view
			printer.setOutputFileName("screenshot-view.pdf");
			printer.setPaperSize(viewport()->rect().size(), QPrinter::Point);
			QPainter painter(&printer);
			painter.setRenderHint(QPainter::Antialiasing);
			render(&painter);

			svggen.setFileName("screenshot-view.svg");
			svggen.setSize(viewport()->rect().size());
			QPainter svgPainter(&svggen);
			svgPainter.setRenderHint(QPainter::Antialiasing);
			render(&svgPainter);

			QImage image(PNG_SCREENSHOT_SCALE * viewport()->rect().size(), QImage::Format_ARGB32);
			image.fill(Qt::transparent);
			QPainter pmapPainter(&image);
			pmapPainter.setRenderHint(QPainter::Antialiasing);
			render(&pmapPainter);
			image.save("screenshot-view.png");
		}

		setCursorAndOwnerIgnoreScaleForScreenShot(true, ownerIgnoresScale);
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F11)
	{
		event->accept();
		QWidget* window = this;
		while (window->parentWidget()) window = window->parentWidget();

		if (window->isFullScreen()) window->showNormal();
		else window->showFullScreen();
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F10)
	{
		event->accept();
		if (miniMap->width() == MINIMAP_DEFAULT_WIDTH && miniMap->height() ==  MINIMAP_DEFAULT_HEIGHT)
			setMiniMapSize(width(), height());
		else setMiniMapSize(MINIMAP_DEFAULT_WIDTH, MINIMAP_DEFAULT_HEIGHT);
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F9)
	{
		event->accept();
		if (miniMap->isVisible()) miniMap->hide();
		else miniMap->show();
	}
	else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F7)
	{
		event->accept();
		showTimers_ = ~showTimers_;
		updateInfoLabels();
	}
	else View::keyPressEvent(event);
}

void MainView::updateInfoLabels()
{
	if (!showTimers_)
	{
		if (!infoLabels_.isEmpty())
		{
			for (auto l : infoLabels_) SAFE_DELETE(l);
			infoLabels_.clear();
		}
		return;
	}

	int labelIndex = 0;
	int yPos = 10;

	// Add timers
	for (auto name : Logger::Timer::timerNames())
	{
		QLabel* label{};

		if (infoLabels_.size() <= labelIndex)
		{
			label = new QLabel(this);
			label->setAttribute(Qt::WA_TransparentForMouseEvents);
			infoLabels_.append(label);
			label->show();
			label->setStyleSheet("QLabel { color : red; }");
		}
		else label = infoLabels_.at(labelIndex);

		// Set the position of the label
		label->move(10, yPos);

		// Construct label text
		auto info = name + ":  ";
		for (auto val : Logger::Timer::timer(name)->values())
			info += QString::number(val) + "  ";

		label->setText(info);
		label->adjustSize();

		++labelIndex;
		yPos+=label->height();
	}

	// Remove unnecessary labels
	while (labelIndex < infoLabels_.size() )
	{
		SAFE_DELETE(infoLabels_.last());
		infoLabels_.removeLast();
	}
}

void MainView::paintEvent(QPaintEvent* event)
{
	auto t = Logger::Timer::start("Main view paint");
	View::paintEvent(event);
	t->tick();
}

void MainView::mouseMoveEvent(QMouseEvent *event)
{
	if (!isPanning_) return View::mouseMoveEvent(event);

	event->accept();
	horizontalScrollBar()->setValue(horizontalScrollBar()->value() - (event->x() - panStartPos_.x()));
	verticalScrollBar()->setValue(verticalScrollBar()->value() - (event->y() - panStartPos_.y()));
	panStartPos_ = event->pos();
}

void MainView::mousePressEvent(QMouseEvent *event)
{
	if (event->modifiers() != Qt::ControlModifier) return View::mousePressEvent(event);

	event->accept();
	isPanning_ = true;
	panStartPos_ = event->pos();
	setCursor(Qt::ClosedHandCursor);
}

void MainView::mouseReleaseEvent(QMouseEvent *event)
{
	if (!isPanning_) return View::mouseReleaseEvent(event);

	event->accept();
	setCursor(Qt::ArrowCursor);
	isPanning_ = false;
}

bool MainView::setCursorAndOwnerIgnoreScaleForScreenShot(bool ignore, bool modifyOwner)
{
	bool ownerIgnoresScale = false;

	auto cursor = scene()->mainCursor();
	if (cursor)
	{
		if ( auto vis = cursor->visualization() ) vis->setFlag(Item::ItemIgnoresTransformations, ignore);
		auto owner = cursor->owner();
		if (owner)
		{
			while (owner->parent()) owner = owner->parent();
			if (!ignore)
			{
				ownerIgnoresScale = owner->flags() & Item::ItemIgnoresTransformations;
				if (ownerIgnoresScale) owner->setFlag(Item::ItemIgnoresTransformations, false);
			}
			else if (modifyOwner) owner->setFlag(Item::ItemIgnoresTransformations, true);
		}
	}

	return ownerIgnoresScale;
}

}
<|endoftext|>


<commit_before>/****************************************************************/
/*             DO NOT MODIFY OR REMOVE THIS HEADER              */
/*          FALCON - Fracturing And Liquid CONvection           */
/*                                                              */
/*       (c) pending 2012 Battelle Energy Alliance, LLC         */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "CoupledTemperatureAux.h"
#include "WaterSteamEOS.h"

template<>
InputParameters validParams<CoupledTemperatureAux>()
{
    InputParameters params = validParams<AuxKernel>();
    params.addCoupledVar("pressure", "Use pressure to calculate variable temperature");
    params.addCoupledVar("enthalpy", "Use enthalpy to calculate variable temperature");
    params.addParam("temperature", 100., "Initial value for temperature");
    params.addRequiredParam<UserObjectName>("water_steam_properties", "EOS functions, calculate water and steam properties");
    return params;
}

CoupledTemperatureAux::CoupledTemperatureAux(const std::string & name,
                                               InputParameters parameters)
    :AuxKernel(name, parameters),
    _water_steam_properties(getUserObject<WaterSteamEOS>("water_steam_properties")),

    _pressure(coupledValue("pressure")),
    _enthalpy(coupledValue("enthalpy")),
    _input_temperature(getParam<Real>("temperature"))
{}

Real
CoupledTemperatureAux::computeValue()
{
    Real _temperature = _input_temperature;
    Real _dummy_var[12];

    _water_steam_properties.waterAndSteamEquationOfStatePropertiesPH (_enthalpy[_qp], _pressure[_qp], _dummy_var[0] , _temperature, _dummy_var[1], _dummy_var[2], _dummy_var[3], _dummy_var[4], _dummy_var[5], _dummy_var[6], _dummy_var[7], _dummy_var[8], _dummy_var[9], _dummy_var[10], _dummy_var[11]);

    return _temperature;

}

<commit_msg>Fixing strange file permissions... C files should not have execute bit set.<commit_after>/****************************************************************/
/*             DO NOT MODIFY OR REMOVE THIS HEADER              */
/*          FALCON - Fracturing And Liquid CONvection           */
/*                                                              */
/*       (c) pending 2012 Battelle Energy Alliance, LLC         */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "CoupledTemperatureAux.h"
#include "WaterSteamEOS.h"

template<>
InputParameters validParams<CoupledTemperatureAux>()
{
    InputParameters params = validParams<AuxKernel>();
    params.addCoupledVar("pressure", "Use pressure to calculate variable temperature");
    params.addCoupledVar("enthalpy", "Use enthalpy to calculate variable temperature");
    params.addParam("temperature", 100., "Initial value for temperature");
    params.addRequiredParam<UserObjectName>("water_steam_properties", "EOS functions, calculate water and steam properties");
    return params;
}

CoupledTemperatureAux::CoupledTemperatureAux(const std::string & name,
                                               InputParameters parameters)
    :AuxKernel(name, parameters),
    _water_steam_properties(getUserObject<WaterSteamEOS>("water_steam_properties")),

    _pressure(coupledValue("pressure")),
    _enthalpy(coupledValue("enthalpy")),
    _input_temperature(getParam<Real>("temperature"))
{}

Real
CoupledTemperatureAux::computeValue()
{
    Real _temperature = _input_temperature;
    Real _dummy_var[12];

    _water_steam_properties.waterAndSteamEquationOfStatePropertiesPH (_enthalpy[_qp], _pressure[_qp], _dummy_var[0] , _temperature, _dummy_var[1], _dummy_var[2], _dummy_var[3], _dummy_var[4], _dummy_var[5], _dummy_var[6], _dummy_var[7], _dummy_var[8], _dummy_var[9], _dummy_var[10], _dummy_var[11]);

    return _temperature;

}

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// hash_set_op_executor.cpp
//
// Identification: src/backend/executor/hash_set_op_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <utility>
#include <vector>

#include "backend/common/logger.h"
#include "backend/common/value.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/hash_executor.h"
#include "backend/planner/hash_plan.h"
#include "backend/expression/tuple_value_expression.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor
 */
HashExecutor::HashExecutor(const planner::AbstractPlan *node,
                                     ExecutorContext *executor_context)
    : AbstractExecutor(node, executor_context) {}

/**
 * @brief Do some basic checks and initialize executor state.
 * @return true on success, false otherwise.
 */
bool HashExecutor::DInit() {
  assert(children_.size() == 1);
  return true;
}

bool HashExecutor::DExecute() {
  LOG_INFO("Hash Executor");

  if (!done_) {
    const planner::HashPlan &node = GetPlanNode<planner::HashPlan>();

    while (children_[0]->Execute()) {
      child_tiles_.emplace_back(children_[0]->GetOutput());
    }

    if (child_tiles_.size() == 0) return false;

    /* HashKeys should be a vector of TupleValue expr
     * from which we construct a vector of column ids that represent the
     * attributes of the underlying table.
     * The hash table builds on these attributes */
    auto &hashkeys = node.GetHashKeys();
    for (auto &hashkey : hashkeys) {
      assert(hashkey->GetExpressionType() == EXPRESSION_TYPE_VALUE_TUPLE);
      auto tuple_value = reinterpret_cast<const expression::TupleValueExpression *>(hashkey.get());
      //assert(tuple_value->GetTupleIdx() == 0);
      column_ids_.push_back(tuple_value->GetColumnId());
    }

    for (size_t i = 0; i < child_tiles_.size(); i++) {
      auto tile = child_tiles_[i].get();
      for (oid_t tuple_id : *tile) {
        htable_[HashMapType::key_type(tile, tuple_id, &column_ids_)].insert(std::make_pair(i, tuple_id));
      }
    }

    done_ = true;
  }

  DumpHashTable();

  while (result_itr < child_tiles_.size()) {
    if (child_tiles_[result_itr]->GetTupleCount() == 0) {
      result_itr++;
      continue;
    } else {
      SetOutput(child_tiles_[result_itr++].release());
      return true;
    }
  }
  return false;
}

void HashExecutor::DumpHashTable() const {
  assert(done_);
  for (auto &kv : htable_) {
    LOG_INFO("Key %lu, Num of tuple: %lu", kv.first.HashCode(), kv.second.size());
  }

}

} /* namespace executor */
} /* namespace peloton */
<commit_msg>Refactored hash and hash join executors<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// hash_set_op_executor.cpp
//
// Identification: src/backend/executor/hash_set_op_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <utility>
#include <vector>

#include "backend/common/logger.h"
#include "backend/common/value.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/hash_executor.h"
#include "backend/planner/hash_plan.h"
#include "backend/expression/tuple_value_expression.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor
 */
HashExecutor::HashExecutor(const planner::AbstractPlan *node,
                           ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}

/**
 * @brief Do some basic checks and initialize executor state.
 * @return true on success, false otherwise.
 */
bool HashExecutor::DInit() {
  assert(children_.size() == 1);

  // Initialize executor state
  done_ = false;
  result_itr = 0;

  return true;
}

bool HashExecutor::DExecute() {
  LOG_INFO("Hash Executor");

  if (!done_) {
    const planner::HashPlan &node = GetPlanNode<planner::HashPlan>();

    // First, get all the input logical tiles
    while (children_[0]->Execute()) {
      child_tiles_.emplace_back(children_[0]->GetOutput());
    }

    if (child_tiles_.size() == 0)
      return false;

    /* *
     * HashKeys is a vector of TupleValue expr
     * from which we construct a vector of column ids that represent the
     * attributes of the underlying table.
     * The hash table is built on top of these hash key attributes
     * */
    auto &hashkeys = node.GetHashKeys();

    // Construct a logical tile
    for (auto &hashkey : hashkeys) {
      assert(hashkey->GetExpressionType() == EXPRESSION_TYPE_VALUE_TUPLE);
      auto tuple_value = reinterpret_cast<const expression::TupleValueExpression *>(hashkey.get());
      column_ids_.push_back(tuple_value->GetColumnId());
    }

    // Construct the hash table by going over each child logical tile and hashing
    for (size_t child_tile_itr = 0; child_tile_itr < child_tiles_.size(); child_tile_itr++) {
      auto tile = child_tiles_[child_tile_itr].get();

      // Go over all tuples in the logical tile
      for (oid_t tuple_id : *tile) {
        // Key : container tuple with a subset of tuple attributes
        // Value : < child_tile offset, tuple offset >
        htable_[HashMapType::key_type(tile, tuple_id, &column_ids_)].insert(std::make_pair(child_tile_itr, tuple_id));
      }

    }

    done_ = true;
  }

  // Print hash table for debugging
  DumpHashTable();

  // Return logical tiles one at a time
  while (result_itr < child_tiles_.size()) {
    if (child_tiles_[result_itr]->GetTupleCount() == 0) {
      result_itr++;
      continue;
    } else {
      SetOutput(child_tiles_[result_itr++].release());
      return true;
    }
  }

  return false;
}

void HashExecutor::DumpHashTable() const {
  assert(done_);

  // Go over hash table
  for (auto &kv : htable_) {
    LOG_INFO("Key %lu, Num of tuple: %lu", kv.first.HashCode(), kv.second.size());
  }

}

} /* namespace executor */
} /* namespace peloton */
<|endoftext|>


<commit_before>
#include "../../Flare.h"
#include "FlarePlanetaryBox.h"

void SFlarePlanetaryBox::Construct(const SFlarePlanetaryBox::FArguments& InArgs)
{
	Radius = 200;
	PlanetImage = NULL;
	ClearChildren();

	// Add slots
	const int32 NumSlots = InArgs.Slots.Num();
	for (int32 SlotIndex = 0; SlotIndex < NumSlots; ++SlotIndex)
	{
		Children.Add(InArgs.Slots[SlotIndex]);
	}
}

void SFlarePlanetaryBox::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();

	for (int32 ChildIndex = 0; ChildIndex < Children.Num(); ++ChildIndex)
	{
		// Get all required data
		const SFlarePlanetaryBox::FSlot& CurChild = Children[ChildIndex];
		const EVisibility ChildVisibility = CurChild.GetWidget()->GetVisibility();
		FVector2D WidgetSize = CurChild.GetWidget()->GetDesiredSize();
		FVector2D Offset = FVector2D::ZeroVector;

		// Child with index 0 is the main body, index 1 is probably the name but we don't care, others are sectors
		if (ChildIndex > 0)
		{
			float X, Y;
			float Angle = (360 / (Children.Num() - 1)) * (ChildIndex - 1) - 90;
			FMath::PolarToCartesian(Radius, FMath::DegreesToRadians(Angle), X, Y);
			Offset = FVector2D(X, Y);

			WidgetSize = FVector2D(CurChild.GetWidget()->GetDesiredSize().X, Theme.SectorButtonHeight);
		}

		// Arrange the child
		FVector2D Location = (AllottedGeometry.GetLocalSize() - WidgetSize) / 2 + Offset;
		ArrangedChildren.AddWidget(ChildVisibility, AllottedGeometry.MakeChild(
			CurChild.GetWidget(),
			Location,
			CurChild.GetWidget()->GetDesiredSize()
		));
	}
}

FVector2D SFlarePlanetaryBox::ComputeDesiredSize(float) const
{
	return 2.6 * FVector2D(Radius, Radius);
}

FChildren* SFlarePlanetaryBox::GetChildren()
{
	return &Children;
}

int32 SFlarePlanetaryBox::RemoveSlot(const TSharedRef<SWidget>& SlotWidget)
{
	for (int32 SlotIdx = 0; SlotIdx < Children.Num(); ++SlotIdx)
	{
		if (SlotWidget == Children[SlotIdx].GetWidget())
		{
			Children.RemoveAt(SlotIdx);
			return SlotIdx;
		}
	}

	return -1;
}

void SFlarePlanetaryBox::ClearChildren()
{
	Children.Empty();

	if (PlanetImage)
	{
		AddSlot()
		[
			SNew(SImage).Image(PlanetImage)
		];
	}
}
<commit_msg>Fix orbital layout<commit_after>
#include "../../Flare.h"
#include "FlarePlanetaryBox.h"

void SFlarePlanetaryBox::Construct(const SFlarePlanetaryBox::FArguments& InArgs)
{
	Radius = 200;
	PlanetImage = NULL;
	ClearChildren();

	// Add slots
	const int32 NumSlots = InArgs.Slots.Num();
	for (int32 SlotIndex = 0; SlotIndex < NumSlots; ++SlotIndex)
	{
		Children.Add(InArgs.Slots[SlotIndex]);
	}
}

void SFlarePlanetaryBox::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();

	for (int32 ChildIndex = 0; ChildIndex < Children.Num(); ++ChildIndex)
	{
		// Get all required data
		const SFlarePlanetaryBox::FSlot& CurChild = Children[ChildIndex];
		const EVisibility ChildVisibility = CurChild.GetWidget()->GetVisibility();
		FVector2D WidgetSize = CurChild.GetWidget()->GetDesiredSize();
		FVector2D Offset = FVector2D::ZeroVector;

		// Child with index 0 is the main body, index 1 is probably the name but we don't care, others are sectors
		if (ChildIndex > 0)
		{
			float X, Y;
			float Angle = (360 / (Children.Num() - 1)) * (ChildIndex - 1) - 90;
			FMath::PolarToCartesian(Radius, FMath::DegreesToRadians(Angle), X, Y);
			Offset = FVector2D(X, Y);

			WidgetSize = FVector2D(CurChild.GetWidget()->GetDesiredSize().X, Theme.SectorButtonHeight);
		}

		// Arrange the child
		FVector2D Location = (AllottedGeometry.GetLocalSize() - WidgetSize) / 2 + Offset;
		ArrangedChildren.AddWidget(ChildVisibility, AllottedGeometry.MakeChild(
			CurChild.GetWidget(),
			Location,
			CurChild.GetWidget()->GetDesiredSize()
		));
	}
}

FVector2D SFlarePlanetaryBox::ComputeDesiredSize(float) const
{
	return FVector2D(2.6 * Radius, 2.8 * Radius);
}

FChildren* SFlarePlanetaryBox::GetChildren()
{
	return &Children;
}

int32 SFlarePlanetaryBox::RemoveSlot(const TSharedRef<SWidget>& SlotWidget)
{
	for (int32 SlotIdx = 0; SlotIdx < Children.Num(); ++SlotIdx)
	{
		if (SlotWidget == Children[SlotIdx].GetWidget())
		{
			Children.RemoveAt(SlotIdx);
			return SlotIdx;
		}
	}

	return -1;
}

void SFlarePlanetaryBox::ClearChildren()
{
	Children.Empty();

	if (PlanetImage)
	{
		AddSlot()
		[
			SNew(SImage).Image(PlanetImage)
		];
	}
}
<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc 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 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "../cpuid.h"
#include <cstdio>
#include <cstdlib>

using namespace Vc;

template<typename Vector> class DoCompares
{
    enum {
        Factor2 = 128
    };
    public:
        static void run()
        {
            const int Factor = CpuId::L1Data() / (sizeof(Vector) * 2); // half L1
            Vector *a = new Vector[Factor + 3];
#ifndef VC_BENCHMARK_NO_MLOCK
            mlock(a, (Factor + 3) * sizeof(Vector));
#endif
            for (int i = 0; i < Factor + 3; ++i) {
                a[i] = PseudoRandom<Vector>::next();
            }

#ifdef VC_IMPL_Scalar
            typedef bool M;
#else
            typedef typename Vector::Mask M;
#endif

            {
                Benchmark timer("operator==", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            const M &tmp0 = a[i + 0] == a[i + 1]; keepResults(tmp0);
                            const M &tmp1 = a[i + 0] == a[i + 2]; keepResults(tmp1);
                            const M &tmp2 = a[i + 0] == a[i + 3]; keepResults(tmp2);
                            const M &tmp3 = a[i + 1] == a[i + 2]; keepResults(tmp3);
                            const M &tmp4 = a[i + 1] == a[i + 3]; keepResults(tmp4);
                            const M &tmp5 = a[i + 2] == a[i + 3]; keepResults(tmp5);
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            {
                Benchmark timer("operator<", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            const M &tmp0 = a[i + 0] < a[i + 1]; keepResults(tmp0);
                            const M &tmp1 = a[i + 0] < a[i + 2]; keepResults(tmp1);
                            const M &tmp2 = a[i + 0] < a[i + 3]; keepResults(tmp2);
                            const M &tmp3 = a[i + 1] < a[i + 2]; keepResults(tmp3);
                            const M &tmp4 = a[i + 1] < a[i + 3]; keepResults(tmp4);
                            const M &tmp5 = a[i + 2] < a[i + 3]; keepResults(tmp5);
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            {
                Benchmark timer("(operator<).isFull()", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            if ((a[i + 0] < a[i + 1]).isFull()) asm volatile("");
                            if ((a[i + 0] < a[i + 2]).isFull()) asm volatile("");
                            if ((a[i + 0] < a[i + 3]).isFull()) asm volatile("");
                            if ((a[i + 1] < a[i + 2]).isFull()) asm volatile("");
                            if ((a[i + 1] < a[i + 3]).isFull()) asm volatile("");
                            if ((a[i + 2] < a[i + 3]).isFull()) asm volatile("");
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            {
                Benchmark timer("!(operator<).isEmpty()", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            if (!(a[i + 0] < a[i + 1]).isEmpty()) asm volatile("");
                            if (!(a[i + 0] < a[i + 2]).isEmpty()) asm volatile("");
                            if (!(a[i + 0] < a[i + 3]).isEmpty()) asm volatile("");
                            if (!(a[i + 1] < a[i + 2]).isEmpty()) asm volatile("");
                            if (!(a[i + 1] < a[i + 3]).isEmpty()) asm volatile("");
                            if (!(a[i + 2] < a[i + 3]).isEmpty()) asm volatile("");
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            delete[] a;
        }
};

int bmain()
{
    Benchmark::addColumn("datatype");

    Benchmark::setColumnData("datatype", "double_v");
    DoCompares<double_v>::run();
    Benchmark::setColumnData("datatype", "float_v");
    DoCompares<float_v>::run();
    Benchmark::setColumnData("datatype", "int_v");
    DoCompares<int_v>::run();
    Benchmark::setColumnData("datatype", "uint_v");
    DoCompares<uint_v>::run();
    Benchmark::setColumnData("datatype", "short_v");
    DoCompares<short_v>::run();
    Benchmark::setColumnData("datatype", "ushort_v");
    DoCompares<ushort_v>::run();
    Benchmark::setColumnData("datatype", "sfloat_v");
    DoCompares<sfloat_v>::run();

    return 0;
}
<commit_msg>remove unnecessary ifdef<commit_after>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc 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 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "../cpuid.h"
#include <cstdio>
#include <cstdlib>

using namespace Vc;

template<typename Vector> class DoCompares
{
    enum {
        Factor2 = 128
    };
    public:
        static void run()
        {
            const int Factor = CpuId::L1Data() / (sizeof(Vector) * 2); // half L1
            Vector *a = new Vector[Factor + 3];
#ifndef VC_BENCHMARK_NO_MLOCK
            mlock(a, (Factor + 3) * sizeof(Vector));
#endif
            for (int i = 0; i < Factor + 3; ++i) {
                a[i] = PseudoRandom<Vector>::next();
            }

            typedef typename Vector::Mask M;

            {
                Benchmark timer("operator==", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            const M &tmp0 = a[i + 0] == a[i + 1]; keepResults(tmp0);
                            const M &tmp1 = a[i + 0] == a[i + 2]; keepResults(tmp1);
                            const M &tmp2 = a[i + 0] == a[i + 3]; keepResults(tmp2);
                            const M &tmp3 = a[i + 1] == a[i + 2]; keepResults(tmp3);
                            const M &tmp4 = a[i + 1] == a[i + 3]; keepResults(tmp4);
                            const M &tmp5 = a[i + 2] == a[i + 3]; keepResults(tmp5);
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            {
                Benchmark timer("operator<", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            const M &tmp0 = a[i + 0] < a[i + 1]; keepResults(tmp0);
                            const M &tmp1 = a[i + 0] < a[i + 2]; keepResults(tmp1);
                            const M &tmp2 = a[i + 0] < a[i + 3]; keepResults(tmp2);
                            const M &tmp3 = a[i + 1] < a[i + 2]; keepResults(tmp3);
                            const M &tmp4 = a[i + 1] < a[i + 3]; keepResults(tmp4);
                            const M &tmp5 = a[i + 2] < a[i + 3]; keepResults(tmp5);
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            {
                Benchmark timer("(operator<).isFull()", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            if ((a[i + 0] < a[i + 1]).isFull()) asm volatile("");
                            if ((a[i + 0] < a[i + 2]).isFull()) asm volatile("");
                            if ((a[i + 0] < a[i + 3]).isFull()) asm volatile("");
                            if ((a[i + 1] < a[i + 2]).isFull()) asm volatile("");
                            if ((a[i + 1] < a[i + 3]).isFull()) asm volatile("");
                            if ((a[i + 2] < a[i + 3]).isFull()) asm volatile("");
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            {
                Benchmark timer("!(operator<).isEmpty()", Vector::Size * Factor * Factor2 * 6.0, "Op");
                while (timer.wantsMoreDataPoints()) {
                    timer.Start();
                    for (int j = 0; j < Factor2; ++j) {
                        for (int i = 0; i < Factor; ++i) {
                            if (!(a[i + 0] < a[i + 1]).isEmpty()) asm volatile("");
                            if (!(a[i + 0] < a[i + 2]).isEmpty()) asm volatile("");
                            if (!(a[i + 0] < a[i + 3]).isEmpty()) asm volatile("");
                            if (!(a[i + 1] < a[i + 2]).isEmpty()) asm volatile("");
                            if (!(a[i + 1] < a[i + 3]).isEmpty()) asm volatile("");
                            if (!(a[i + 2] < a[i + 3]).isEmpty()) asm volatile("");
                        }
                    }
                    timer.Stop();
                }
                timer.Print();
            }
            delete[] a;
        }
};

int bmain()
{
    Benchmark::addColumn("datatype");

    Benchmark::setColumnData("datatype", "double_v");
    DoCompares<double_v>::run();
    Benchmark::setColumnData("datatype", "float_v");
    DoCompares<float_v>::run();
    Benchmark::setColumnData("datatype", "int_v");
    DoCompares<int_v>::run();
    Benchmark::setColumnData("datatype", "uint_v");
    DoCompares<uint_v>::run();
    Benchmark::setColumnData("datatype", "short_v");
    DoCompares<short_v>::run();
    Benchmark::setColumnData("datatype", "ushort_v");
    DoCompares<ushort_v>::run();
    Benchmark::setColumnData("datatype", "sfloat_v");
    DoCompares<sfloat_v>::run();

    return 0;
}
<|endoftext|>