<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/lock_impl.h"

#include <errno.h>

#include "base/logging.h"

LockImpl::LockImpl() {
#ifndef NDEBUG
  // In debug, setup attributes for lock error checking.
  pthread_mutexattr_t mta;
  int rv = pthread_mutexattr_init(&mta);
  DCHECK(rv == 0);
  rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);
  DCHECK(rv == 0);
  rv = pthread_mutex_init(&os_lock_, &mta);
  DCHECK(rv == 0);
  rv = pthread_mutexattr_destroy(&mta);
  DCHECK(rv == 0);
#else
  // In release, go with the default lock attributes.
  pthread_mutex_init(&os_lock_, NULL);
#endif
}

LockImpl::~LockImpl() {
  int rv = pthread_mutex_destroy(&os_lock_);
  DCHECK(rv == 0);
}

bool LockImpl::Try() {
  int rv = pthread_mutex_trylock(&os_lock_);
  DCHECK(rv == 0 || rv == EBUSY);
  return rv == 0;
}

void LockImpl::Lock() {
  int rv = pthread_mutex_lock(&os_lock_);
  DCHECK(rv == 0);
}

void LockImpl::Unlock() {
  int rv = pthread_mutex_unlock(&os_lock_);
  DCHECK(rv == 0);
}
<commit_msg>Change DCHECK( == 0) to DCHECK_EQ in the posix lock implementation.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/lock_impl.h"

#include <errno.h>

#include "base/logging.h"

LockImpl::LockImpl() {
#ifndef NDEBUG
  // In debug, setup attributes for lock error checking.
  pthread_mutexattr_t mta;
  int rv = pthread_mutexattr_init(&mta);
  DCHECK_EQ(rv, 0);
  rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);
  DCHECK_EQ(rv, 0);
  rv = pthread_mutex_init(&os_lock_, &mta);
  DCHECK_EQ(rv, 0);
  rv = pthread_mutexattr_destroy(&mta);
  DCHECK_EQ(rv, 0);
#else
  // In release, go with the default lock attributes.
  pthread_mutex_init(&os_lock_, NULL);
#endif
}

LockImpl::~LockImpl() {
  int rv = pthread_mutex_destroy(&os_lock_);
  DCHECK_EQ(rv, 0);
}

bool LockImpl::Try() {
  int rv = pthread_mutex_trylock(&os_lock_);
  DCHECK(rv == 0 || rv == EBUSY);
  return rv == 0;
}

void LockImpl::Lock() {
  int rv = pthread_mutex_lock(&os_lock_);
  DCHECK_EQ(rv, 0);
}

void LockImpl::Unlock() {
  int rv = pthread_mutex_unlock(&os_lock_);
  DCHECK_EQ(rv, 0);
}
<|endoftext|>


<commit_before>#include "condor_common.h"
#include "condor_classad.h"

BEGIN_NAMESPACE( classad )

ClassAd* getOldClassAd( Sock& sock )
{
	ClassAd *ad = new ClassAd( );
	if( !ad ) {
		return (ClassAd*) 0;
	}
	if( !getOldClassAd( sock, *ad ) ) {
		delete ad;
		return NULL;
	}
	return ad;
}

bool getOldClassAd( Sock& sock, ClassAd& ad )
{
	Source 	src;
	int 	numExprs;
	char 	*eq;
	ExprTree *expr;
	static  char *buffer = new char[ 10240 ];

	sock.decode( );
	if( !sock.code( numExprs ) ) {
		return false;
	}

	for( int i = 0 ; i < numExprs ; i++ ) {
			// get the expression and find the '=' in the expr
		if( !sock.code( buffer ) || !( eq = strchr( buffer, '=' ) ) ) {
			return false;
		}
			// split the expression at the '='
		*eq = '\0';

			// set the source to the part after the '='
		src.SetSource( eq+1 );

			// parse the expression and insert it into the classad
		if( !src.ParseExpression( expr ) || !ad.Insert( buffer, expr ) ) {
			return false;
		}
	}

	return true;
}

void printClassAdExpr( ExprTree *tree )
{
	static Sink				sink;
	static FormatOptions	fo;

	sink.SetSink( stdout );
	fo.SetClassAdIndentation( );
	fo.SetListIndentation( );
	sink.SetFormatOptions( &fo );
	tree->ToSink( sink );
	sink.FlushSink( );
}

void printClassAdValue( Value &val )
{
	static Sink				sink;
	static FormatOptions	fo;

	sink.SetSink( stdout );
	fo.SetClassAdIndentation( );
	fo.SetListIndentation( );
	sink.SetFormatOptions( &fo );
	val.ToSink( sink );
	sink.FlushSink( );
}

END_NAMESPACE // classad
<commit_msg>Added methods to send and receive old classads<commit_after>#include "condor_common.h"
#include "condor_classad.h"

BEGIN_NAMESPACE( classad )

ClassAd* getOldClassAd( Sock& sock )
{
	ClassAd *ad = new ClassAd( );
	if( !ad ) {
		return (ClassAd*) 0;
	}
	if( !getOldClassAd( sock, *ad ) ) {
		delete ad;
		return NULL;
	}
	return ad;
}

bool getOldClassAd( Sock& sock, ClassAd& ad )
{
	Source 	src;
	int 	numExprs;
	char 	*eq;
	ExprTree *expr;
	static  char *buffer = new char[ 10240 ];

	sock.decode( );
	if( !sock.code( numExprs ) ) {
		return false;
	}

	for( int i = 0 ; i < numExprs ; i++ ) {
			// get the expression and find the '=' in the expr
		if( !sock.code( buffer ) || !( eq = strchr( buffer, '=' ) ) ) {
			return false;
		}
			// split the expression at the '='
		*eq = '\0';

			// set the source to the part after the '='
		src.SetSource( eq+1 );

			// parse the expression and insert it into the classad
		if( !src.ParseExpression( expr ) || !ad.Insert( buffer, expr ) ) {
			return false;
		}
	}

	// Get my type and target type
	if (!sock.code(buffer) || !ad.Insert("MyType",buffer)) return false;
	if (!sock.code(buffer) || !ad.Insert("TargetType",buffer)) return false;

	return true;
}

bool putOldClassAd ( Sock& sock, ClassAd& ad )
{
	char* attr;
	ExprTree* expr;

	char buffer[10240];
	char tmp[10240];
	char* tmpPtr=tmp;

	int numExprs=0;
	ClassAdIterator itor(ad);
	while (itor.NextAttribute(attr, expr)) {
		if (strcmp(attr,"MyType")==0 || strcmp(attr,"TargetType")==0) continue;
		numExprs++;
	}

	sock.encode( );
//printf("Sending: %d\n",numExprs);
	if( !sock.code( numExprs ) ) {
		return false;
	}

	itor.ToBeforeFirst();
	while (itor.NextAttribute(attr, expr)) {
		if (strcmp(attr,"MyType")==0 || strcmp(attr,"TargetType")==0) continue;
		memset(buffer,0,sizeof(buffer));
		Sink s;
		s.SetSink(buffer,sizeof(buffer));
		expr->ToSink(s);
		sprintf(tmp,"%s = %s",attr,buffer);
//printf("Sending: %s\n",tmpPtr);
		if (!sock.code(tmpPtr)) {
			return false;
		}
	}

	// Send the type
	char* type=NULL;
	if (!ad.EvaluateAttrString("MyType",type)) type="(unknown type)";
//printf("Sending: %s\n",type);
	if (!sock.code(type)) {
		return false;
	}

	char* target_type=NULL;
	if (!ad.EvaluateAttrString("TargetType",target_type)) target_type="(unknown type)";
//printf("Sending: %s\n",target_type);
	if (!sock.code(target_type)) {
		return false;
	}

	return true;
}

void printClassAdExpr( ExprTree *tree )
{
	static Sink				sink;
	static FormatOptions	fo;

	sink.SetSink( stdout );
	fo.SetClassAdIndentation( );
	fo.SetListIndentation( );
	sink.SetFormatOptions( &fo );
	tree->ToSink( sink );
	sink.FlushSink( );
}

void printClassAdValue( Value &val )
{
	static Sink				sink;
	static FormatOptions	fo;

	sink.SetSink( stdout );
	fo.SetClassAdIndentation( );
	fo.SetListIndentation( );
	sink.SetFormatOptions( &fo );
	val.ToSink( sink );
	sink.FlushSink( );
}

END_NAMESPACE // classad
<|endoftext|>


<commit_before>#pragma once

#include "node.hpp"
#include "random.hpp"
#include "settings.hpp"
#include "data.hpp"
#include "MeanShift.hpp"

#include <vector>
#include <cstdint>
#include <ctime>

#include <unordered_map>

namespace ISUE {
  namespace RelocForests {
    class Point3D {
    public:
      Point3D(double x, double y, double z) : x(x), y(y), z(z) {};
      double x, y, z;
    };

    struct hashFunc{
      size_t operator()(const Point3D &k) const {
        size_t h1 = std::hash<double>()(k.x);
        size_t h2 = std::hash<double>()(k.y);
        size_t h3 = std::hash<double>()(k.z);
        return (h1 ^ (h2 << 1)) ^ h3;
      }
    };

    struct equalsFunc {
      bool operator()(const Point3D &l, const Point3D &r) const{
        return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);
      }
    };

    typedef std::unordered_map<Point3D, uint32_t, hashFunc, equalsFunc> Point3DMap;

    class Tree {
    public:
      Tree()
      {
        root_ = new Node();
      };

      ~Tree()
      {
        delete root_;
      };

      void Serialize(std::ostream& stream) const
      {
        const int majorVersion = 0, minorVersion = 0;

        stream.write(binaryFileHeader_, strlen(binaryFileHeader_));
        stream.write((const char*)(&majorVersion), sizeof(majorVersion));
        stream.write((const char*)(&minorVersion), sizeof(minorVersion));

        stream.write((const char*)(&settings_->max_tree_depth_), sizeof(settings_->max_tree_depth_));

        stream.write((const char*)(this), sizeof(this));
      }

      // learner output
      enum DECISION { LEFT, RIGHT, TRASH };

      //  Evaluates weak learner. Decides whether the point should go left or right.
      //  Returns DECISION enum value.
      DECISION eval_learner(Data *data, LabeledPixel pixel, DepthAdaptiveRGB *feature)
      {
        bool valid = true;
        float response = feature->GetResponse(data->GetDepthImage(pixel.frame_), data->GetRGBImage(pixel.frame_), pixel.pos_, valid);

        if (!valid) // no depth or out of bounds
          return DECISION::TRASH;

        return (DECISION)(response >= feature->GetThreshold());
      }

      // V(S)
      double variance(std::vector<LabeledPixel> labeled_data)
      {
        if (labeled_data.size() == 0)
          return 0.0;
        double V = (1.0f / (double)labeled_data.size());
        double sum = 0.0f;

        // calculate mean of S
        cv::Point3f tmp;
        for (auto p : labeled_data)
          tmp += p.label_;
        uint32_t size = labeled_data.size();
        cv::Point3f mean(tmp.x / size, tmp.y / size, tmp.z / size);

        for (auto p : labeled_data) {
          cv::Point3f val = (p.label_ - mean);
          sum += val.x * val.x  + val.y * val.y + val.z * val.z;
        }

        return V * sum;
      }

      // Q(S_n, \theta)
      double objective_function(std::vector<LabeledPixel> data, std::vector<LabeledPixel> left, std::vector<LabeledPixel> right)
      {
        double var = variance(data);
        double left_val = ((double)left.size() / (double)data.size()) * variance(left);
        double right_val = ((double)right.size() / (double)data.size()) * variance(right);

        return var - (left_val + right_val);
      }

      // Returns height from current node to root node.
      uint32_t traverse_to_root(Node *node) {
        if (node == nullptr)
          return 0;
        return 1 + traverse_to_root(node->parent_);
      }

      void train_recurse(Node *node, std::vector<LabeledPixel> S)
      {
        uint16_t height = traverse_to_root(node);
        if (S.size() == 1 || height >= settings_->max_tree_depth_) {

          std::vector<Eigen::Vector3d> data;

          // calc mode for leaf, sub-sample N_SS = 500
          for (uint16_t i = 0; i < (S.size() < 500 ? S.size() : 500); i++) {
            auto p = S.at(i);
            Eigen::Vector3d point { p.label_.x, p.label_.y, p.label_.z };
            data.push_back(point);
          }

          // cluster
          MeanShift *ms = new MeanShift(nullptr);
          double kernel_bandwidth = 0.01f; // gaussian
          std::vector<Eigen::Vector3d> cluster = ms->cluster(data, kernel_bandwidth);

          // find mode
          std::vector<Point3D> clustered_points;
          for (auto c : cluster)
            clustered_points.push_back(Point3D(floor(c[0] * 10000) / 10000, floor(c[1] * 10000) / 10000, floor(c[2] * 10000) / 10000));

          Point3DMap cluster_map;

          for (auto p : clustered_points)
            cluster_map[p]++;

          std::vector<cv::Point3d> modes;
          for (auto p : cluster_map)
            modes.push_back(cv::Point3d(p.first.x, p.first.y, p.first.z));

          node->modes_ = modes;
          node->is_leaf_ = true;
          return;
        }
        else if (S.size() == 0) {
          delete node;
          node = nullptr;
          return;
        }

        node->is_split_ = true;
        node->is_leaf_ = false;

        uint32_t num_candidates = 5,
                feature = 0;
        double minimum_objective = DBL_MAX;

        std::vector<DepthAdaptiveRGB*> candidate_params;
        std::vector<LabeledPixel> left_final, right_final;

        for (uint32_t i = 0; i < num_candidates; ++i) {

          // add candidate
          candidate_params.push_back(DepthAdaptiveRGB::CreateRandom(random_));

          // partition data with candidate
          std::vector<LabeledPixel> left_data, right_data;

          for (uint32_t j = 0; j < S.size(); ++j) {
            // todo throw away undefined vals

            DECISION val = eval_learner(data_, S.at(j), candidate_params.at(i));

            switch (val) {
            case LEFT:
              left_data.push_back(S.at(j));
              break;
            case RIGHT:
              right_data.push_back(S.at(j));
              break;
            case TRASH:
              // do nothing
              break;
            }

          }

          // eval tree training objective function and take best
          // todo: ensure objective function is correct
          double objective = objective_function(S, left_data, right_data);

          if (objective < minimum_objective) {
            feature = i;
            minimum_objective= objective;
            left_final = left_data;
            right_final = right_data;
          }
        }

        // set feature
        node->feature_ = candidate_params.at(feature);
        node->left_ = new Node();
        node->right_ = new Node();
        node->left_->parent_ = node->right_->parent_ = node;

        train_recurse(node->left_, left_final);
        train_recurse(node->right_, right_final);
      }

      void Train(Data *data, std::vector<LabeledPixel> labeled_data, Random *random, Settings *settings)
      {
        data_ = data;
        random_ = random;
        settings_ = settings;
        train_recurse(root_, labeled_data);
      }

      std::vector<cv::Point3d> eval_recursive(Node *node, int row, int col, cv::Mat rgb_image, cv::Mat depth_image)
      {

        if (node->is_leaf_) {
          return node->modes_;
        }

        bool valid = true;

        float response = node->feature_->GetResponse(depth_image, rgb_image, cv::Point2i(col, row), valid);

        DECISION val = (DECISION)(response >= node->feature_->GetThreshold());

        switch (val) {
        case LEFT:
          eval_recursive(node->left_, row, col, rgb_image, depth_image);
          break;
        case RIGHT:
          eval_recursive(node->right_, row, col, rgb_image, depth_image);
          break;
        case TRASH:
          // do nothing
          break;
        }
      }

      // Evaluate tree at a pixel
      std::vector<cv::Point3d> Eval(int row, int col, cv::Mat rgb_image, cv::Mat depth_image)
      {
        return eval_recursive(root_, row, col, rgb_image, depth_image);
      }

    private:
      Node *root_;
      Data *data_;
      Random *random_;
      Settings *settings_;
      const char* binaryFileHeader_ = "ISUE.RelocForests.Tree";
    };
  }
}
<commit_msg>Use eval_learner for training and testing.<commit_after>#pragma once

#include "node.hpp"
#include "random.hpp"
#include "settings.hpp"
#include "data.hpp"
#include "MeanShift.hpp"

#include <vector>
#include <cstdint>
#include <ctime>

#include <unordered_map>

namespace ISUE {
  namespace RelocForests {
    class Point3D {
    public:
      Point3D(double x, double y, double z) : x(x), y(y), z(z) {};
      double x, y, z;
    };

    struct hashFunc{
      size_t operator()(const Point3D &k) const {
        size_t h1 = std::hash<double>()(k.x);
        size_t h2 = std::hash<double>()(k.y);
        size_t h3 = std::hash<double>()(k.z);
        return (h1 ^ (h2 << 1)) ^ h3;
      }
    };

    struct equalsFunc {
      bool operator()(const Point3D &l, const Point3D &r) const{
        return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);
      }
    };

    typedef std::unordered_map<Point3D, uint32_t, hashFunc, equalsFunc> Point3DMap;

    class Tree {
    public:
      Tree()
      {
        root_ = new Node();
      };

      ~Tree()
      {
        delete root_;
      };

      void Serialize(std::ostream& stream) const
      {
        const int majorVersion = 0, minorVersion = 0;

        stream.write(binaryFileHeader_, strlen(binaryFileHeader_));
        stream.write((const char*)(&majorVersion), sizeof(majorVersion));
        stream.write((const char*)(&minorVersion), sizeof(minorVersion));

        stream.write((const char*)(&settings_->max_tree_depth_), sizeof(settings_->max_tree_depth_));

        stream.write((const char*)(this), sizeof(this));
      }

      // learner output
      enum DECISION { LEFT, RIGHT, TRASH };

      //  Evaluates weak learner. Decides whether the point should go left or right.
      //  Returns DECISION enum value.
      //DECISION eval_learner(Data *data, LabeledPixel pixel, DepthAdaptiveRGB *feature)
      DECISION eval_learner(DepthAdaptiveRGB *feature, cv::Mat depth_image, cv::Mat rgb_image, cv::Point2i pos)
      {
        bool valid = true;
        float response = feature->GetResponse(depth_image, rgb_image, pos, valid);

        if (!valid) // no depth or out of bounds
          return DECISION::TRASH;

        return (DECISION)(response >= feature->GetThreshold());
      }

      // V(S)
      double variance(std::vector<LabeledPixel> labeled_data)
      {
        if (labeled_data.size() == 0)
          return 0.0;
        double V = (1.0f / (double)labeled_data.size());
        double sum = 0.0f;

        // calculate mean of S
        cv::Point3f tmp;
        for (auto p : labeled_data)
          tmp += p.label_;
        uint32_t size = labeled_data.size();
        cv::Point3f mean(tmp.x / size, tmp.y / size, tmp.z / size);

        for (auto p : labeled_data) {
          cv::Point3f val = (p.label_ - mean);
          sum += val.x * val.x  + val.y * val.y + val.z * val.z;
        }

        return V * sum;
      }

      // Q(S_n, \theta)
      double objective_function(std::vector<LabeledPixel> data, std::vector<LabeledPixel> left, std::vector<LabeledPixel> right)
      {
        double var = variance(data);
        double left_val = ((double)left.size() / (double)data.size()) * variance(left);
        double right_val = ((double)right.size() / (double)data.size()) * variance(right);

        return var - (left_val + right_val);
      }

      // Returns height from current node to root node.
      uint32_t traverse_to_root(Node *node) {
        if (node == nullptr)
          return 0;
        return 1 + traverse_to_root(node->parent_);
      }

      void train_recurse(Node *node, std::vector<LabeledPixel> S)
      {
        uint16_t height = traverse_to_root(node);
        if (S.size() == 1 || height >= settings_->max_tree_depth_) {

          std::vector<Eigen::Vector3d> data;

          // calc mode for leaf, sub-sample N_SS = 500
          for (uint16_t i = 0; i < (S.size() < 500 ? S.size() : 500); i++) {
            auto p = S.at(i);
            Eigen::Vector3d point { p.label_.x, p.label_.y, p.label_.z };
            data.push_back(point);
          }

          // cluster
          MeanShift *ms = new MeanShift(nullptr);
          double kernel_bandwidth = 0.01f; // gaussian
          std::vector<Eigen::Vector3d> cluster = ms->cluster(data, kernel_bandwidth);

          // find mode
          std::vector<Point3D> clustered_points;
          for (auto c : cluster)
            clustered_points.push_back(Point3D(floor(c[0] * 10000) / 10000, floor(c[1] * 10000) / 10000, floor(c[2] * 10000) / 10000));

          Point3DMap cluster_map;

          for (auto p : clustered_points)
            cluster_map[p]++;

          std::vector<cv::Point3d> modes;
          for (auto p : cluster_map)
            modes.push_back(cv::Point3d(p.first.x, p.first.y, p.first.z));

          node->modes_ = modes;
          node->is_leaf_ = true;
          return;
        }
        else if (S.size() == 0) {
          delete node;
          node = nullptr;
          return;
        }

        node->is_split_ = true;
        node->is_leaf_ = false;

        uint32_t num_candidates = 5,
                feature = 0;
        double minimum_objective = DBL_MAX;

        std::vector<DepthAdaptiveRGB*> candidate_params;
        std::vector<LabeledPixel> left_final, right_final;

        for (uint32_t i = 0; i < num_candidates; ++i) {

          // add candidate
          candidate_params.push_back(DepthAdaptiveRGB::CreateRandom(random_));

          // partition data with candidate
          std::vector<LabeledPixel> left_data, right_data;

          for (uint32_t j = 0; j < S.size(); ++j) {

            //DECISION val = eval_learner(data_, S.at(j), candidate_params.at(i));
            LabeledPixel p = S.at(j);
            DECISION val = eval_learner(candidate_params.at(i), data_->GetDepthImage(p.frame_), data_->GetRGBImage(p.frame_), p.pos_);

            switch (val) {
            case LEFT:
              left_data.push_back(S.at(j));
              break;
            case RIGHT:
              right_data.push_back(S.at(j));
              break;
            case TRASH:
              // do nothing
              break;
            }

          }

          // eval tree training objective function and take best
          // todo: ensure objective function is correct
          double objective = objective_function(S, left_data, right_data);

          if (objective < minimum_objective) {
            feature = i;
            minimum_objective= objective;
            left_final = left_data;
            right_final = right_data;
          }
        }

        // set feature
        node->feature_ = candidate_params.at(feature);
        node->left_ = new Node();
        node->right_ = new Node();
        node->left_->parent_ = node->right_->parent_ = node;

        train_recurse(node->left_, left_final);
        train_recurse(node->right_, right_final);
      }

      void Train(Data *data, std::vector<LabeledPixel> labeled_data, Random *random, Settings *settings)
      {
        data_ = data;
        random_ = random;
        settings_ = settings;
        train_recurse(root_, labeled_data);
      }

      std::vector<cv::Point3d> eval_recursive(Node *node, int row, int col, cv::Mat rgb_image, cv::Mat depth_image)
      {

        if (node->is_leaf_) {
          return node->modes_;
        }

        DECISION val = eval_learner(node->feature_, depth_image, rgb_image, cv::Point2i(col, row));

        switch (val) {
        case LEFT:
          eval_recursive(node->left_, row, col, rgb_image, depth_image);
          break;
        case RIGHT:
          eval_recursive(node->right_, row, col, rgb_image, depth_image);
          break;
        case TRASH:
          break;
        }
      }

      // Evaluate tree at a pixel
      std::vector<cv::Point3d> Eval(int row, int col, cv::Mat rgb_image, cv::Mat depth_image)
      {
        return eval_recursive(root_, row, col, rgb_image, depth_image);
      }

    private:
      Node *root_;
      Data *data_;
      Random *random_;
      Settings *settings_;
      const char* binaryFileHeader_ = "ISUE.RelocForests.Tree";
    };
  }
}
<|endoftext|>


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

// open space includes
#include <openspace/util/ImageSequencer2.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/filesystem/directory.h>
#include <openspace/util/time.h>
#include <ghoul/filesystem/cachemanager.h>

#include <openspace/util/spicemanager.h>
#include <fstream>
#include <iterator>
#include <iomanip>
#include <limits>

namespace {
const std::string _loggerCat = "ImageSequencer2";
}

namespace openspace {

ImageSequencer2* ImageSequencer2::_instance = nullptr;

ImageSequencer2::ImageSequencer2() :
_hasData(false),
_defaultCaptureImage(absPath("C:/Users/michal/openspace/openspace-data/scene/common/textures/placeholder_blank.png"))
{}

ImageSequencer2& ImageSequencer2::ref() {
	assert(_instance != nullptr);
	return *_instance;
}
void ImageSequencer2::initialize() {
	assert(_instance == nullptr);
	_instance = new ImageSequencer2;
}

void ImageSequencer2::deinitialize() {
	delete _instance;
	_instance = nullptr;
}

bool ImageSequencer2::isReady(){
	return _hasData;
}

bool ImageSequencer2::imageComparer(const Image &a, const Image &b){
	return a.startTime < b.startTime;
};

std::vector<Image>::iterator ImageSequencer2::binary_find(std::vector<Image>::iterator begin,
	std::vector<Image>::iterator end,
	const Image &val,
	bool(*compareFunc)(const Image &a, const Image &b)){
	// Finds the lower bound in at most log(last - first) + 1 comparisons
	std::vector<Image>::iterator it = std::lower_bound(begin, end, val, compareFunc);
	if (it != begin && it != end){
		return it;
	}
	return end;
}

void ImageSequencer2::updateSequencer(double time){
	if (_currentTime != time){
		_previousTime = _currentTime;
		_currentTime = time;
	}
}

std::pair<double, std::string> ImageSequencer2::getNextTarget(){
	// make into template func
	auto compareTime = [](const std::pair<double, std::string> &a,
	                 	  const std::pair<double, std::string> &b)->bool{
		return a.first < b.first;
	};
	std::pair<double, std::string> findEqualToThis;
	findEqualToThis.first = _currentTime;
	auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);

	if (it != _targetTimes.end()){
		return (*it);
	}
}

std::pair<double, std::string> ImageSequencer2::getCurrentTarget(){
	// make into template func
	auto compareTime = [](const std::pair<double, std::string> &a,
		const std::pair<double, std::string> &b)->bool{
		return a.first < b.first;
	};
	std::pair<double, std::string> findEqualToThis;
	findEqualToThis.first = _currentTime;
	auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);

	if (it != _targetTimes.end()){
		return *std::prev(it);
	}
}

std::pair<double, std::vector<std::string>> ImageSequencer2::getIncidentTargetList(int range){
	std::pair<double, std::vector<std::string>> incidentTargets;

	auto compareTime = [](const std::pair<double, std::string> &a,
		const std::pair<double, std::string> &b)->bool{
		return a.first < b.first;
	};
	std::pair<double, std::string> findEqualToThis;
	findEqualToThis.first = _currentTime;
	auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);

	std::advance(it, -(range+1));

	for (int i = 0; i < 2*range+1; i++){
		incidentTargets.first = it->first;
		incidentTargets.second.push_back(it->second);
		it++;
		if (it == _targetTimes.end())
			break;
	}

	return incidentTargets;
}

double ImageSequencer2::getIntervalLength(){
	double upcoming = getNextCaptureTime();
	if (_nextCapture != upcoming){
		_nextCapture = upcoming;
		_intervalLength = upcoming - _currentTime;
	}
	return _intervalLength;
}

double ImageSequencer2::getNextCaptureTime(){
	auto compareTime = [](const double &a, const double &b)->bool{
		return a < b;
	};
	double nextCaptureTime = 0;
	auto it = std::lower_bound(_captureProgression.begin(), _captureProgression.end(), _currentTime, compareTime);
	if (it != _captureProgression.end())
		nextCaptureTime = *it;

	return nextCaptureTime;
}

std::vector<std::pair<std::string, bool>> ImageSequencer2::getActiveInstruments(){
	for (int i = 0; i < _instrumentOnOff.size(); i++){
		_instrumentOnOff[i].second = false;
	}
	for (auto key : _fileTranslation){
		for (auto instrumentID : key.second->getTranslation()){
				if (instumentActive(instrumentID)){
					for (int i = 0; i < _instrumentOnOff.size(); i++){
						if (instrumentID == _instrumentOnOff[i].first){
							_instrumentOnOff[i].second = true;
						}
					}
				}
			}
		}
	return _instrumentOnOff;
}
bool ImageSequencer2::instumentActive(std::string instrumentID){
	for (auto i : _instrumentTimes){
		//check if this instrument is in range
		if (i.second.inRange(_currentTime)){
			//if so, then get the corresponding spiceIDs
			std::vector < std::string> spiceIDs = _fileTranslation[i.first]->getTranslation();
			//check which specific subinstrument is firing
			for (auto s : spiceIDs){
				if (s == instrumentID){
					return true;
				}
			}
		}
	}
	return false;
}
bool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures,  std::string projectee, std::string instrumentID){
	if (!instumentActive(instrumentID) && !Time::ref().timeJumped()) return false;
	return (instrumentID == "NH_LORRI") ? getImagePaths(captures, projectee) : false;
}

bool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures,
	                                std::string projectee){
	if (_subsetMap[projectee]._range.inRange(_currentTime) ||
		_subsetMap[projectee]._range.inRange(_previousTime)){
		auto compareTime = [](const Image &a,
			const Image &b)->bool{
			return a.startTime < b.startTime;
		};

		auto begin = _subsetMap[projectee]._subset.begin();
		auto end = _subsetMap[projectee]._subset.end();

		std::vector<std::pair<double, std::string>> captureTimes;
		Image findPrevious;
		findPrevious.startTime = _previousTime;
		Image findCurrent;
		findCurrent.startTime = _currentTime;

		auto curr = std::lower_bound(begin, end, findCurrent, compareTime);
		auto prev = std::lower_bound(begin, end, findPrevious, compareTime);

		if (curr != begin && curr != end  && prev != begin && prev != end){
			std::transform(prev, curr, std::back_inserter(captureTimes),
				[](const Image& i) {
				return std::make_pair(i.startTime, i.path);
			});
			std::reverse(captureTimes.begin(), captureTimes.end());
			captures = captureTimes;
			return true;
		}
	}
	return false;
}

void ImageSequencer2::runSequenceParser(SequenceParser* parser){
	parser->create();
	_fileTranslation    = parser->getTranslation(); // should perhaps be named 'instrumentTranslation'
	_subsetMap          = parser->getSubsetMap();
	_instrumentTimes    = parser->getIstrumentTimes();
	_targetTimes        = parser->getTargetTimes();
	_captureProgression = parser->getCaptureProgression();

	//copy payload from _fileTranslation
	for (auto t : _fileTranslation){
		std::vector<std::string> spiceIDs = t.second->getTranslation();
		for (auto id : spiceIDs){
			_instrumentOnOff.push_back(std::make_pair(id, false));
		}
	}
	_instrumentOnOff.erase(std::unique(_instrumentOnOff.begin(),
									   _instrumentOnOff.end()),
									   _instrumentOnOff.end());
	_hasData = true;

}
}  // namespace openspace
<commit_msg>Changed from absolute path into relative using ${OPENSPACE_DATA}<commit_after>/*****************************************************************************************
*                                                                                *
* OpenSpace                                                                             *
*                                                                                *
* Copyright (c) 2014                                                                    *
*                                                                                *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify,    *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
* permit persons to whom the Software is furnished to do so, subject to the following   *
* conditions:                                                                           *
*                                                                                *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software.                                              *
*                                                                                *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
****************************************************************************************/

// open space includes
#include <openspace/util/ImageSequencer2.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/filesystem/directory.h>
#include <openspace/util/time.h>
#include <ghoul/filesystem/cachemanager.h>

#include <openspace/util/spicemanager.h>
#include <fstream>
#include <iterator>
#include <iomanip>
#include <limits>

namespace {
const std::string _loggerCat = "ImageSequencer2";
}

namespace openspace {

ImageSequencer2* ImageSequencer2::_instance = nullptr;

ImageSequencer2::ImageSequencer2() :
_hasData(false),
_defaultCaptureImage(absPath("${OPENSPACE_DATA}/scene/common/textures/placeholder_blank.png"))
{}

ImageSequencer2& ImageSequencer2::ref() {
	assert(_instance != nullptr);
	return *_instance;
}
void ImageSequencer2::initialize() {
	assert(_instance == nullptr);
	_instance = new ImageSequencer2;
}

void ImageSequencer2::deinitialize() {
	delete _instance;
	_instance = nullptr;
}

bool ImageSequencer2::isReady(){
	return _hasData;
}

bool ImageSequencer2::imageComparer(const Image &a, const Image &b){
	return a.startTime < b.startTime;
};

std::vector<Image>::iterator ImageSequencer2::binary_find(std::vector<Image>::iterator begin,
	std::vector<Image>::iterator end,
	const Image &val,
	bool(*compareFunc)(const Image &a, const Image &b)){
	// Finds the lower bound in at most log(last - first) + 1 comparisons
	std::vector<Image>::iterator it = std::lower_bound(begin, end, val, compareFunc);
	if (it != begin && it != end){
		return it;
	}
	return end;
}

void ImageSequencer2::updateSequencer(double time){
	if (_currentTime != time){
		_previousTime = _currentTime;
		_currentTime = time;
	}
}

std::pair<double, std::string> ImageSequencer2::getNextTarget(){
	// make into template func
	auto compareTime = [](const std::pair<double, std::string> &a,
	                 	  const std::pair<double, std::string> &b)->bool{
		return a.first < b.first;
	};
	std::pair<double, std::string> findEqualToThis;
	findEqualToThis.first = _currentTime;
	auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);

	if (it != _targetTimes.end()){
		return (*it);
	}
}

std::pair<double, std::string> ImageSequencer2::getCurrentTarget(){
	// make into template func
	auto compareTime = [](const std::pair<double, std::string> &a,
		const std::pair<double, std::string> &b)->bool{
		return a.first < b.first;
	};
	std::pair<double, std::string> findEqualToThis;
	findEqualToThis.first = _currentTime;
	auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);

	if (it != _targetTimes.end()){
		return *std::prev(it);
	}
}

std::pair<double, std::vector<std::string>> ImageSequencer2::getIncidentTargetList(int range){
	std::pair<double, std::vector<std::string>> incidentTargets;

	auto compareTime = [](const std::pair<double, std::string> &a,
		const std::pair<double, std::string> &b)->bool{
		return a.first < b.first;
	};
	std::pair<double, std::string> findEqualToThis;
	findEqualToThis.first = _currentTime;
	auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);

	std::advance(it, -(range+1));

	for (int i = 0; i < 2*range+1; i++){
		incidentTargets.first = it->first;
		incidentTargets.second.push_back(it->second);
		it++;
		if (it == _targetTimes.end())
			break;
	}

	return incidentTargets;
}

double ImageSequencer2::getIntervalLength(){
	double upcoming = getNextCaptureTime();
	if (_nextCapture != upcoming){
		_nextCapture = upcoming;
		_intervalLength = upcoming - _currentTime;
	}
	return _intervalLength;
}

double ImageSequencer2::getNextCaptureTime(){
	auto compareTime = [](const double &a, const double &b)->bool{
		return a < b;
	};
	double nextCaptureTime = 0;
	auto it = std::lower_bound(_captureProgression.begin(), _captureProgression.end(), _currentTime, compareTime);
	if (it != _captureProgression.end())
		nextCaptureTime = *it;

	return nextCaptureTime;
}

std::vector<std::pair<std::string, bool>> ImageSequencer2::getActiveInstruments(){
	for (int i = 0; i < _instrumentOnOff.size(); i++){
		_instrumentOnOff[i].second = false;
	}
	for (auto key : _fileTranslation){
		for (auto instrumentID : key.second->getTranslation()){
				if (instumentActive(instrumentID)){
					for (int i = 0; i < _instrumentOnOff.size(); i++){
						if (instrumentID == _instrumentOnOff[i].first){
							_instrumentOnOff[i].second = true;
						}
					}
				}
			}
		}
	return _instrumentOnOff;
}
bool ImageSequencer2::instumentActive(std::string instrumentID){
	for (auto i : _instrumentTimes){
		//check if this instrument is in range
		if (i.second.inRange(_currentTime)){
			//if so, then get the corresponding spiceIDs
			std::vector < std::string> spiceIDs = _fileTranslation[i.first]->getTranslation();
			//check which specific subinstrument is firing
			for (auto s : spiceIDs){
				if (s == instrumentID){
					return true;
				}
			}
		}
	}
	return false;
}
bool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures,  std::string projectee, std::string instrumentID){
	if (!instumentActive(instrumentID) && !Time::ref().timeJumped()) return false;
	return (instrumentID == "NH_LORRI") ? getImagePaths(captures, projectee) : false;
}

bool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures,
	                                std::string projectee){
	if (_subsetMap[projectee]._range.inRange(_currentTime) ||
		_subsetMap[projectee]._range.inRange(_previousTime)){
		auto compareTime = [](const Image &a,
			const Image &b)->bool{
			return a.startTime < b.startTime;
		};

		auto begin = _subsetMap[projectee]._subset.begin();
		auto end = _subsetMap[projectee]._subset.end();

		std::vector<std::pair<double, std::string>> captureTimes;
		Image findPrevious;
		findPrevious.startTime = _previousTime;
		Image findCurrent;
		findCurrent.startTime = _currentTime;

		auto curr = std::lower_bound(begin, end, findCurrent, compareTime);
		auto prev = std::lower_bound(begin, end, findPrevious, compareTime);

		if (curr != begin && curr != end  && prev != begin && prev != end){
			std::transform(prev, curr, std::back_inserter(captureTimes),
				[](const Image& i) {
				return std::make_pair(i.startTime, i.path);
			});
			std::reverse(captureTimes.begin(), captureTimes.end());
			captures = captureTimes;
			return true;
		}
	}
	return false;
}

void ImageSequencer2::runSequenceParser(SequenceParser* parser){
	parser->create();
	_fileTranslation    = parser->getTranslation(); // should perhaps be named 'instrumentTranslation'
	_subsetMap          = parser->getSubsetMap();
	_instrumentTimes    = parser->getIstrumentTimes();
	_targetTimes        = parser->getTargetTimes();
	_captureProgression = parser->getCaptureProgression();

	//copy payload from _fileTranslation
	for (auto t : _fileTranslation){
		std::vector<std::string> spiceIDs = t.second->getTranslation();
		for (auto id : spiceIDs){
			_instrumentOnOff.push_back(std::make_pair(id, false));
		}
	}
	_instrumentOnOff.erase(std::unique(_instrumentOnOff.begin(),
									   _instrumentOnOff.end()),
									   _instrumentOnOff.end());
	_hasData = true;

}
}  // namespace openspace
<|endoftext|>


<commit_before>/*
 *
 */
#include <stdio.h>
#include "sync.h"
#include "topo.h"
#include "mp.h"
#include "measurement_framework.h"
#include <pthread.h>
#include <unistd.h>
#include <vector>

#include "model_defs.h"
#include "barrier.h"

#ifdef PARLIB
#include "mcs.h"
#endif

//#define SEND7

#ifdef BARRELFISH
#include <barrelfish/barrelfish.h>
#include <posixcompat.h>
#endif

__thread struct sk_measurement m;
__thread struct sk_measurement m2;

unsigned num_threads;
#define NUM_RUNS 100000 //50 // 10000 // Tested up to 1.000.000
#define NUM_RESULTS 1000

pthread_barrier_t ab_barrier;

#define TOPO_NAME(x,y) sprintf(x, "%s_%s", y, topo_get_name());

mcs_barrier_t mcs_b;
static void* mcs_barrier(void* a)
{
    coreid_t tid = *((int*) a);
    __thread_init(tid, num_threads); // will bind threads

    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
    char outname[1024];
    TOPO_NAME(outname, "mcs-barrier");
    sk_m_init(&m, NUM_RESULTS, outname, buf);

    sk_m_restart_tsc(&m);
    for (unsigned i=0; i<NUM_RUNS; i++) {

        mcs_barrier_wait(&mcs_b, tid);
    }

    sk_m_add(&m);
    if (get_thread_id() == get_sequentializer()) {
        sk_m_print(&m);
    }

    return NULL;
}

static void* barrier(void* a)
{

    coreid_t tid = *((int*) a);
    __thread_init(tid, num_threads);

    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
    char outname[1024];
    TOPO_NAME(outname, "syc-barrier");
    sk_m_init(&m, NUM_RESULTS, outname, buf);

    sk_m_restart_tsc(&m);
    for (int epoch=0; epoch<NUM_RUNS; epoch++) {
#ifdef HYB
        shl_hybrid_barrier(NULL);
#else
        mp_barrier(NULL);
#endif
    }

    sk_m_add(&m);
    if (get_thread_id() == get_sequentializer()) {
        sk_m_print(&m);
    }

    __thread_end();
    return NULL;
}

static void* barrier0(void* a)
{

    coreid_t tid = *((int*) a);
    __thread_init(tid, num_threads);

    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
    char outname[1024];
    TOPO_NAME(outname, "syc-barrier0");
    sk_m_init(&m, NUM_RESULTS, outname, buf);

    sk_m_restart_tsc(&m);
    for (int epoch=0; epoch<NUM_RUNS; epoch++) {
#ifdef HYB
        shl_hybrid_barrier0(NULL);
#else
        mp_barrier0();
#endif
    }

    sk_m_add(&m);
    if (get_thread_id() == get_sequentializer()) {
        sk_m_print(&m);
    }

    __thread_end();
    return NULL;
}

#define NUM_EXP 3

#define max(a,b) \
    ({ __typeof__ (a) _a = (a); \
        __typeof__ (b) _b = (b); \
        _a > _b ? _a : _b; })

int main(int argc, char **argv)
{
    unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF);

    int topology = -1;
    if (argc>1) {
        topology = atoi(argv[1]);

    }
    if (topology>=0) {
        switch_topo_to_idx(topology);
    } else {
        printf("No topology given, using default one\n");
    }

    __sync_init(nthreads, true);

    num_threads = get_num_threads();

    mcs_barrier_init(&mcs_b, num_threads);
    pthread_barrier_init(&ab_barrier, NULL, num_threads);

    typedef void* (worker_func_t)(void*);
    worker_func_t* workers[NUM_EXP] = {
        &mcs_barrier,
        &barrier,
        &barrier0,
    };

    const char *labels[NUM_EXP] = {
        "MCS barrier",
        "libsync barrier",
        "libsync barrier0"
    };

    pthread_t ptds[num_threads];
    int tids[num_threads];

    printf("%d models\n", max(1U, (topo_num_topos()-1)));

    // Choose how many topologies to evaluate.  We evaluate at least
    // one, even in the case of the auto-generated binary tree. If a
    // topology is given as argument, we ONLY evaluate that single
    // one.
    size_t num_topos = max(1U, (topo_num_topos()-1));
    if (topology>=0) {
        num_topos = 1;
    }

    for (unsigned e=0; e<num_topos; e++) {
        for (int j=0; j<NUM_EXP; j++) {
            printf("----------------------------------------\n");
            printf("Executing experiment %d - %s\n", (j+1), labels[j]);
            printf("----------------------------------------\n");

            // Yield to reduce the risk of getting de-scheduled later
            sched_yield();

            // Create
            for (unsigned i=1; i<num_threads; i++) {
                tids[i] = i;

                pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i));
            }

            // Master thread executes work for node 0
            tids[0] = 0;
            workers[j]((void*) (tids+0));

            // Join
            for (unsigned i=1; i<num_threads; i++) {
                pthread_join(ptds[i], NULL);
            }
        }

        if( e<topo_num_topos()-1) switch_topo();
    }

    pthread_barrier_destroy(&ab_barrier);
}
<commit_msg>adding multiple runs for ab-throuthput<commit_after>/*
 *
 */
#include <stdio.h>
#include "sync.h"
#include "topo.h"
#include "mp.h"
#include "measurement_framework.h"
#include <pthread.h>
#include <unistd.h>
#include <vector>

#include "model_defs.h"
#include "barrier.h"

#ifdef PARLIB
#include "mcs.h"
#endif

#define HYB 1

//#define SEND7

#ifdef BARRELFISH
#include <barrelfish/barrelfish.h>
#include <posixcompat.h>
#endif

__thread struct sk_measurement m;
__thread struct sk_measurement m2;

unsigned num_threads;
#define NUM_RUNS 100000 //50 // 10000 // Tested up to 1.000.000
#define NUM_REPETITIONS 100
#define NUM_RESULTS 1000

pthread_barrier_t ab_barrier;

#define TOPO_NAME(x,y) sprintf(x, "%s_%s", y, topo_get_name());

mcs_barrier_t mcs_b;
static void* mcs_barrier(void* a)
{
    coreid_t tid = *((int*) a);
    __thread_init(tid, num_threads); // will bind threads

    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
    char outname[1024];
    TOPO_NAME(outname, "mcs-barrier");
    sk_m_init(&m, NUM_RESULTS, outname, buf);
for (int k = 0; k < NUM_REPETITIONS; ++k) {

    sk_m_restart_tsc(&m);
    for (unsigned i=0; i<NUM_RUNS; i++) {

        mcs_barrier_wait(&mcs_b, tid);
    }

    sk_m_add(&m);
    if (get_thread_id() == get_sequentializer()) {
        sk_m_print(&m);
    }
}
    return NULL;
}

static void* barrier(void* a)
{

    coreid_t tid = *((int*) a);
    __thread_init(tid, num_threads);

    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
    char outname[1024];
    TOPO_NAME(outname, "syc-barrier");
    sk_m_init(&m, NUM_RESULTS, outname, buf);
for (int k = 0; k < NUM_REPETITIONS; ++k) {

    sk_m_restart_tsc(&m);
    for (int epoch=0; epoch<NUM_RUNS; epoch++) {
#ifdef HYB
        shl_hybrid_barrier(NULL);
#else
        mp_barrier(NULL);
#endif
    }

    sk_m_add(&m);
    if (get_thread_id() == get_sequentializer()) {
        sk_m_print(&m);
    }
}
    __thread_end();
    return NULL;
}

static void* barrier0(void* a)
{

    coreid_t tid = *((int*) a);
    __thread_init(tid, num_threads);

    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
    char outname[1024];
    TOPO_NAME(outname, "syc-barrier0");
    sk_m_init(&m, NUM_RESULTS, outname, buf);

    for (int k = 0; k < NUM_REPETITIONS; ++k) {

    sk_m_restart_tsc(&m);
    for (int epoch=0; epoch<NUM_RUNS; epoch++) {
#ifdef HYB
        shl_hybrid_barrier0(NULL);
#else
        mp_barrier0();
#endif
    }

    sk_m_add(&m);
    if (get_thread_id() == get_sequentializer()) {
        sk_m_print(&m);
    }
    }
    __thread_end();
    return NULL;
}

#define NUM_EXP 3

#define max(a,b) \
    ({ __typeof__ (a) _a = (a); \
        __typeof__ (b) _b = (b); \
        _a > _b ? _a : _b; })

#ifdef BARRELFISH
static void domain_init_done(void *arg, errval_t err)
{
    debug_printf("SPANNED!\n");
}
#endif

int main(int argc, char **argv)
{
    unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF);

    int topology = -1;
    if (argc>1) {
        topology = atoi(argv[1]);

    }
    if (topology>=0) {
        switch_topo_to_idx(topology);
    } else {
        printf("No topology given, using default one\n");
    }

    __sync_init(nthreads, true);

    num_threads = get_num_threads();

    mcs_barrier_init(&mcs_b, num_threads);
    pthread_barrier_init(&ab_barrier, NULL, num_threads);

    typedef void* (worker_func_t)(void*);
    worker_func_t* workers[NUM_EXP] = {
        &mcs_barrier,
        &barrier,
        &barrier0,
    };

    const char *labels[NUM_EXP] = {
        "MCS barrier",
        "libsync barrier",
        "libsync barrier0"
    };

    pthread_t ptds[num_threads];
    int tids[num_threads];

    printf("%d models\n", max(1U, (topo_num_topos()-1)));

#ifdef BARRELFISH
    cpu_set_t *cpuset = CPU_ALLOC(num_threads);

    for (unsigned i=1; i<num_threads; i++) {
        //for (int i = my_core_id + BOMP_DEFAULT_CORE_STRIDE; i < nos_threads + my_core_id; i++) {
        coreid_t core = i;
        errval_t err = domain_new_dispatcher(core, domain_init_done, NULL);
        if (err_is_fail(err)) {
            DEBUG_ERR(err, "failed to span domain");
            printf("Failed to span domain to %d\n", i);
            assert(err_is_ok(err));
        }
    }

#endif

    // Choose how many topologies to evaluate.  We evaluate at least
    // one, even in the case of the auto-generated binary tree. If a
    // topology is given as argument, we ONLY evaluate that single
    // one.
    size_t num_topos = max(1U, (topo_num_topos()-1));
    if (topology>=0) {
        num_topos = 1;
    }

    for (unsigned e=0; e<num_topos; e++) {
        for (int j=0; j<NUM_EXP; j++) {
            printf("----------------------------------------\n");
            printf("Executing experiment %d - %s\n", (j+1), labels[j]);
            printf("----------------------------------------\n");
            // Yield to reduce the risk of getting de-scheduled later
            sched_yield();

            // Create
            for (unsigned i=1; i<num_threads; i++) {
                tids[i] = i;
#ifdef BARRELFISH
                pthread_attr_t attr;
                pthread_attr_init(&attr);

                CPU_ZERO(cpuset);
                CPU_SET(i, cpuset);
                pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), cpuset);

                pthread_create(ptds+i, &attr, workers[j], (void*) (tids+i));
#else

                pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i));
#endif
            }

            // Master thread executes work for node 0
            tids[0] = 0;
            workers[j]((void*) (tids+0));

            // Join
            for (unsigned i=1; i<num_threads; i++) {
                pthread_join(ptds[i], NULL);
            }
        }

        if( e<topo_num_topos()-1) switch_topo();
    }

    pthread_barrier_destroy(&ab_barrier);
}
<|endoftext|>


<commit_before>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#define BOOST_TEST_MAIN

#include "Tudat/JsonInterface/UnitTests/unitTestSupport.h"
#include "Tudat/JsonInterface/Support/valueAccess.h"
#include "Tudat/JsonInterface/Support/valueConversions.h"
#include "Tudat/JsonInterface/Support/deserialization.h"

namespace tudat
{

namespace unit_tests
{

#define INPUT( filename ) \
    ( json_interface::inputDirectory( ) / boost::filesystem::path( __FILE__ ).stem( ) / filename ).string( )

BOOST_AUTO_TEST_SUITE( test_json_deserialization )

// Test 1: value access
BOOST_AUTO_TEST_CASE( test_json_valueAccess )
{
    using namespace json_interface;

    const nlohmann::json dog = parseJSONFile( INPUT( "valueAccess" ) );

    // Numbers
    BOOST_CHECK_EQUAL( getValue< unsigned int >( dog, "age" ), 11 );
    BOOST_CHECK_EQUAL( getValue< int >( dog, "age" ), 11 );
    BOOST_CHECK_EQUAL( getValue< double >( dog, "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< float >( dog, "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< long double >( dog, "mass" ), 19.5 );

    // Strings
    BOOST_CHECK_EQUAL( getValue< std::string >( dog, "name" ), "Bumper" );

    // Arrays
    const std::vector< std::string > hobbies = { "eat", "sleep" };
    const std::string hobbiesKey = "hobbies";
    BOOST_CHECK( getValue< std::vector< std::string > >( dog, hobbiesKey ) == hobbies );
    BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 0 ), hobbies.at( 0 ) );
    BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 1 ), hobbies.at( 1 ) );

    // Context: one level
    const nlohmann::json enemy = getValue< std::vector< nlohmann::json > >( dog, "enemies" ).front( );
    BOOST_CHECK_EQUAL( getRootObject( enemy ), dog );
    BOOST_CHECK_EQUAL( getValue< double >( enemy, "mass" ), 2.6 );
    BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::root / "mass" ), 19.5 );

    // Context: several levels
    const nlohmann::json valencia =
            getValue< nlohmann::json >( enemy, std::string( "mother" ) / "birthplace" / "city" );
    BOOST_CHECK_EQUAL( valencia.at( "name" ), "Valencia" );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::root / "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / SpecialKeys::up / SpecialKeys::up /
                                           SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 0 ), -15 );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 1 ), 45 );

    // Eigen
    const Eigen::Matrix3d matrix = getValue< Eigen::Matrix3d >( dog, "orientation" );
    const Eigen::Matrix3d matrix2 = ( Eigen::Matrix3d( ) << 1.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 3.0, -1.0 ).finished( );
    BOOST_CHECK_EQUAL( matrix, matrix2 );

    // Map with non-char keys
    const std::map< double, std::string > food = getValue< std::map< double, std::string > >( dog, "food" );
    const std::map< double, std::string > food2 = { { 7, "feed" }, { 12, "meat" }, { 15, "feed" }, { 19, "feed" } };
    BOOST_CHECK( food == food2 );
}

// Test 2: modular
BOOST_AUTO_TEST_CASE( test_json_modular )
{
    using namespace json_interface;

    const nlohmann::json modular = getDeserializedJSON( getPathForJSONFile( INPUT( "modular" ) ) );

    nlohmann::json simulation;
    simulation[ "bodies" ] =
            R"(
            {
            "Earth": {
            "useDefaultSettings": true
            },
            "satellite": {
            "mass": 500
            }
            }
            )"_json;

    simulation[ "propagators" ] =
            R"(
            [
            {
            "centralBodies": [
            "Earth"
            ],
            "bodiesToPropagate": [
            "satellite"
            ]
            }
            ]
            )"_json;

    simulation[ "integrator" ] =
            R"(
            {
            "type": "rungeKutta4",
            "stepSize": 30
            }
            )"_json;

    simulation[ "export" ] =
            R"(
            [
            {
            "variables": [
            {
            "type": "independent"
            }
            ]
            },
            {
            "variables": [
            {
            "body": "satellite",
            "dependentVariableType": "relativePosition",
            "relatieToBody": "Earth"
            },
            {
            "body": "satellite",
            "dependentVariableType": "relativeVelocity",
            "relatieToBody": "Earth"
            }
            ]
            }
            ]
            )"_json;

    simulation[ "export" ][ 0 ][ "file" ] =
            ( boost::filesystem::path( "export" ) / ".." / "outputs" / "epochs.txt" ).string( );
    simulation[ "export" ][ 1 ][ "file" ] =
            ( boost::filesystem::path( "export" ) / ".." / "states.txt" ).string( );

    BOOST_CHECK_EQUAL( modular, simulation );
}

// Test 3: mergeable
BOOST_AUTO_TEST_CASE( test_json_mergeable )
{
    using namespace json_interface;
    using namespace boost::filesystem;

    const nlohmann::json merged1 = getDeserializedJSON(
                getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge1" ).string( ) ) ) );

    const nlohmann::json manual1 =
            R"(
            {
            "type": "rungeKutta4",
            "stepSize": 20
            }
            )"_json;

    BOOST_CHECK_EQUAL( merged1, manual1 );

    const nlohmann::json merged2 = getDeserializedJSON(
                getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge2" ).string( ) ) ) );

    const nlohmann::json manual2 =
            R"(
            {
            "integrator": {
            "type": "rungeKutta4",
            "stepSize": 20,
            "initialTimes": [
            0,
            86400
            ]
            }
            }
            )"_json;

    BOOST_CHECK_EQUAL( merged2, manual2 );

    const nlohmann::json merged3 = getDeserializedJSON(
                getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge3" ).string( ) ) ) );

    const nlohmann::json manual3 =
            R"(
            {
            "integrator": {
            "type": "rungeKutta4",
            "stepSize": 20,
            "initialTimes": [
            0,
            43200,
            86400
            ]
            },
            "spice": {
            "useStandardKernels": true,
            "preloadEpehemeris": false
            }
            }
            )"_json;

    BOOST_CHECK_EQUAL( merged3, manual3 );
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests

} // namespace tudat
<commit_msg>Fix path difference in unit test for windows.<commit_after>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#define BOOST_TEST_MAIN

#include "Tudat/JsonInterface/UnitTests/unitTestSupport.h"
#include "Tudat/JsonInterface/Support/valueAccess.h"
#include "Tudat/JsonInterface/Support/valueConversions.h"
#include "Tudat/JsonInterface/Support/deserialization.h"

namespace tudat
{

namespace unit_tests
{

#define INPUT( filename ) \
    ( json_interface::inputDirectory( ) / boost::filesystem::path( __FILE__ ).stem( ) / filename ).string( )

BOOST_AUTO_TEST_SUITE( test_json_deserialization )

// Test 1: value access
BOOST_AUTO_TEST_CASE( test_json_valueAccess )
{
    using namespace json_interface;

    const nlohmann::json dog = parseJSONFile( INPUT( "valueAccess" ) );

    // Numbers
    BOOST_CHECK_EQUAL( getValue< unsigned int >( dog, "age" ), 11 );
    BOOST_CHECK_EQUAL( getValue< int >( dog, "age" ), 11 );
    BOOST_CHECK_EQUAL( getValue< double >( dog, "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< float >( dog, "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< long double >( dog, "mass" ), 19.5 );

    // Strings
    BOOST_CHECK_EQUAL( getValue< std::string >( dog, "name" ), "Bumper" );

    // Arrays
    const std::vector< std::string > hobbies = { "eat", "sleep" };
    const std::string hobbiesKey = "hobbies";
    BOOST_CHECK( getValue< std::vector< std::string > >( dog, hobbiesKey ) == hobbies );
    BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 0 ), hobbies.at( 0 ) );
    BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 1 ), hobbies.at( 1 ) );

    // Context: one level
    const nlohmann::json enemy = getValue< std::vector< nlohmann::json > >( dog, "enemies" ).front( );
    BOOST_CHECK_EQUAL( getRootObject( enemy ), dog );
    BOOST_CHECK_EQUAL( getValue< double >( enemy, "mass" ), 2.6 );
    BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::root / "mass" ), 19.5 );

    // Context: several levels
    const nlohmann::json valencia =
            getValue< nlohmann::json >( enemy, std::string( "mother" ) / "birthplace" / "city" );
    BOOST_CHECK_EQUAL( valencia.at( "name" ), "Valencia" );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::root / "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / SpecialKeys::up / SpecialKeys::up /
                                           SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 0 ), -15 );
    BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 1 ), 45 );

    // Eigen
    const Eigen::Matrix3d matrix = getValue< Eigen::Matrix3d >( dog, "orientation" );
    const Eigen::Matrix3d matrix2 = ( Eigen::Matrix3d( ) << 1.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 3.0, -1.0 ).finished( );
    BOOST_CHECK_EQUAL( matrix, matrix2 );

    // Map with non-char keys
    const std::map< double, std::string > food = getValue< std::map< double, std::string > >( dog, "food" );
    const std::map< double, std::string > food2 = { { 7, "feed" }, { 12, "meat" }, { 15, "feed" }, { 19, "feed" } };
    BOOST_CHECK( food == food2 );
}

// Test 2: modular
BOOST_AUTO_TEST_CASE( test_json_modular )
{
    using namespace json_interface;

    const nlohmann::json modular = getDeserializedJSON( getPathForJSONFile( INPUT( "modular" ) ) );

    nlohmann::json simulation;
    simulation[ "bodies" ] =
            R"(
            {
            "Earth": {
            "useDefaultSettings": true
            },
            "satellite": {
            "mass": 500
            }
            }
            )"_json;

    simulation[ "propagators" ] =
            R"(
            [
            {
            "centralBodies": [
            "Earth"
            ],
            "bodiesToPropagate": [
            "satellite"
            ]
            }
            ]
            )"_json;

    simulation[ "integrator" ] =
            R"(
            {
            "type": "rungeKutta4",
            "stepSize": 30
            }
            )"_json;

    simulation[ "export" ] =
            R"(
            [
            {
            "variables": [
            {
            "type": "independent"
            }
            ]
            },
            {
            "variables": [
            {
            "body": "satellite",
            "dependentVariableType": "relativePosition",
            "relatieToBody": "Earth"
            },
            {
            "body": "satellite",
            "dependentVariableType": "relativeVelocity",
            "relatieToBody": "Earth"
            }
            ]
            }
            ]
            )"_json;

    simulation[ "export" ][ 0 ][ "file" ] =
            ( boost::filesystem::path( "export" ) / "../outputs/epochs.txt" ).string( );
    simulation[ "export" ][ 1 ][ "file" ] =
            ( boost::filesystem::path( "export" ) / "../states.txt" ).string( );

    BOOST_CHECK_EQUAL( modular, simulation );
}

// Test 3: mergeable
BOOST_AUTO_TEST_CASE( test_json_mergeable )
{
    using namespace json_interface;
    using namespace boost::filesystem;

    const nlohmann::json merged1 = getDeserializedJSON(
                getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge1" ).string( ) ) ) );

    const nlohmann::json manual1 =
            R"(
            {
            "type": "rungeKutta4",
            "stepSize": 20
            }
            )"_json;

    BOOST_CHECK_EQUAL( merged1, manual1 );

    const nlohmann::json merged2 = getDeserializedJSON(
                getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge2" ).string( ) ) ) );

    const nlohmann::json manual2 =
            R"(
            {
            "integrator": {
            "type": "rungeKutta4",
            "stepSize": 20,
            "initialTimes": [
            0,
            86400
            ]
            }
            }
            )"_json;

    BOOST_CHECK_EQUAL( merged2, manual2 );

    const nlohmann::json merged3 = getDeserializedJSON(
                getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge3" ).string( ) ) ) );

    const nlohmann::json manual3 =
            R"(
            {
            "integrator": {
            "type": "rungeKutta4",
            "stepSize": 20,
            "initialTimes": [
            0,
            43200,
            86400
            ]
            },
            "spice": {
            "useStandardKernels": true,
            "preloadEpehemeris": false
            }
            }
            )"_json;

    BOOST_CHECK_EQUAL( merged3, manual3 );
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests

} // namespace tudat
<|endoftext|>


<commit_before>//
// Created by Vadim N. on 18/03/2015.
//

#ifndef _BENCHMARK_H_
#define _BENCHMARK_H_

#include "benchutils.h"

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

    if (argc < 2) {
      std::cout << "Please re-run the script with the data folder path supplied." << std::endl;
      return 1;
    }

    std::chrono::system_clock::time_point tp1, tp2;

    std::vector< std::pair<std::string, size_t> > timepoints;

    std::vector<prob_t> logLvec;

    std::string temp_str;

    std::string BENCH_DATA_FOLDER = argv[1];

    ClonesetNuc cloneset_vj, cloneset_vdj, cloneset_vj_noncoding, cloneset_vdj_noncoding;

    string input_alpha_file = "alpha.full.500k.txt", input_alpha_file_nonc = "alpha.noncoding.100k.txt";
    string input_beta_file = "beta.noncoding.500k.txt", input_beta_file_nonc = "beta.noncoding.100k.txt";

    auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3,
                                                           VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),
                                                                                AlignmentEventScore(1, -1, 1),
                                                                                AlignmentEventScore(1, -1, 1)),
                                                           VDJAlignmentScoreThreshold(2, 3, 2));

    ParserNuc parser(new NaiveCDR3NucleotideAligner());

    //
    // TCR alpha chain repertoire - VJ recombination
    //
    VDJRecombinationGenes vj_single_genes("Vgene",
                                   BENCH_DATA_FOLDER + "trav.txt",
                                   "Jgene",
                                   BENCH_DATA_FOLDER + "traj.txt");

    YMIR_BENCHMARK("Parsing VJ",
                   parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,
                                       &cloneset_vj,
                                       vj_single_genes,
                                       VJ_RECOMB,
                                       AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
                                                              AlignmentColumnOptions::REALIGN_PROVIDED),
                                       vdj_aligner_parameters_nuc))

    //
    // TCR beta chain repertoire - VDJ recombination
    //
    VDJRecombinationGenes vdj_single_genes("Vgene",
                                    BENCH_DATA_FOLDER + "trbv.txt",
                                    "Jgene",
                                    BENCH_DATA_FOLDER + "trbj.txt",
                                    "Dgene",
                                    BENCH_DATA_FOLDER + "trbd.txt");

    YMIR_BENCHMARK("Parsing VDJ",
                   parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,
                                       &cloneset_vdj,
                                       vdj_single_genes,
                                       VDJ_RECOMB,
                                       AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
                                                              AlignmentColumnOptions::OVERWRITE,
                                                              AlignmentColumnOptions::REALIGN_PROVIDED),
                                       vdj_aligner_parameters_nuc))

    //
    // VJ MAAG
    //
    vector<prob_t> vec;
    ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY);
    YMIR_BENCHMARK("VJ meta", vj_single_model.buildGraphs(cloneset_vj, SAVE_METADATA, NO_ERRORS, false))
    YMIR_BENCHMARK("VJ prob", vec = vj_single_model.computeFullProbabilities(cloneset_vj, NO_ERRORS, SUM_PROBABILITY, false))
    std::cout << loglikelihood(vec) << std::endl;

    //
    // VDJ MAAG
    //
    ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);
    YMIR_BENCHMARK("VDJ meta", vdj_single_model.buildGraphs(cloneset_vdj, SAVE_METADATA, NO_ERRORS, false))
    YMIR_BENCHMARK("VDJ prob", vdj_single_model.computeFullProbabilities(cloneset_vdj, NO_ERRORS, SUM_PROBABILITY, false))

    //
    // VJ inference
    //
    parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file_nonc,
                        &cloneset_vj_noncoding,
                        vj_single_genes,
                        VJ_RECOMB,
                        AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
                                               AlignmentColumnOptions::REALIGN_PROVIDED),
                        vdj_aligner_parameters_nuc);

    YMIR_BENCHMARK("VJ EM",
                   logLvec = EMAlgorithm().statisticalInference(cloneset_vj, vj_single_model,
                                                                EMAlgorithm::AlgorithmParameters()
                                                                        .set("niter", 30),
                                                                NO_ERRORS))
//
//    YMIR_BENCHMARK("VJ SG",
//                   logLvec = SGAlgorithm().statisticalInference(cloneset_vj, vj_single_model,
//                                                                SGAlgorithm::AlgorithmParameters()
//                                                                        .set("niter", 10)
//                                                                        .set("block.size", 5000)
//                                                                        .set("alpha", .7)
//                                                                        .set("beta", 1.)
//                                                                        .set("K", 2.)
//                                                                        .set("prebuild", false)
//                                                                        .set("sample", 100000),
//                                                                NO_ERRORS))

    //
    // VDJ inference
    //
    parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file_nonc,
                        &cloneset_vdj_noncoding,
                        vdj_single_genes,
                        VDJ_RECOMB,
                        AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
                                               AlignmentColumnOptions::OVERWRITE,
                                               AlignmentColumnOptions::REALIGN_PROVIDED),
                        vdj_aligner_parameters_nuc);

    YMIR_BENCHMARK("VDJ EM",
                   logLvec = EMAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,
                                                      EMAlgorithm::AlgorithmParameters()
                                                              .set("niter", 30),
                                                                NO_ERRORS))
//
//    YMIR_BENCHMARK("VDJ SG",
//                   logLvec = SGAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,
//                                                      SGAlgorithm::AlgorithmParameters()
//                                                              .set("niter", 10)
//                                                              .set("block.size", 5000)
//                                                              .set("alpha", .7)
//                                                              .set("beta", 1.)
//                                                              .set("K", 2.)
//                                                              .set("prebuild", false)
//                                                              .set("sample", 100000),
//                                                                NO_ERRORS))

    //
    // Results
    //
    cout << "========================" << endl << "Results:" << endl;

    for (size_t i = 0; i < timepoints.size(); ++i) {
        cout << timepoints[i].first << ":\t" << timepoints[i].second << endl;
    }

    cout << endl << "========================" << endl;

    return 0;
}

#endif //_BENCHMARK_H_
<commit_msg>change aligner params<commit_after>//
// Created by Vadim N. on 18/03/2015.
//

#ifndef _BENCHMARK_H_
#define _BENCHMARK_H_

#include "benchutils.h"

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

    if (argc < 2) {
      std::cout << "Please re-run the script with the data folder path supplied." << std::endl;
      return 1;
    }

    std::chrono::system_clock::time_point tp1, tp2;

    std::vector< std::pair<std::string, size_t> > timepoints;

    std::vector<prob_t> logLvec;

    std::string temp_str;

    std::string BENCH_DATA_FOLDER = argv[1];

    ClonesetNuc cloneset_vj, cloneset_vdj, cloneset_vj_noncoding, cloneset_vdj_noncoding;

    string input_alpha_file = "alpha.full.500k.txt", input_alpha_file_nonc = "alpha.noncoding.100k.txt";
    string input_beta_file = "beta.noncoding.500k.txt", input_beta_file_nonc = "beta.noncoding.100k.txt";

    auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3,
                                                           VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),
                                                                                AlignmentEventScore(1, -1, 1),
                                                                                AlignmentEventScore(1, -1, 1)),
                                                           VDJAlignmentScoreThreshold(6, 3, 5));

    ParserNuc parser(new NaiveCDR3NucleotideAligner());

    //
    // TCR alpha chain repertoire - VJ recombination
    //
    VDJRecombinationGenes vj_single_genes("Vgene",
                                   BENCH_DATA_FOLDER + "trav.txt",
                                   "Jgene",
                                   BENCH_DATA_FOLDER + "traj.txt");

    YMIR_BENCHMARK("Parsing VJ",
                   parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,
                                       &cloneset_vj,
                                       vj_single_genes,
                                       VJ_RECOMB,
                                       AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE,
                                                              AlignmentColumnOptions::OVERWRITE),
                                       vdj_aligner_parameters_nuc))

    //
    // TCR beta chain repertoire - VDJ recombination
    //
    VDJRecombinationGenes vdj_single_genes("Vgene",
                                    BENCH_DATA_FOLDER + "trbv.txt",
                                    "Jgene",
                                    BENCH_DATA_FOLDER + "trbj.txt",
                                    "Dgene",
                                    BENCH_DATA_FOLDER + "trbd.txt");

    YMIR_BENCHMARK("Parsing VDJ",
                   parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,
                                       &cloneset_vdj,
                                       vdj_single_genes,
                                       VDJ_RECOMB,
                                       AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE,
                                                              AlignmentColumnOptions::OVERWRITE,
                                                              AlignmentColumnOptions::OVERWRITE),
                                       vdj_aligner_parameters_nuc))

    //
    // VJ MAAG
    //
    vector<prob_t> vec;
    ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY);
    YMIR_BENCHMARK("VJ meta", vj_single_model.buildGraphs(cloneset_vj, SAVE_METADATA, NO_ERRORS, false))
    YMIR_BENCHMARK("VJ prob", vec = vj_single_model.computeFullProbabilities(cloneset_vj, NO_ERRORS, SUM_PROBABILITY, false))
    std::cout << loglikelihood(vec) << std::endl;

    //
    // VDJ MAAG
    //
    ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);
    YMIR_BENCHMARK("VDJ meta", vdj_single_model.buildGraphs(cloneset_vdj, SAVE_METADATA, NO_ERRORS, false))
    YMIR_BENCHMARK("VDJ prob", vdj_single_model.computeFullProbabilities(cloneset_vdj, NO_ERRORS, SUM_PROBABILITY, false))

    //
    // VJ inference
    //
    parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file_nonc,
                        &cloneset_vj_noncoding,
                        vj_single_genes,
                        VJ_RECOMB,
                        AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
                                               AlignmentColumnOptions::REALIGN_PROVIDED),
                        vdj_aligner_parameters_nuc);

    YMIR_BENCHMARK("VJ EM",
                   logLvec = EMAlgorithm().statisticalInference(cloneset_vj, vj_single_model,
                                                                EMAlgorithm::AlgorithmParameters()
                                                                        .set("niter", 30),
                                                                NO_ERRORS))
//
//    YMIR_BENCHMARK("VJ SG",
//                   logLvec = SGAlgorithm().statisticalInference(cloneset_vj, vj_single_model,
//                                                                SGAlgorithm::AlgorithmParameters()
//                                                                        .set("niter", 10)
//                                                                        .set("block.size", 5000)
//                                                                        .set("alpha", .7)
//                                                                        .set("beta", 1.)
//                                                                        .set("K", 2.)
//                                                                        .set("prebuild", false)
//                                                                        .set("sample", 100000),
//                                                                NO_ERRORS))

    //
    // VDJ inference
    //
    parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file_nonc,
                        &cloneset_vdj_noncoding,
                        vdj_single_genes,
                        VDJ_RECOMB,
                        AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
                                               AlignmentColumnOptions::OVERWRITE,
                                               AlignmentColumnOptions::REALIGN_PROVIDED),
                        vdj_aligner_parameters_nuc);

    YMIR_BENCHMARK("VDJ EM",
                   logLvec = EMAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,
                                                      EMAlgorithm::AlgorithmParameters()
                                                              .set("niter", 30),
                                                                NO_ERRORS))
//
//    YMIR_BENCHMARK("VDJ SG",
//                   logLvec = SGAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,
//                                                      SGAlgorithm::AlgorithmParameters()
//                                                              .set("niter", 10)
//                                                              .set("block.size", 5000)
//                                                              .set("alpha", .7)
//                                                              .set("beta", 1.)
//                                                              .set("K", 2.)
//                                                              .set("prebuild", false)
//                                                              .set("sample", 100000),
//                                                                NO_ERRORS))

    //
    // Results
    //
    cout << "========================" << endl << "Results:" << endl;

    for (size_t i = 0; i < timepoints.size(); ++i) {
        cout << timepoints[i].first << ":\t" << timepoints[i].second << endl;
    }

    cout << endl << "========================" << endl;

    return 0;
}

#endif //_BENCHMARK_H_
<|endoftext|>


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

#ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP
#define INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP

#include "../../../Platform.hpp"
#if defined(NENE_OS_WINDOWS)

#include <memory>
#include <d3d11.h>
#include <wrl/client.h>
#include "../../../Uncopyable.hpp"
#include "../../IDynamicTexture.hpp"

namespace Nene::Windows::Direct3D11
{
	// Forward declarations.
	class Texture;

	/**
	 * @brief      Directr3D11 dynamic texture implementation.
	 */
	class DynamicTexture final
		: public  IDynamicTexture
		, private Uncopyable
	{
		std::unique_ptr<Texture> texture_;

		Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTarget_;

	public:
		/**
		 * @brief      Constructor.
		 *
		 * @param[in]  texture  Direct3D11 texture.
		 */
		explicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Texture2D>& texture);

		/**
		 * @brief      Constructor.
		 *
		 * @param[in]  device  Direct3D11 device.
		 * @param[in]  size    The texture size.
		 * @param[in]  format  The texture pixel format.
		 */
		explicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Device>& device, const Size2Di& size);

		/**
		 * @brief      Destructor.
		 */
		~DynamicTexture();

		/**
		 * @see        `Nene::ITexture::size()`.
		 */
		[[nodiscard]]
		const Size2Di& size() const noexcept override;
	};
}

#endif

#endif  // #ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP
<commit_msg>:pencil: Fix typo.<commit_after>//=============================================================================
// Copyright (c) 2017 Ryooooooga
// https://github.com/Ryooooooga
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom
// the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//=============================================================================

#ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP
#define INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP

#include "../../../Platform.hpp"
#if defined(NENE_OS_WINDOWS)

#include <memory>
#include <d3d11.h>
#include <wrl/client.h>
#include "../../../Uncopyable.hpp"
#include "../../IDynamicTexture.hpp"

namespace Nene::Windows::Direct3D11
{
	// Forward declarations.
	class Texture;

	/**
	 * @brief      Direct3D11 dynamic texture implementation.
	 */
	class DynamicTexture final
		: public  IDynamicTexture
		, private Uncopyable
	{
		std::unique_ptr<Texture> texture_;

		Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTarget_;

	public:
		/**
		 * @brief      Constructor.
		 *
		 * @param[in]  texture  Direct3D11 texture.
		 */
		explicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Texture2D>& texture);

		/**
		 * @brief      Constructor.
		 *
		 * @param[in]  device  Direct3D11 device.
		 * @param[in]  size    The texture size.
		 * @param[in]  format  The texture pixel format.
		 */
		explicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Device>& device, const Size2Di& size);

		/**
		 * @brief      Destructor.
		 */
		~DynamicTexture();

		/**
		 * @see        `Nene::ITexture::size()`.
		 */
		[[nodiscard]]
		const Size2Di& size() const noexcept override;
	};
}

#endif

#endif  // #ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdint>
#include <vector>
#include <limits>

//////////////////////////////////////////////////////////////////////
// Represents the range [low,high]
template <typename VAL_T>
class value_range
{
 public:
	typedef VAL_T value_type;
	typedef std::size_t size_type;

	value_range() : begin(0) , end(0) { }

	value_range(const value_type & low, const value_type & high)
	  : begin(low) , end(high) { }

/*
	value_range(const value_range & other) = default;
	value_range(value_range && other) = default;
	~value_range() = default;
*/

	value_type min() const { return begin; }

	value_type max() const { return end; }

	size_type size() const { return (end - begin); }

	bool intersects(const value_range & other)
	{
		return (  ( other.begin >= begin && other.begin <= end )
		       || ( other.end >= begin   && other.end <= end )
		       || ( begin >= other.begin && begin <= other.end )
		       || ( end >= other.begin   && end <= other.end ) );
	}

	bool operator == (const value_range & other)
		{ return ( (begin == other.begin) && (end == other.end) ); }

 private:
	value_type begin, end;
};

//////////////////////////////////////////////////////////////////////
value_range<uint32_t>
find_interval(std::vector<uint32_t> & interval_list, uint32_t val)
{
	value_range<uint32_t> retval;
	uint32_t last = 0;
	for (auto & x : interval_list)
	{
		if (val <= x)
		{
			retval = value_range<uint32_t>(last, x);
			break;
		}

		last = x + 1;
	}
	return retval;
}

//////////////////////////////////////////////////////////////////////
value_range<uint32_t>
find_interval2(std::vector<uint32_t> & interval_list, uint32_t val)
{
	value_range<uint32_t> retval;
	size_t index = (interval_list.size() >> 1);
	size_t lbound = 0;
	size_t ubound = interval_list.size() - 1;

	while ((ubound - lbound) > 1)
	{
		printf("index = %zu, l = %zu, u = %zu\n", index, lbound, ubound);
		if (val <= interval_list[index])
		{
			ubound = index;
		} else if (val > interval_list[index])
		{
			lbound = index;
		}

		index = ((ubound + lbound) >> 1);
	}

	printf("index = %zu, l = %zu, u = %zu\n", index, lbound, ubound);
	printf("----> %u (%u-%u)\n", interval_list[index],
	       interval_list[lbound], interval_list[ubound]);

	return retval;
}

//////////////////////////////////////////////////////////////////////
int main()
{
	std::vector<value_range<uint32_t>> intervals;
	std::vector<uint32_t> search;

	intervals.emplace_back(0, 20);
	intervals.emplace_back(intervals.back().max() + 1, 23);
	intervals.emplace_back(intervals.back().max() + 1, 24);
	intervals.emplace_back(intervals.back().max() + 1, 50);
	intervals.emplace_back(intervals.back().max() + 1, 60);
	intervals.emplace_back(intervals.back().max() + 1, 81);
	intervals.emplace_back(intervals.back().max() + 1, 85);
	intervals.emplace_back(intervals.back().max() + 1, 90);
	intervals.emplace_back(intervals.back().max() + 1, 99);
	intervals.emplace_back(intervals.back().max() + 1,
	                       std::numeric_limits<uint32_t>::max());

	search.reserve(intervals.size());
	for (auto & r : intervals)
	{
		search.push_back(r.max());
		printf("%u\n", r.max());
	}

	auto r = find_interval(search, 2);
	printf("%u -> [%u-%u]\n", 2, r.min(), r.max());
	r = find_interval2(search, 2);

	r = find_interval(search, 80);
	printf("%u -> [%u-%u]\n", 80, r.min(), r.max());
	r = find_interval2(search, 80);

	r = find_interval(search, 24);
	printf("%u -> [%u-%u]\n", 24, r.min(), r.max());
	r = find_interval2(search, 24);

	r = find_interval2(search, 2000);

	return 0;
}
<commit_msg>More fun with intervals<commit_after>#include <cstdio>
#include <cstdint>
#include <vector>
#include <limits>

//////////////////////////////////////////////////////////////////////
// Represents the range [low,high]
template <typename VAL_T>
class value_range
{
 public:
	typedef VAL_T value_type;
	typedef std::size_t size_type;

	value_range() : begin(0) , end(0) { }

	value_range(const value_type & low, const value_type & high)
	  : begin(low) , end(high) { }

/*
	value_range(const value_range & other) = default;
	value_range(value_range && other) = default;
	~value_range() = default;
*/

	value_type & min() { return begin; }
	const value_type & min() const { return begin; }

	value_type & max() { return end; }
	const value_type & max() const { return end; }

	size_type size() const { return (end - begin); }

	bool intersects(const value_range & other)
	{
		return (  ( other.begin >= begin && other.begin <= end )
		       || ( other.end >= begin   && other.end <= end )
		       || ( begin >= other.begin && begin <= other.end )
		       || ( end >= other.begin   && end <= other.end ) );
	}

	bool operator == (const value_range & other)
		{ return ( (begin == other.begin) && (end == other.end) ); }

 private:
	value_type begin, end;
};

//////////////////////////////////////////////////////////////////////
template <typename T>
value_range<T> find_interval(const std::vector<T> & interval_list, T val)
{
	int i = 1;
	value_range<T> retval { std::numeric_limits<T>::min(),
	                               std::numeric_limits<T>::max() };

//	uint32_t last = std::numeric_limits<uint32_t>::min();

	for (auto & x : interval_list)
	{
		++i;
		if (val <= x)
		{
			retval.max() = x;
			break;
		}

		retval.min() = x + 1;
	}
	printf("--> i = %d\n", i);
	return retval;
}

//////////////////////////////////////////////////////////////////////
template <typename T>
value_range<T> find_interval2(const std::vector<T> & list, T val)
{
	value_range<T> retval { std::numeric_limits<T>::min(),
		                    std::numeric_limits<T>::max() };
	int i = 1;

	if (list.empty())
	{
		// do nothing
	} else if (val <= list.front())
	{
		retval.max() = list.front();
	} else if (val > list.back())
	{
		retval.min() = list.back() + 1;
		++i;
	} else
	{
		++i;
		++i;
		size_t lower = 0;
		size_t upper = (list.size() - 1);
		size_t middle;
		while (upper - lower > 1)
		{
			middle = ((upper + lower) >> 1);

			if (val <= list[middle])
				upper = middle;
			else
				lower = middle;

			++i;
		}
		retval = value_range<T>{list[lower] + 1, list[upper]};
	}

	printf("--> i = %d\n", i);

	return retval;
}

//////////////////////////////////////////////////////////////////////
int main()
{
	std::vector<value_range<uint32_t>> intervals;
	std::vector<uint32_t> search;
	std::vector<uint32_t> search2;

	intervals.emplace_back(0, 9);
	intervals.emplace_back(intervals.back().max() + 1, 15);
	intervals.emplace_back(intervals.back().max() + 1, 21);
	intervals.emplace_back(intervals.back().max() + 1, 23);
	intervals.emplace_back(intervals.back().max() + 1, 24);
	intervals.emplace_back(intervals.back().max() + 1, 50);
	intervals.emplace_back(intervals.back().max() + 1, 60);
	intervals.emplace_back(intervals.back().max() + 1, 81);
	intervals.emplace_back(intervals.back().max() + 1, 85);
	intervals.emplace_back(intervals.back().max() + 1, 90);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
	intervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);
/*
	intervals.emplace_back(intervals.back().max() + 1,
	                       std::numeric_limits<uint32_t>::max());
*/

	printf("SIZE = %zu\n", intervals.size());
	search.reserve(intervals.size());
	search2.reserve(intervals.size() + 1);
	//search2.push_back(0);
	for (auto & r : intervals)
	{
		search.push_back(r.max());
		search2.push_back(r.max());
		printf("%u\n", r.max());
	}

	auto r = find_interval(search, 2u);
	printf("%u -> [%u-%u]\n", 2u, r.min(), r.max());
	r = find_interval2(search2, 2u);
	printf("%u -> [%u-%u]\n", 2u, r.min(), r.max());

	r = find_interval(search, 80u);
	printf("%u -> [%u-%u]\n", 80u, r.min(), r.max());
	r = find_interval2(search2, 80u);
	printf("%u -> [%u-%u]\n", 80u, r.min(), r.max());

	r = find_interval(search, 24u);
	printf("%u -> [%u-%u]\n", 24u, r.min(), r.max());
	r = find_interval2(search2, 24u);
	printf("%u -> [%u-%u]\n", 24u, r.min(), r.max());

	r = find_interval(search, 2000u);
	printf("%u -> [%u-%u]\n", 2000u, r.min(), r.max());
	r = find_interval2(search2, 2000u);
	printf("%u -> [%u-%u]\n", 2000u, r.min(), r.max());

	r = find_interval(search, 125u);
	printf("%u -> [%u-%u]\n", 125u, r.min(), r.max());
	r = find_interval2(search2, 125u);
	printf("%u -> [%u-%u]\n", 125u, r.min(), r.max());

	r = find_interval(search, 4294967295u);
	printf("%u -> [%u-%u]\n", 4294967295u, r.min(), r.max());
	r = find_interval2(search2, 4294967295u);
	printf("%u -> [%u-%u]\n", 4294967295u, r.min(), r.max());

	return 0;
}
<|endoftext|>