<commit_before>#ifndef H_GIL_SIMPLE_VIEW
#define H_GIL_SIMPLE_VIEW

namespace boost{ namespace gil{ struct image_view; }}

namespace gil_simple_view
{
	enum struct channel_type
	{
		bits8  ,	//  uint8_t
		bits8s ,	//   int8_t
		bits16 ,	// uint16_t
		bits16s,	//  int16_t
		bits32 ,	// uint32_t
		bits32s,	//  int32_t
		bits32f 	//   double
	};

	enum struct color_type
	{
		gray_t   ,	// [gray]scale
		alpha_t  ,	// [a]rgb
		red_t    ,	// a[r]gb
		green_t  ,	// ar[g]b
		blue_t   ,	// arg[b]
		cyan_t   ,	// [c]myk
		magenta_t,	// c[m]yk
		yellow_t ,	// cm[y]k
		black_t   	// cmy[k]
	};

	namespace color_space_type
	{
		std::vector<color_type> gray({ color_type::gray_t });
		std::vector<color_type> rgb ({ color_type::red_t  , color_type::green_t  , color_type::blue_t  });
		std::vector<color_type> bgr ({ color_type::blue_t , color_type::green_t  , color_type::red_t   });
		std::vector<color_type> argb({ color_type::alpha_t, color_type::red_t    , color_type::green_t , color_type::blue_t  });
		std::vector<color_type> abgr({ color_type::alpha_t, color_type::blue_t   , color_type::green_t , color_type::red_t   });
		std::vector<color_type> rgba({ color_type::red_t  , color_type::green_t  , color_type::blue_t  , color_type::alpha_t });
		std::vector<color_type> bgra({ color_type::blue_t , color_type::green_t  , color_type::red_t   , color_type::alpha_t });
		std::vector<color_type> cmyk({ color_type::cyan_t , color_type::magenta_t, color_type::yellow_t, color_type::black_t };
	}

	struct simple_view
	{
		channel_type channel;
		std::vector<color_type> color_space;
		boost::gil::image_view* src_view;
	};

	// check channel type bit-wise
	bool is_8bit      (simple_view& v);
	bool is_16bit     (simple_view& v);
	bool is_32bit     (simple_view& v);

	// check channel type representation-wise
	bool is_unsigned  (simple_view& v);
	bool is_signed    (simple_view& v);
	bool is_float     (simple_view& v);

	// check color space type disregarding the order
	bool is_grayscale (simple_view& v);
	bool is_rgb       (simple_view& v);
	bool is_argb      (simple_view& v);
	bool is_cmyk      (simple_view& v);

	// create a simple_view from a boost::gil view
	template<typename T> simple_view create_simple_view (T& v);

	template<typename L> simple_view create_simple_view (boost::gil::image_view<L>& v);

	simple_view create_simple_view (boost::gil::image_view<gray8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<rgb8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<bgr8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<argb8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<abgr8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<rgba8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<bgra8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<cmyk8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk32f_loc_t>& v);

}

#endif
<commit_msg>Added include & namespace::scope<commit_after>#ifndef H_GIL_SIMPLE_VIEW
#define H_GIL_SIMPLE_VIEW
#include "boost/gil/gil_all.hpp"

namespace gil_simple_view
{
	enum struct channel_type
	{
		bits8  ,	//  uint8_t
		bits8s ,	//   int8_t
		bits16 ,	// uint16_t
		bits16s,	//  int16_t
		bits32 ,	// uint32_t
		bits32s,	//  int32_t
		bits32f 	//   double
	};

	enum struct color_type
	{
		gray_t   ,	// [gray]scale
		alpha_t  ,	// [a]rgb
		red_t    ,	// a[r]gb
		green_t  ,	// ar[g]b
		blue_t   ,	// arg[b]
		cyan_t   ,	// [c]myk
		magenta_t,	// c[m]yk
		yellow_t ,	// cm[y]k
		black_t   	// cmy[k]
	};

	namespace color_space_type
	{
		std::vector<color_type> gray({ color_type::gray_t });
		std::vector<color_type> rgb ({ color_type::red_t  , color_type::green_t  , color_type::blue_t  });
		std::vector<color_type> bgr ({ color_type::blue_t , color_type::green_t  , color_type::red_t   });
		std::vector<color_type> argb({ color_type::alpha_t, color_type::red_t    , color_type::green_t , color_type::blue_t  });
		std::vector<color_type> abgr({ color_type::alpha_t, color_type::blue_t   , color_type::green_t , color_type::red_t   });
		std::vector<color_type> rgba({ color_type::red_t  , color_type::green_t  , color_type::blue_t  , color_type::alpha_t });
		std::vector<color_type> bgra({ color_type::blue_t , color_type::green_t  , color_type::red_t   , color_type::alpha_t });
		std::vector<color_type> cmyk({ color_type::cyan_t , color_type::magenta_t, color_type::yellow_t, color_type::black_t };
	}

	struct simple_view
	{
		channel_type channel;
		std::vector<color_type> color_space;
		boost::gil::image_view* src_view;
	};

	// check channel type bit-wise
	bool is_8bit      (simple_view& v);
	bool is_16bit     (simple_view& v);
	bool is_32bit     (simple_view& v);

	// check channel type representation-wise
	bool is_unsigned  (simple_view& v);
	bool is_signed    (simple_view& v);
	bool is_float     (simple_view& v);

	// check color space type disregarding the order
	bool is_grayscale (simple_view& v);
	bool is_rgb       (simple_view& v);
	bool is_argb      (simple_view& v);
	bool is_cmyk      (simple_view& v);

	// create a simple_view from a boost::gil view
	template<typename T> simple_view create_simple_view (T& v);

	template<typename L> simple_view create_simple_view (boost::gil::image_view<L>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::gray8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::gray8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::gray16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::gray16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::gray32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::gray32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::gray32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgb8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgb8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgb16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgb16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgb32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgb32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgb32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgr8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgr8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgr16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgr16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgr32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgr32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgr32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::argb8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::argb8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::argb16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::argb16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::argb32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::argb32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::argb32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::abgr8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::abgr8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::abgr16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::abgr16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::abgr32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::abgr32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::abgr32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgba8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgba8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgba16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgba16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgba32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgba32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::rgba32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgra8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgra8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgra16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgra16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgra32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgra32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::bgra32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk8_loc_t  >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk8s_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk16_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk32_loc_t >& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk32f_loc_t>& v);

}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <omp.h>

#include "structuredPack.h"
#include "packer.h"
#include "../boundingBox.h"
#include "../shape.h"

StructuredPack::StructuredPack(Packer *packer)
{
  std::cout << "Initializing StructuredPack..." << std::flush;
  this->packer = packer;
  this->len = packer->len;

  dim = 3;
  if(len[2] < 2) dim = 2;

  state = new int[len[0]*len[1]*len[2]];
  pos = new double[len[0]*len[1]*len[2]*dim];

  if(dim>2)
  {
    #pragma omp parallel for schedule(static)
    for(long k=0; k<len[2]; k++){
      for(long j=0; j<len[1]; j++){
        for(long i=0; i<len[0]; i++){
          state[ID(i,j,k)] = 0;
        }
      }
    }
  } else {
    for(long k=0; k<len[2]; k++){
      #pragma omp parallel for schedule(static)
      for(long j=0; j<len[1]; j++){
        for(long i=0; i<len[0]; i++){
          state[ID(i,j,k)] = 0;
        }
      }
    }
  }

  numParticles = 0;

  positions = NULL;
  states = NULL;

  std::cout << " complete" << std::endl;
}

StructuredPack::~StructuredPack()
{
  delete [] state;
  delete [] pos;
  if(!positions) delete [] positions;
  if(!states) delete [] states;
}

long* StructuredPack::GetIntLength()
{
  return len;
}

int* StructuredPack::GetState()
{
  return state;
}

double* StructuredPack::GetPos()
{
  return pos;
}

long StructuredPack::ID(long i, long j, long k)
{
  return i+j*len[0]+k*len[0]*len[1];
}

long StructuredPack::DimID(long thisDim,long i, long j, long k)
{
  return thisDim+i*dim+j*dim*len[0]+k*dim*len[0]*len[1];
}

void StructuredPack::Process()
{
  MapShapes();
  numParticles = ComputeNumParticles();
  positions = CreatePositions();
  states = CreateStates();

  std::cout << "Processing StructuredPack...complete (" << numParticles << " particles)" << std::endl;;
}

void StructuredPack::MapShape(Shape *shape)
{
  BoundingBox *bb = shape->boundingBox;

  // Convert to StructuredPack indexes
  long *p1 = new long[3];
  long *p2 = new long[3];

  // Get the ijk extent
  // Third argument "floors" the ijk indexes (lower left corner) if true
  // "ceils" the ijk indexes (upper right corner) if false
  packer->Pos2IDX(bb->p1, p1, true);
  packer->Pos2IDX(bb->p2, p2, false);

  std::cout << "Mapping a shape..." << std::flush;

  if(dim>2)
  {
    #pragma omp parallel for schedule(static)
    for(long k=p1[2]; k<p2[2]; k++){
      double thisPos[3];
      for(long j=p1[1]; j<p2[1]; j++){
        for(long i=p1[0]; i<p2[0]; i++){
          packer->IDX2Pos(i,j,k,thisPos);
          if(shape->IsInside(thisPos)){
            state[ID(i,j,k)] = shape->state;
            pos[DimID(0,i,j,k)] = thisPos[0];
            pos[DimID(1,i,j,k)] = thisPos[1];
            if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];
          }
        }
      }
    }
  } else {
    for(long k=p1[2]; k<p2[2]; k++){
      #pragma omp parallel for schedule(static)
      for(long j=p1[1]; j<p2[1]; j++){
        double thisPos[3];
        for(long i=p1[0]; i<p2[0]; i++){
          packer->IDX2Pos(i,j,k,thisPos);
          if(shape->IsInside(thisPos)){
            state[ID(i,j,k)] = shape->state;
            pos[DimID(0,i,j,k)] = thisPos[0];
            pos[DimID(1,i,j,k)] = thisPos[1];
            if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];
          }
        }
      }
    }
  }
    std::cout << " complete" << std::endl;
}

long StructuredPack::ComputeNumParticles(){
  if(numParticles != 0) return numParticles;

  long n = 0;
  long totalIJK = len[0]*len[1]*len[2];
  for(long i=0;i<totalIJK;i++){
    if(state[i]!=0) n++;
  }

  return n;
}
long StructuredPack::getNumParticles()
{
  return numParticles;
}
double* StructuredPack::CreatePositions(){
  double *positions = new double[numParticles*3];

  long totalIJK = len[0]*len[1]*len[2];
  long particle = 0;

  for(long i=0;i<totalIJK;i++){
    if(state[i]!=0){
      long thisIDX = i*dim;
      positions[particle] = pos[thisIDX];
      positions[particle+1] = pos[thisIDX+1];
      if(dim>2)
      {
        positions[particle+2] = pos[thisIDX+2];
      } else {
        positions[particle+2] = 0.0;
      }
      particle+=3;
    }
  }

  return positions;
}

int* StructuredPack::CreateStates()
{
  int *states = new int[numParticles];

  long totalIJK = len[0]*len[1]*len[2];
  long particle = 0;
  for(long i=0;i<totalIJK;i++){
    if(state[i]!=0){
      states[particle] = state[i];
      particle++;
    }
  }

  return states;
}

int StructuredPack::GetDim()
{
  return dim;
}
<commit_msg>+ Fixed a potential bug in 2D<commit_after>#include <iostream>
#include <omp.h>

#include "structuredPack.h"
#include "packer.h"
#include "../boundingBox.h"
#include "../shape.h"

StructuredPack::StructuredPack(Packer *packer)
{
  std::cout << "Initializing StructuredPack..." << std::flush;
  this->packer = packer;
  this->len = packer->len;

  dim = 3;
  if(len[2] < 2) dim = 2;

  state = new int[len[0]*len[1]*len[2]];
  pos = new double[len[0]*len[1]*len[2]*dim];

  if(dim>2)
  {
    #pragma omp parallel for schedule(static)
    for(long k=0; k<len[2]; k++){
      for(long j=0; j<len[1]; j++){
        for(long i=0; i<len[0]; i++){
          state[ID(i,j,k)] = 0;
        }
      }
    }
  } else {
    for(long k=0; k<len[2]; k++){
      #pragma omp parallel for schedule(static)
      for(long j=0; j<len[1]; j++){
        for(long i=0; i<len[0]; i++){
          state[ID(i,j,k)] = 0;
        }
      }
    }
  }

  numParticles = 0;

  positions = NULL;
  states = NULL;

  std::cout << " complete" << std::endl;
}

StructuredPack::~StructuredPack()
{
  delete [] state;
  delete [] pos;
  if(!positions) delete [] positions;
  if(!states) delete [] states;
}

long* StructuredPack::GetIntLength()
{
  return len;
}

int* StructuredPack::GetState()
{
  return state;
}

double* StructuredPack::GetPos()
{
  return pos;
}

long StructuredPack::ID(long i, long j, long k)
{
  return i+j*len[0]+k*len[0]*len[1];
}

long StructuredPack::DimID(long thisDim,long i, long j, long k)
{
  return thisDim+i*dim+j*dim*len[0]+k*dim*len[0]*len[1];
}

void StructuredPack::Process()
{
  MapShapes();
  numParticles = ComputeNumParticles();
  positions = CreatePositions();
  states = CreateStates();

  std::cout << "Processing StructuredPack...complete (" << numParticles << " particles)" << std::endl;;
}

void StructuredPack::MapShape(Shape *shape)
{
  BoundingBox *bb = shape->boundingBox;

  // Convert to StructuredPack indexes
  long *p1 = new long[3];
  long *p2 = new long[3];

  // Get the ijk extent
  // Third argument "floors" the ijk indexes (lower left corner) if true
  // "ceils" the ijk indexes (upper right corner) if false
  packer->Pos2IDX(bb->p1, p1, true);
  packer->Pos2IDX(bb->p2, p2, false);

  std::cout << "Mapping a shape..." << std::flush;

  if(dim>2)
  {
    #pragma omp parallel for schedule(static)
    for(long k=p1[2]; k<p2[2]; k++){
      double thisPos[3];
      for(long j=p1[1]; j<p2[1]; j++){
        for(long i=p1[0]; i<p2[0]; i++){
          packer->IDX2Pos(i,j,k,thisPos);
          if(shape->IsInside(thisPos)){
            state[ID(i,j,k)] = shape->state;
            pos[DimID(0,i,j,k)] = thisPos[0];
            pos[DimID(1,i,j,k)] = thisPos[1];
            if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];
          }
        }
      }
    }
  } else {
    long k = 0;
    #pragma omp parallel for schedule(static)
    for(long j=p1[1]; j<p2[1]; j++){
      double thisPos[3];
      for(long i=p1[0]; i<p2[0]; i++){
        packer->IDX2Pos(i,j,k,thisPos);
        if(shape->IsInside(thisPos)){
          state[ID(i,j,k)] = shape->state;
          pos[DimID(0,i,j,k)] = thisPos[0];
          pos[DimID(1,i,j,k)] = thisPos[1];
          if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];
        }
      }
    }
  }
    std::cout << " complete" << std::endl;
}

long StructuredPack::ComputeNumParticles(){
  if(numParticles != 0) return numParticles;

  long n = 0;
  long totalIJK = len[0]*len[1]*len[2];
  for(long i=0;i<totalIJK;i++){
    if(state[i]!=0) n++;
  }

  return n;
}
long StructuredPack::getNumParticles()
{
  return numParticles;
}
double* StructuredPack::CreatePositions(){
  double *positions = new double[numParticles*3];

  long totalIJK = len[0]*len[1]*len[2];
  long particle = 0;

  for(long i=0;i<totalIJK;i++){
    if(state[i]!=0){
      long thisIDX = i*dim;
      positions[particle] = pos[thisIDX];
      positions[particle+1] = pos[thisIDX+1];
      if(dim>2)
      {
        positions[particle+2] = pos[thisIDX+2];
      } else {
        positions[particle+2] = 0.0;
      }
      particle+=3;
    }
  }

  return positions;
}

int* StructuredPack::CreateStates()
{
  int *states = new int[numParticles];

  long totalIJK = len[0]*len[1]*len[2];
  long particle = 0;
  for(long i=0;i<totalIJK;i++){
    if(state[i]!=0){
      states[particle] = state[i];
      particle++;
    }
  }

  return states;
}

int StructuredPack::GetDim()
{
  return dim;
}
<|endoftext|>


<commit_before>#ifndef CMDSTAN_WRITE_OPENCL_DEVICE_HPP
#define CMDSTAN_WRITE_OPENCL_DEVICE_HPP

#include <stan/callbacks/writer.hpp>
#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl_context.hpp>
#endif
#include <string>

namespace cmdstan {

  void write_opencl_device(stan::callbacks::writer& writer) {
#ifdef STAN_OPENCL
    if((stan::math::opencl_context.platform().size() > 0) && (stan::math::opencl_context.device().size() > 0)) {
        std::stringstream msg_opencl_platform;
        msg_opencl_platform << "opencl_platform = " << stan::math::opencl_context.platform()[0].getInfo<CL_PLATFORM_NAME>();
        writer(msg_opencl_platform.str());
        std::stringstream msg_opencl_device;
        msg_opencl_device << "opencl_platform = " << stan::math::opencl_context.device()[0].getInfo<CL_DEVICE_NAME>();
        writer(msg_opencl_device.str());
    }
#endif
  }

}
#endif
<commit_msg>the second opencl_platform should be opencl_device (#860)<commit_after>#ifndef CMDSTAN_WRITE_OPENCL_DEVICE_HPP
#define CMDSTAN_WRITE_OPENCL_DEVICE_HPP

#include <stan/callbacks/writer.hpp>
#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl_context.hpp>
#endif
#include <string>

namespace cmdstan {

  void write_opencl_device(stan::callbacks::writer& writer) {
#ifdef STAN_OPENCL
    if((stan::math::opencl_context.platform().size() > 0) && (stan::math::opencl_context.device().size() > 0)) {
        std::stringstream msg_opencl_platform;
        msg_opencl_platform << "opencl_platform = " << stan::math::opencl_context.platform()[0].getInfo<CL_PLATFORM_NAME>();
        writer(msg_opencl_platform.str());
        std::stringstream msg_opencl_device;
        msg_opencl_device << "opencl_device = " << stan::math::opencl_context.device()[0].getInfo<CL_DEVICE_NAME>();
        writer(msg_opencl_device.str());
    }
#endif
  }

}
#endif
<|endoftext|>


<commit_before>#include "MidiClock.h"
#include "midi-common.hh"
#include "helpers.h"
// #include "MidiUart.h"

// #define DEBUG_MIDI_CLOCK 0

MidiClockClass::MidiClockClass() {
  init();
  mode = OFF;
  setTempo(120);
  transmit = false;
}

void MidiClockClass::init() {
  state = PAUSED;
  counter = 10000;
  rx_clock = rx_last_clock = 0;
  outdiv96th_counter = 0;
  div96th_counter = indiv96th_counter = 0;
  div32th_counter = indiv32th_counter = 0;
  div16th_counter = indiv16th_counter = 0;
  mod6_counter = inmod6_counter = 0;
  pll_x = 200;
  counter = 10000;
  isInit = false;
}

uint16_t midi_clock_diff(uint16_t old_clock, uint16_t new_clock) {
  if (new_clock >= old_clock)
    return new_clock - old_clock;
  else
    return new_clock + (65535 - old_clock);
}

void MidiClockClass::handleMidiStart() {
  if (transmit)
    MidiUart.sendRaw(MIDI_START);
  init();
  state = STARTING;
  outdiv96th_counter = 0;
  counter = 10000;
}

void MidiClockClass::handleMidiStop() {
  state = PAUSED;
  if (transmit)
    MidiUart.sendRaw(MIDI_STOP);

}

void MidiClockClass::start() {
  if (mode == INTERNAL_MIDI) {
    init();
    state = STARTED;
    if (transmit)
      MidiUart.sendRaw(MIDI_START);
  }
}

void MidiClockClass::stop() {
  if (mode == INTERNAL_MIDI) {
    state = PAUSED;
    if (transmit)
      MidiUart.sendRaw(MIDI_STOP);
  }
}

void MidiClockClass::pause() {
  if (mode == INTERNAL_MIDI) {
    if (state == PAUSED) {
      start();
    } else {
      stop();
    }
  }
}

void MidiClockClass::setTempo(uint16_t _tempo) {
  USE_LOCK();
  SET_LOCK();
  tempo = _tempo;
  //  interval = 62500 / (tempo * 24 / 60);
  interval = (uint32_t)((uint32_t)156250 / tempo) - 16;
  CLEAR_LOCK();
}

void MidiClockClass::handleSongPositionPtr(uint8_t *msg) {
  if (mode == EXTERNAL || mode == EXTERNAL_UART2) {
    uint16_t ptr = (msg[1] & 0x7F) | ((msg[2] & 0x7F) << 7);
    USE_LOCK();
    SET_LOCK();
    indiv96th_counter = ptr;
    indiv32th_counter = ptr / 3;
    indiv16th_counter = ptr / 6;
    inmod6_counter = indiv96th_counter % 6;
    CLEAR_LOCK();
  }
}

void MidiClockClass::setSongPositionPtr(uint16_t pos) {
  div96th_counter = pos;
  div32th_counter = pos / 3;
  div16th_counter = pos / 6;
  mod6_counter = pos % 6;
  if (transmit) {
    uint8_t msg[3] = { MIDI_SONG_POSITION_PTR, 0, 0 };
    msg[1] = pos & 0x7F;
    msg[2] = (pos >> 7) & 0x7F;
    MidiUart.sendRaw(msg, 3);
  }
}

void MidiClockClass::updateClockInterval() {
}

/* in interrupt on receiving 0xF8 */
void MidiClockClass::handleClock() {
  uint8_t _mod6_counter = mod6_counter;

  if (transmit)
    MidiUart.putc_immediate(0xF8);

  if (mod6_counter == 5) {
    div16th_counter++;
    div32th_counter++;
  }

  if (mod6_counter == 2) {
    div32th_counter++;
  }

  div96th_counter++;
  mod6_counter++;
  if (mod6_counter == 6)
    mod6_counter = 0;

  if (state == STARTING && div96th_counter >= 1) {
    state = STARTED;
  }

  static bool inCallback = false;
  if (inCallback) {
    return;
  } else {
    inCallback = true;
  }

  sei();

  //    on96Callbacks.call();

  if (_mod6_counter == 0) {
    on16Callbacks.call(div16th_counter);
    on32Callbacks.call(div32th_counter);
  }
  if (_mod6_counter == 3) {
    on32Callbacks.call(div32th_counter);
  }

  inCallback = false;
}

/* in interrupt on timer */
void MidiClockClass::handleTimerInt()  {
}

MidiClockClass MidiClock;
<commit_msg>make led blink for clock<commit_after>#include "MidiClock.h"
#include "midi-common.hh"
#include "helpers.h"
// #include "MidiUart.h"

// #define DEBUG_MIDI_CLOCK 0

MidiClockClass::MidiClockClass() {
  init();
  mode = OFF;
  setTempo(120);
  transmit = false;
}

void MidiClockClass::init() {
  state = PAUSED;
  counter = 10000;
  rx_clock = rx_last_clock = 0;
  outdiv96th_counter = 0;
  div96th_counter = indiv96th_counter = 0;
  div32th_counter = indiv32th_counter = 0;
  div16th_counter = indiv16th_counter = 0;
  mod6_counter = inmod6_counter = 0;
  pll_x = 200;
  counter = 10000;
  isInit = false;
}

uint16_t midi_clock_diff(uint16_t old_clock, uint16_t new_clock) {
  if (new_clock >= old_clock)
    return new_clock - old_clock;
  else
    return new_clock + (65535 - old_clock);
}

void MidiClockClass::handleMidiStart() {
  if (transmit)
    MidiUart.sendRaw(MIDI_START);
  init();
  state = STARTING;
  outdiv96th_counter = 0;
  counter = 10000;
}

void MidiClockClass::handleMidiStop() {
  state = PAUSED;
  if (transmit)
    MidiUart.sendRaw(MIDI_STOP);

}

void MidiClockClass::start() {
  if (mode == INTERNAL_MIDI) {
    init();
    state = STARTED;
    if (transmit)
      MidiUart.sendRaw(MIDI_START);
  }
}

void MidiClockClass::stop() {
  if (mode == INTERNAL_MIDI) {
    state = PAUSED;
    if (transmit)
      MidiUart.sendRaw(MIDI_STOP);
  }
}

void MidiClockClass::pause() {
  if (mode == INTERNAL_MIDI) {
    if (state == PAUSED) {
      start();
    } else {
      stop();
    }
  }
}

void MidiClockClass::setTempo(uint16_t _tempo) {
  USE_LOCK();
  SET_LOCK();
  tempo = _tempo;
  //  interval = 62500 / (tempo * 24 / 60);
  interval = (uint32_t)((uint32_t)156250 / tempo) - 16;
  CLEAR_LOCK();
}

void MidiClockClass::handleSongPositionPtr(uint8_t *msg) {
  if (mode == EXTERNAL || mode == EXTERNAL_UART2) {
    uint16_t ptr = (msg[1] & 0x7F) | ((msg[2] & 0x7F) << 7);
    USE_LOCK();
    SET_LOCK();
    indiv96th_counter = ptr;
    indiv32th_counter = ptr / 3;
    indiv16th_counter = ptr / 6;
    inmod6_counter = indiv96th_counter % 6;
    CLEAR_LOCK();
  }
}

void MidiClockClass::setSongPositionPtr(uint16_t pos) {
  div96th_counter = pos;
  div32th_counter = pos / 3;
  div16th_counter = pos / 6;
  mod6_counter = pos % 6;
  if (transmit) {
    uint8_t msg[3] = { MIDI_SONG_POSITION_PTR, 0, 0 };
    msg[1] = pos & 0x7F;
    msg[2] = (pos >> 7) & 0x7F;
    MidiUart.sendRaw(msg, 3);
  }
}

void MidiClockClass::updateClockInterval() {
}

/* in interrupt on receiving 0xF8 */
void MidiClockClass::handleClock() {
  uint8_t _mod6_counter = mod6_counter;

  if (transmit)
    MidiUart.putc_immediate(0xF8);

  if (mod6_counter == 5) {
    div16th_counter++;
    div32th_counter++;
  }

  if (div16th_counter % 4 == 0) {
    setLed();
  } else {
    clearLed();
  }

  if (mod6_counter == 2) {
    div32th_counter++;
  }

  div96th_counter++;
  mod6_counter++;
  if (mod6_counter == 6)
    mod6_counter = 0;

  if (state == STARTING && div96th_counter >= 1) {
    state = STARTED;
  }

  static bool inCallback = false;
  if (inCallback) {
    return;
  } else {
    inCallback = true;
  }

  sei();

  //    on96Callbacks.call();

  if (_mod6_counter == 0) {
    on16Callbacks.call(div16th_counter);
    on32Callbacks.call(div32th_counter);
  }
  if (_mod6_counter == 3) {
    on32Callbacks.call(div32th_counter);
  }

  inCallback = false;
}

/* in interrupt on timer */
void MidiClockClass::handleTimerInt()  {
}

MidiClockClass MidiClock;
<|endoftext|>


<commit_before>#include "cnn/param-nodes.h"
#include "cnn/tensor.h"
#include "cnn/weight-decay.h"

#include <sstream>

using namespace std;

namespace cnn {

string ConstParameterNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "const_parameters(" << dim << ", " << params << ')';
  return s.str();
}

Dim ConstParameterNode::dim_forward(const vector<Dim>& xs) const {
  assert(xs.size() == 0);
  return dim;
}

void ConstParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
  *fx = *params->values * global_weight_decay.CurrentWeightDecay();
}

void ConstParameterNode::backward_impl(const vector<const Tensor*>& xs,
                    const Tensor& fx,
                    const Tensor& dEdf,
                               unsigned i,
                               Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node: i = " << i << endl;
  abort();
}

string ParameterNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "parameters(" << dim << ", " << params << ')';
  return s.str();
}

Dim ParameterNode::dim_forward(const vector<Dim>& xs) const {
  assert(xs.size() == 0);
  return dim;
}

void ParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
// TODO
//  if (params->not_regularized) {
//    fx.v = params->values.v;
//    return;
//  }
#if HAVE_CUDA
  fx.v = params->values.v;
  cerr << "ParameterNode::forward_impl - implement * global_weight_scale for CUDA\n";
#else
  *fx = *params->values * global_weight_decay.CurrentWeightDecay();
#endif
}

void ParameterNode::backward_impl(const vector<const Tensor*>& xs,
                                  const Tensor& fx,
                                  const Tensor& dEdf,
                                  unsigned i,
                                  Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node: i = " << i << endl;
  abort();
}

void ParameterNode::accumulate_grad(const Tensor& g) {
  params->accumulate_grad(g);
}

string InputNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "constant(" << dim << ')';
  return s.str();
}

Dim InputNode::dim_forward(const vector<Dim>& xs) const {
  return dim;
}

void InputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
#if HAVE_CUDA
  cudaMemcpyAsync(fx.v, &pdata->front(), dim.size() * sizeof(float), cudaMemcpyHostToDevice);
#else
  // TODO memcpy is only necessary if pdata->front() points to an unaligned location
  // need to compute this value
  bool is_input_address_aligned = false;
  if (!is_input_address_aligned) {
    memcpy(fx.v, &pdata->front(), dim.size() * sizeof(float));
  } else {
    fx.v = const_cast<float*>(&pdata->front());
  }
#endif
}

void InputNode::backward_impl(const vector<const Tensor*>& xs,
                    const Tensor& fx,
                    const Tensor& dEdf,
                               unsigned i,
                               Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node\n";
  abort();
}

string ScalarInputNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "scalar_constant(" << pdata << ')';
  return s.str();
}

Dim ScalarInputNode::dim_forward(const vector<Dim>& xs) const {
  return Dim({1});
}

void ScalarInputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
#if HAVE_CUDA
  cudaMemcpyAsync(fx.v, pdata, 1 * sizeof(float), cudaMemcpyHostToDevice);
#else
  fx.v[0] = *pdata;
#endif
}

void ScalarInputNode::backward_impl(const vector<const Tensor*>& xs,
                               const Tensor& fx,
                               const Tensor& dEdf,
                               unsigned i,
                               Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node\n";
  abort();
}

string LookupNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "lookup_parameters(|x|=" << params->values.size() << " --> " << dim << ')';
  return s.str();
}

Dim LookupNode::dim_forward(const vector<Dim>& xs) const {
  return dim;
}

void LookupNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
  if(pindex) {
    assert(*pindex < params->values.size());
    assert (fx.d.batch_elems() == 1);
    *fx = *params->values[*pindex] * global_weight_decay.CurrentWeightDecay();
  } else {
    assert (pindices);
    assert (fx.d.batch_elems() == pindices->size());
    for (unsigned b = 0; b < pindices->size(); ++b) {
      unsigned i = pindices->at(b);
      assert (i < params->values.size());
      float* v = fx.v + fx.d.batch_size() * (b % fx.d.batch_elems());
#if HAVE_CUDA
      cudaMemcpyAsync(v, params->values[i].v, fx.d.batch_size() * sizeof(float), cudaMemcpyDeviceToDevice);
#else
      memcpy(v, params->values[i].v, fx.d.batch_size() * sizeof(float));
#endif
      cerr << "TODO: implement * global_weight_scale\n";
    }
  }
}

void LookupNode::backward_impl(const vector<const Tensor*>& xs,
                            const Tensor& fx,
                            const Tensor& dEdf,
                            unsigned i,
                            Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node\n";
  abort();
}

void LookupNode::accumulate_grad(const Tensor& g) {
  if(pindex) {
    params->accumulate_grad(*pindex, g);
  } else {
    assert (pindices);
    const vector<Tensor>& gb = g.batch_elems();
    for (unsigned b = 0; b < pindices->size(); ++b) {
      unsigned i = pindices->at(b);
      assert (i < params->values.size());
      params->accumulate_grad(i, gb[b]);
    }
  }
}

} // namespace cnn
<commit_msg>fix batch lookup with weight decay<commit_after>#include "cnn/param-nodes.h"
#include "cnn/tensor.h"
#include "cnn/weight-decay.h"

#include <sstream>

using namespace std;

namespace cnn {

string ConstParameterNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "const_parameters(" << dim << ", " << params << ')';
  return s.str();
}

Dim ConstParameterNode::dim_forward(const vector<Dim>& xs) const {
  assert(xs.size() == 0);
  return dim;
}

void ConstParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
  *fx = *params->values * global_weight_decay.CurrentWeightDecay();
}

void ConstParameterNode::backward_impl(const vector<const Tensor*>& xs,
                    const Tensor& fx,
                    const Tensor& dEdf,
                               unsigned i,
                               Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node: i = " << i << endl;
  abort();
}

string ParameterNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "parameters(" << dim << ", " << params << ')';
  return s.str();
}

Dim ParameterNode::dim_forward(const vector<Dim>& xs) const {
  assert(xs.size() == 0);
  return dim;
}

void ParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
// TODO
//  if (params->not_regularized) {
//    fx.v = params->values.v;
//    return;
//  }
#if HAVE_CUDA
  fx.v = params->values.v;
  cerr << "ParameterNode::forward_impl - implement * global_weight_scale for CUDA\n";
#else
  *fx = *params->values * global_weight_decay.CurrentWeightDecay();
#endif
}

void ParameterNode::backward_impl(const vector<const Tensor*>& xs,
                                  const Tensor& fx,
                                  const Tensor& dEdf,
                                  unsigned i,
                                  Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node: i = " << i << endl;
  abort();
}

void ParameterNode::accumulate_grad(const Tensor& g) {
  params->accumulate_grad(g);
}

string InputNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "constant(" << dim << ')';
  return s.str();
}

Dim InputNode::dim_forward(const vector<Dim>& xs) const {
  return dim;
}

void InputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
#if HAVE_CUDA
  cudaMemcpyAsync(fx.v, &pdata->front(), dim.size() * sizeof(float), cudaMemcpyHostToDevice);
#else
  // TODO memcpy is only necessary if pdata->front() points to an unaligned location
  // need to compute this value
  bool is_input_address_aligned = false;
  if (!is_input_address_aligned) {
    memcpy(fx.v, &pdata->front(), dim.size() * sizeof(float));
  } else {
    fx.v = const_cast<float*>(&pdata->front());
  }
#endif
}

void InputNode::backward_impl(const vector<const Tensor*>& xs,
                    const Tensor& fx,
                    const Tensor& dEdf,
                               unsigned i,
                               Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node\n";
  abort();
}

string ScalarInputNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "scalar_constant(" << pdata << ')';
  return s.str();
}

Dim ScalarInputNode::dim_forward(const vector<Dim>& xs) const {
  return Dim({1});
}

void ScalarInputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
#if HAVE_CUDA
  cudaMemcpyAsync(fx.v, pdata, 1 * sizeof(float), cudaMemcpyHostToDevice);
#else
  fx.v[0] = *pdata;
#endif
}

void ScalarInputNode::backward_impl(const vector<const Tensor*>& xs,
                               const Tensor& fx,
                               const Tensor& dEdf,
                               unsigned i,
                               Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node\n";
  abort();
}

string LookupNode::as_string(const vector<string>& arg_names) const {
  ostringstream s;
  s << "lookup_parameters(|x|=" << params->values.size() << " --> " << dim << ')';
  return s.str();
}

Dim LookupNode::dim_forward(const vector<Dim>& xs) const {
  return dim;
}

void LookupNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
  assert(xs.size() == 0);
  if(pindex) {
    assert(*pindex < params->values.size());
    assert (fx.d.batch_elems() == 1);
    fx.vec() = params->values[*pindex].vec() * global_weight_decay.CurrentWeightDecay();
  } else {
    assert (pindices);
    assert (fx.d.batch_elems() == pindices->size());
    for (unsigned b = 0; b < pindices->size(); ++b) {
      unsigned i = pindices->at(b);
      assert (i < params->values.size());
      float* v = fx.v + fx.d.batch_size() * (b % fx.d.batch_elems());
#if HAVE_CUDA
      cudaMemcpyAsync(v, params->values[i].v, fx.d.batch_size() * sizeof(float), cudaMemcpyDeviceToDevice);
#else
      // we should use colwise() instead of memcpy to get rid of the
      // extra multiply by global_weight_decay.CurrentWeightDecay()
      memcpy(v, params->values[i].v, fx.d.batch_size() * sizeof(float));
#endif
    }
    fx.vec() *= global_weight_decay.CurrentWeightDecay();
  }
}

void LookupNode::backward_impl(const vector<const Tensor*>& xs,
                            const Tensor& fx,
                            const Tensor& dEdf,
                            unsigned i,
                            Tensor& dEdxi) const {
  cerr << "called backward() on arity 0 node\n";
  abort();
}

void LookupNode::accumulate_grad(const Tensor& g) {
  if(pindex) {
    params->accumulate_grad(*pindex, g);
  } else {
    assert (pindices);
    const vector<Tensor>& gb = g.batch_elems();
    for (unsigned b = 0; b < pindices->size(); ++b) {
      unsigned i = pindices->at(b);
      assert (i < params->values.size());
      params->accumulate_grad(i, gb[b]);
    }
  }
}

} // namespace cnn
<|endoftext|>


<commit_before>class Solution {
public:
    /**
     * @param heights: a vector of integers
     * @return: an integer
     */
    int maxArea(vector<int> &heights) {
        // write your code here
    }
};

class Solution {
public:
    int maxArea(vector<int> &height) {
        int max = 0, area;
        int start = 0, end = height.size() - 1;
        while (start < end) {
            if (height[start] > height[end]) {
                area = height[end] * (end - start);
                end --;
            } else {
                area = height[start] * (end - start);
                start ++;
            }
            if (area > max) {
                max = area;
            }
        }
        return max;
    }
};<commit_msg>testing 383<commit_after>

class Solution {
public:
    /**
     * @param heights: a vector of integers
     * @return: an integer
     */
    int maxArea(vector<int> &height) {
        int max = 0, area;
        int start = 0, end = height.size() - 1;
        while (start < end) {
            if (height[start] > height[end]) {
                area = height[end] * (end - start);
                end --;
            } else {
                area = height[start] * (end - start);
                start ++;
            }
            if (area > max) {
                max = area;
            }
        }
        return max;
    }
};<|endoftext|>


<commit_before><commit_msg>画像のロードをボディリスト構築後に実施するように修正<commit_after><|endoftext|>


<commit_before><commit_msg>-Werror,-Wshift-sign-overflow<commit_after><|endoftext|>


<commit_before><commit_msg>no message<commit_after><|endoftext|>


<commit_before><commit_msg>Update checkpoints.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>Checkpoint at first 25-btc-reward block (210,000)<commit_after><|endoftext|>


<commit_before>/*
 * File: string_encode.cpp
 * Part of commonpp.
 *
 * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.
 *
 */
#include "commonpp/core/string/encode.hpp"

#include <cstdlib>

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>

namespace commonpp
{
namespace string
{

static const char* HEXTABLE[256] = {
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b",
    "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17",
    "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23",
    "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
    "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b",
    "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47",
    "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53",
    "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
    "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b",
    "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77",
    "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83",
    "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
    "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b",
    "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7",
    "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3",
    "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
    "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb",
    "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
    "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3",
    "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
    "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb",
    "fc", "fd", "fe", "ff",
};

std::string hex_encode(const uint8_t* it, const uint8_t* end)
{
    std::string str;
    str.reserve((end - it) * 2);
    for(; it != end; ++it)
    {
        str += HEXTABLE[*it];
    }

    return str;
}

std::vector<uint8_t> hex_decode(const char* it, const char* end)
{
    std::vector<uint8_t> result;
    auto size = std::distance(it, end);

    if (size % 2 != 0)
    {
        throw std::invalid_argument(
            "the distance between the two iterators must be even");
    }

    result.reserve(size / 2);
    char tmp[3] = {0, 0, 0};
    for (; it != end;)
    {
        tmp[0] = *it++;
        tmp[1] = *it++;
        auto val = std::strtoul(tmp, nullptr, 16);
        uint8_t* data = reinterpret_cast<uint8_t*>(&val);
        result.emplace_back(data[0]);
    }

    return result;
}

namespace bai = boost::archive::iterators;

// inspiration from here: http://stackoverflow.com/a/16775827
std::string base64_encode(const uint8_t* it, const uint8_t* end)
{
    static const char* padding[] = {"", "==", "="};

    using encoder =
        bai::base64_from_binary<bai::transform_width<const char*, 6, 8>>;

    std::string result;
    std::copy(encoder(it), encoder(end), std::back_inserter(result));

    result += padding[std::distance(it, end) % 3];

    return result;
}

std::vector<uint8_t> base64_decode(const char* begin, const char* end)
{
    std::vector<uint8_t> result;

    using decoder =
        bai::transform_width<bai::binary_from_base64<const char*>, 8, 6>;

    auto size = std::distance(begin, end);

    if (!size)
    {
        return result;
    }

    if (begin[size - 1] == '=')
    {
        --size;
        if (size && begin[size - 1] == '=')
        {
            --size;
        }
    }

    std::copy(decoder(begin), decoder(begin + size), std::back_inserter(result));

    return result;
}

} // namespace string
} // namespace commonpp

<commit_msg>Add missing include<commit_after>/*
 * File: string_encode.cpp
 * Part of commonpp.
 *
 * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.
 *
 */
#include "commonpp/core/string/encode.hpp"

#include <cstdlib>
#include <stdexcept>

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>

namespace commonpp
{
namespace string
{

static const char* HEXTABLE[256] = {
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b",
    "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17",
    "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23",
    "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
    "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b",
    "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47",
    "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53",
    "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
    "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b",
    "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77",
    "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83",
    "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
    "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b",
    "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7",
    "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3",
    "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
    "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb",
    "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
    "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3",
    "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
    "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb",
    "fc", "fd", "fe", "ff",
};

std::string hex_encode(const uint8_t* it, const uint8_t* end)
{
    std::string str;
    str.reserve((end - it) * 2);
    for(; it != end; ++it)
    {
        str += HEXTABLE[*it];
    }

    return str;
}

std::vector<uint8_t> hex_decode(const char* it, const char* end)
{
    std::vector<uint8_t> result;
    auto size = std::distance(it, end);

    if (size % 2 != 0)
    {
        throw std::invalid_argument(
            "the distance between the two iterators must be even");
    }

    result.reserve(size / 2);
    char tmp[3] = {0, 0, 0};
    for (; it != end;)
    {
        tmp[0] = *it++;
        tmp[1] = *it++;
        auto val = std::strtoul(tmp, nullptr, 16);
        uint8_t* data = reinterpret_cast<uint8_t*>(&val);
        result.emplace_back(data[0]);
    }

    return result;
}

namespace bai = boost::archive::iterators;

// inspiration from here: http://stackoverflow.com/a/16775827
std::string base64_encode(const uint8_t* it, const uint8_t* end)
{
    static const char* padding[] = {"", "==", "="};

    using encoder =
        bai::base64_from_binary<bai::transform_width<const char*, 6, 8>>;

    std::string result;
    std::copy(encoder(it), encoder(end), std::back_inserter(result));

    result += padding[std::distance(it, end) % 3];

    return result;
}

std::vector<uint8_t> base64_decode(const char* begin, const char* end)
{
    std::vector<uint8_t> result;

    using decoder =
        bai::transform_width<bai::binary_from_base64<const char*>, 8, 6>;

    auto size = std::distance(begin, end);

    if (!size)
    {
        return result;
    }

    if (begin[size - 1] == '=')
    {
        --size;
        if (size && begin[size - 1] == '=')
        {
            --size;
        }
    }

    std::copy(decoder(begin), decoder(begin + size), std::back_inserter(result));

    return result;
}

} // namespace string
} // namespace commonpp

<|endoftext|>


<commit_before>#include <cuda_runtime.h>
#include <stdio.h>
#include <boost/program_options.hpp>
#include <cmath>
#include <random>
#include "common.h"
#include "tee.h"
#include "non_cache.h"
#include "non_cache_gpu.h"
#include "model.h"
#include "curl.h"
#include "weighted_terms.h"
#include "custom_terms.h"
#include "precalculate_gpu.h"
#include "gpucode.h"

//TODO: logging, user-provided random seed

void make_mol(std::vector<atom_params>& atoms, std::vector<smt>& types,
             std::mt19937 engine,
             size_t natoms=0, size_t min_atoms=1, size_t max_atoms=200,
             float max_x=25, float max_y=25, float max_z=25) {

    if (!natoms) {
    //if not provided, randomly generate the number of atoms
        std::uniform_int_distribution<int> natoms_dist(min_atoms, max_atoms+1);
        natoms = natoms_dist(engine);
    }

    //randomly seed reasonable-ish coordinates and types
    //TODO: get charge from type?
    std::uniform_real_distribution<float> coords_dists[3];
    coords_dists[0] = std::uniform_real_distribution<float>(-25, std::nextafter(max_x, FLT_MAX));
    coords_dists[1] = std::uniform_real_distribution<float>(-25, std::nextafter(max_y, FLT_MAX));
    coords_dists[2] = std::uniform_real_distribution<float>(-25, std::nextafter(max_z, FLT_MAX));
    std::uniform_int_distribution<int> charge_dist(-2, 3);
    std::uniform_int_distribution<int> type_dist(0, smina_atom_type::NumTypes-1);

    //set up vector of atoms as well as types
    for (size_t i=0; i<natoms; ++i) {
        atom_params atom;
        atom.charge = charge_dist(engine);
        for (size_t j=0; j<3; ++j)
            atom.coords[j] = coords_dists[j](engine);
        atoms.push_back(atom);
        atoms[i].charge = charge_dist(engine);
        types.push_back(static_cast<smt>(type_dist(engine)));
    }
}

int main() {
    //TODO: include progress bar?
    //set up program options
    std::string logname("log.test");
    auto seed = std::random_device()();
    namespace po = boost::program_options;
    po::options_description inputs("Input");
    inputs.add_options()
        ("seed,s", po::value<unsigned>(&seed), "seed for random number generator")
        ("log", po::value<std::string>(&logname), "specify logfile, default is log.test");
    po::options_description desc, desc_simple;
    desc.add(inputs);
    desc_simple.add(inputs);

    seed = 0;
    //set up c++11 random number engine
    std::mt19937 engine(seed);

    //set up logging
    bool quiet = true;
    tee log(quiet);
    log.init(logname);
    // log << "test" << "\n";

    //set up scoring function
    custom_terms t;
	t.add("gauss(o=0,_w=0.5,_c=8)", -0.035579);
	t.add("gauss(o=3,_w=2,_c=8)", -0.005156);
	t.add("repulsion(o=0,_c=8)", 0.840245);
	t.add("hydrophobic(g=0.5,_b=1.5,_c=8)", -0.035069);
	t.add("non_dir_h_bond(g=-0.7,_b=0,_c=8)", -0.587439);
	t.add("num_tors_div", 5 * 0.05846 / 0.1 - 1);

    //set up a bunch of constants
    const fl approx_factor = 10;
    const fl granularity = 0.375;
    const vec v = vec(10, 10, 10);
    const fl slope = 10;

    weighted_terms wt(&t, t.weights());

    //set up splines
    const precalculate_gpu* gprec = new precalculate_gpu(wt, approx_factor);
    const precalculate_splines* prec = new precalculate_splines(wt, approx_factor);

    //set up fake lig and rec for testing
    std::vector<atom_params> lig_atoms;
    std::vector<smt> lig_types;
    fl max_x = -HUGE_VALF, max_y = -HUGE_VALF, max_z = -HUGE_VALF;
    fl min_x = HUGE_VALF, min_y = HUGE_VALF, min_z = HUGE_VALF;
    make_mol(lig_atoms, lig_types, engine);

    //set up grid
    for (auto& atom : lig_atoms) {
        min_x = std::min(min_x, atom.coords[0]);
        min_y = std::min(min_y, atom.coords[1]);
        min_z = std::min(min_z, atom.coords[2]);
        max_x = std::max(max_x, atom.coords[0]);
        max_y = std::max(max_y, atom.coords[1]);
        max_z = std::max(max_z, atom.coords[2]);
    }

    fl center_x = (max_x + min_x) / 2.0;
    fl center_y = (max_y + min_y) / 2.0;
    fl center_z = (max_z + min_z) / 2.0;
    fl size_x = max_x - min_x;
    fl size_y = max_y - min_y;
    fl size_z = max_z - min_z;

    vec span(size_x, size_y, size_z);
    vec center(center_x, center_y, center_z);
    grid_dims gd;

    for (size_t i; i < 3; ++i) {
        gd[i].n = sz(std::ceil(span[i] / granularity));
        fl real_span = granularity * gd[i].n;
        gd[i].begin = center[i] - real_span / 2;
        gd[i].end = gd[i].begin + real_span;
    }

    //make rec
    std::vector<atom_params> rec_atoms;
    std::vector<smt> rec_types;
    const float cutoff_sqr = prec->cutoff_sqr();
    const float cutoff = std::sqrt(cutoff_sqr);
    make_mol(rec_atoms, rec_types, engine, 0, 10, 2500, max_x + cutoff, max_y +
            cutoff, max_z + cutoff);

    //manually initialize model object
    model* m = new model;
    m->m_num_movable_atoms = lig_atoms.size();
    m->minus_forces = std::vector<vec>(m->m_num_movable_atoms);

    for (size_t i=0; i <lig_atoms.size(); ++i) {
        m->coords.push_back(*(vec*)&lig_atoms[i]);
        m->atoms.push_back(atom());
        m->atoms[i].sm = lig_types[i];
        m->atoms[i].charge = lig_atoms[i].charge;
        m->atoms[i].coords = *(vec*)&lig_atoms[i];
    }

    for (size_t i=0; i<rec_atoms.size(); ++i) {
        m->grid_atoms.push_back(atom());
        m->grid_atoms[i].sm = rec_types[i];
        m->grid_atoms[i].charge = rec_atoms[i].charge;
        m->grid_atoms[i].coords = *(vec*)&rec_atoms[i];
    }

    szv_grid_cache gridcache(*m, cutoff_sqr);
    non_cache* nc = new non_cache(gridcache, gd, prec);
    non_cache_gpu* nc_gpu = new non_cache_gpu(gridcache, gd, gprec, slope);
    m->initialize_gpu();
    grid user_grid;
    gpu_data& gdat = m->gdata;
    cudaMemset(gdat.minus_forces, 0, m->minus_forces.size()*sizeof(decltype(gdat.minus_forces[0])));

    //get intermolecular energy, check agreement
    float g_out = single_point_calc(nc_gpu->info, gdat.coords, gdat.minus_forces, v[0]);
    float c_out = nc->eval_deriv(*m, v[0], user_grid);

    std::cout << g_out << "\n";
    std::cout << c_out << "\n";

    m->deallocate_gpu();
    delete gprec;
    delete prec;
    delete nc;
    delete nc_gpu;
    delete m;
}
<commit_msg>commandline args work but the program doesn't<commit_after>#include <cuda_runtime.h>
#include <stdio.h>
#include <boost/program_options.hpp>
#include <cmath>
#include <random>
#include "common.h"
#include "tee.h"
#include "non_cache.h"
#include "non_cache_gpu.h"
#include "model.h"
#include "curl.h"
#include "weighted_terms.h"
#include "custom_terms.h"
#include "precalculate_gpu.h"
#include "gpucode.h"

//TODO: logging, user-provided random seed

void make_mol(std::vector<atom_params>& atoms, std::vector<smt>& types,
             std::mt19937 engine,
             size_t natoms=0, size_t min_atoms=1, size_t max_atoms=200,
             float max_x=25, float max_y=25, float max_z=25) {

    if (!natoms) {
    //if not provided, randomly generate the number of atoms
        std::uniform_int_distribution<int> natoms_dist(min_atoms, max_atoms+1);
        natoms = natoms_dist(engine);
    }

    //randomly seed reasonable-ish coordinates and types
    //TODO: get charge from type?
    std::uniform_real_distribution<float> coords_dists[3];
    coords_dists[0] = std::uniform_real_distribution<float>(-25, std::nextafter(max_x, FLT_MAX));
    coords_dists[1] = std::uniform_real_distribution<float>(-25, std::nextafter(max_y, FLT_MAX));
    coords_dists[2] = std::uniform_real_distribution<float>(-25, std::nextafter(max_z, FLT_MAX));
    std::uniform_int_distribution<int> charge_dist(-2, 3);
    std::uniform_int_distribution<int> type_dist(0, smina_atom_type::NumTypes-1);

    //set up vector of atoms as well as types
    for (size_t i=0; i<natoms; ++i) {
        atom_params atom;
        atom.charge = charge_dist(engine);
        for (size_t j=0; j<3; ++j)
            atom.coords[j] = coords_dists[j](engine);
        atoms.push_back(atom);
        atoms[i].charge = charge_dist(engine);
        types.push_back(static_cast<smt>(type_dist(engine)));
    }
}

int main(int argc, char* argv[]) {
    //TODO: include progress bar?
    //set up program options
    std::string logname;
    unsigned seed;
    namespace po = boost::program_options;
	po::positional_options_description positional; // remains empty
    po::options_description inputs("Input");
    inputs.add_options()
        ("seed,s", po::value<unsigned>(&seed), "seed for random number generator")
        ("log", po::value<std::string>(&logname), "specify logfile, default is test.log");
    po::options_description desc, desc_simple;
    desc.add(inputs);
    desc_simple.add(inputs);
    po::variables_map vm;
    try
    {
        po::store(
                po::command_line_parser(argc, argv).options(desc)
                .style(
                    po::command_line_style::default_style
                    ^ po::command_line_style::allow_guessing)
                .positional(positional).run(), vm);
        notify(vm);
    } catch (po::error& e)
    {
		std::cerr << "Command line parse error: " << e.what() << '\n'
				<< "\nCorrect usage:\n" << desc_simple << '\n';
		return 1;
	}
    if (!vm.count("seed"))
        seed = std::random_device()();
    if (!vm.count("logname"))
        logname = "test.log";
    //set up c++11 random number engine
    std::mt19937 engine(seed);

    //set up logging
    bool quiet = true;
    tee log(quiet);
    log.init(logname);
    // log << "test" << "\n";

    //set up scoring function
    custom_terms t;
	t.add("gauss(o=0,_w=0.5,_c=8)", -0.035579);
	t.add("gauss(o=3,_w=2,_c=8)", -0.005156);
	t.add("repulsion(o=0,_c=8)", 0.840245);
	t.add("hydrophobic(g=0.5,_b=1.5,_c=8)", -0.035069);
	t.add("non_dir_h_bond(g=-0.7,_b=0,_c=8)", -0.587439);
	t.add("num_tors_div", 5 * 0.05846 / 0.1 - 1);

    //set up a bunch of constants
    const fl approx_factor = 10;
    const fl granularity = 0.375;
    const vec v = vec(10, 10, 10);
    const fl slope = 10;

    weighted_terms wt(&t, t.weights());

    //set up splines
    const precalculate_gpu* gprec = new precalculate_gpu(wt, approx_factor);
    const precalculate_splines* prec = new precalculate_splines(wt, approx_factor);

    //set up fake lig and rec for testing
    std::vector<atom_params> lig_atoms;
    std::vector<smt> lig_types;
    fl max_x = -HUGE_VALF, max_y = -HUGE_VALF, max_z = -HUGE_VALF;
    fl min_x = HUGE_VALF, min_y = HUGE_VALF, min_z = HUGE_VALF;
    make_mol(lig_atoms, lig_types, engine);

    //set up grid
    for (auto& atom : lig_atoms) {
        min_x = std::min(min_x, atom.coords[0]);
        min_y = std::min(min_y, atom.coords[1]);
        min_z = std::min(min_z, atom.coords[2]);
        max_x = std::max(max_x, atom.coords[0]);
        max_y = std::max(max_y, atom.coords[1]);
        max_z = std::max(max_z, atom.coords[2]);
    }

    fl center_x = (max_x + min_x) / 2.0;
    fl center_y = (max_y + min_y) / 2.0;
    fl center_z = (max_z + min_z) / 2.0;
    fl size_x = max_x - min_x;
    fl size_y = max_y - min_y;
    fl size_z = max_z - min_z;

    vec span(size_x, size_y, size_z);
    vec center(center_x, center_y, center_z);
    grid_dims gd;

    for (size_t i; i < 3; ++i) {
        gd[i].n = sz(std::ceil(span[i] / granularity));
        fl real_span = granularity * gd[i].n;
        gd[i].begin = center[i] - real_span / 2;
        gd[i].end = gd[i].begin + real_span;
    }

    //make rec
    std::vector<atom_params> rec_atoms;
    std::vector<smt> rec_types;
    const float cutoff_sqr = prec->cutoff_sqr();
    const float cutoff = std::sqrt(cutoff_sqr);
    make_mol(rec_atoms, rec_types, engine, 0, 10, 2500, max_x + cutoff, max_y +
            cutoff, max_z + cutoff);

    //manually initialize model object
    model* m = new model;
    m->m_num_movable_atoms = lig_atoms.size();
    m->minus_forces = std::vector<vec>(m->m_num_movable_atoms);

    for (size_t i=0; i <lig_atoms.size(); ++i) {
        m->coords.push_back(*(vec*)&lig_atoms[i]);
        m->atoms.push_back(atom());
        m->atoms[i].sm = lig_types[i];
        m->atoms[i].charge = lig_atoms[i].charge;
        m->atoms[i].coords = *(vec*)&lig_atoms[i];
    }

    for (size_t i=0; i<rec_atoms.size(); ++i) {
        m->grid_atoms.push_back(atom());
        m->grid_atoms[i].sm = rec_types[i];
        m->grid_atoms[i].charge = rec_atoms[i].charge;
        m->grid_atoms[i].coords = *(vec*)&rec_atoms[i];
    }

    szv_grid_cache gridcache(*m, cutoff_sqr);
    non_cache* nc = new non_cache(gridcache, gd, prec);
    non_cache_gpu* nc_gpu = new non_cache_gpu(gridcache, gd, gprec, slope);
    m->initialize_gpu();
    grid user_grid;
    gpu_data& gdat = m->gdata;
    cudaMemset(gdat.minus_forces, 0, m->minus_forces.size()*sizeof(decltype(gdat.minus_forces[0])));

    //get intermolecular energy, check agreement
    float g_out = single_point_calc(nc_gpu->info, gdat.coords, gdat.minus_forces, v[0]);
    float c_out = nc->eval_deriv(*m, v[0], user_grid);

    std::cout << g_out << "\n";
    std::cout << c_out << "\n";

    m->deallocate_gpu();
    delete gprec;
    delete prec;
    delete nc;
    delete nc_gpu;
    delete m;
}
<|endoftext|>


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

// CallDAG.h: Implements a call graph DAG of functions to be re-used accross
// analyses, allows to efficiently traverse the functions in topological
// order.

#include "compiler/translator/CallDAG.h"
#include "compiler/translator/InfoSink.h"

// The CallDAGCreator does all the processing required to create the CallDAG
// structure so that the latter contains only the necessary variables.
class CallDAG::CallDAGCreator : public TIntermTraverser
{
  public:
    CallDAGCreator(TInfoSinkBase *info)
        : TIntermTraverser(true, false, true),
          mCreationInfo(info),
          mCurrentFunction(nullptr),
          mCurrentIndex(0)
    {
    }

    InitResult assignIndices()
    {
        int skipped = 0;
        for (auto &it : mFunctions)
        {
            // Skip unimplemented functions
            if (it.second.node)
            {
                InitResult result = assignIndicesInternal(&it.second);
                if (result != INITDAG_SUCCESS)
                {
                    return result;
                }
            }
            else
            {
                skipped++;
            }
        }
        ASSERT(mFunctions.size() == mCurrentIndex + skipped);
        return INITDAG_SUCCESS;
    }

    void fillDataStructures(std::vector<Record> *records, std::map<int, int> *idToIndex)
    {
        ASSERT(records->empty());
        ASSERT(idToIndex->empty());

        records->resize(mCurrentIndex);

        for (auto &it : mFunctions)
        {
            CreatorFunctionData &data = it.second;
            // Skip unimplemented functions
            if (!data.node)
            {
                continue;
            }
            ASSERT(data.index < records->size());
            Record &record = (*records)[data.index];

            record.name = data.name.data();
            record.node = data.node;

            record.callees.reserve(data.callees.size());
            for (auto &callee : data.callees)
            {
                record.callees.push_back(static_cast<int>(callee->index));
            }

            (*idToIndex)[data.node->getFunctionId()] = static_cast<int>(data.index);
        }
    }

  private:

    struct CreatorFunctionData
    {
        CreatorFunctionData()
            : node(nullptr),
              index(0),
              indexAssigned(false),
              visiting(false)
        {
        }

        std::set<CreatorFunctionData*> callees;
        TIntermAggregate *node;
        TString name;
        size_t index;
        bool indexAssigned;
        bool visiting;
    };

    // Aggregates the AST node for each function as well as the name of the functions called by it
    bool visitAggregate(Visit visit, TIntermAggregate *node) override
    {
        switch (node->getOp())
        {
          case EOpPrototype:
            if (visit == PreVisit)
            {
                // Function declaration, create an empty record.
                mFunctions[node->getName()];
            }
            break;
          case EOpFunction:
            {
                // Function definition, create the record if need be and remember the node.
                if (visit == PreVisit)
                {
                    auto it = mFunctions.find(node->getName());

                    if (it == mFunctions.end())
                    {
                        mCurrentFunction = &mFunctions[node->getName()];
                    }
                    else
                    {
                        mCurrentFunction = &it->second;
                    }

                    mCurrentFunction->node = node;
                    mCurrentFunction->name = node->getName();

                }
                else if (visit == PostVisit)
                {
                    mCurrentFunction = nullptr;
                }
                break;
            }
          case EOpFunctionCall:
            {
                // Function call, add the callees
                if (visit == PreVisit)
                {
                    // Do not handle calls to builtin functions
                    if (node->isUserDefined())
                    {
                        auto it = mFunctions.find(node->getName());
                        ASSERT(it != mFunctions.end());

                        // We might be in a top-level function call to set a global variable
                        if (mCurrentFunction)
                        {
                            mCurrentFunction->callees.insert(&it->second);
                        }
                    }
                }
                break;
            }
          default:
            break;
        }
        return true;
    }

    // Recursively assigns indices to a sub DAG
    InitResult assignIndicesInternal(CreatorFunctionData *function)
    {
        ASSERT(function);

        if (!function->node)
        {
            *mCreationInfo << "Undefined function: " << function->name;
            return INITDAG_UNDEFINED;
        }

        if (function->indexAssigned)
        {
            return INITDAG_SUCCESS;
        }

        if (function->visiting)
        {
            if (mCreationInfo)
            {
                *mCreationInfo << "Recursive function call in the following call chain: " << function->name;
            }
            return INITDAG_RECURSION;
        }
        function->visiting = true;

        for (auto &callee : function->callees)
        {
            InitResult result = assignIndicesInternal(callee);
            if (result == INITDAG_RECURSION)
            {
                // We know that there is a recursive function call chain in the AST,
                // print the link of the chain we were processing.
                if (mCreationInfo)
                {
                    *mCreationInfo << " <- " << function->name;
                }
                return INITDAG_RECURSION;
            }
            else if (result == INITDAG_UNDEFINED)
            {
                return INITDAG_UNDEFINED;
            }
        }

        function->index = mCurrentIndex++;
        function->indexAssigned = true;

        function->visiting = false;
        return INITDAG_SUCCESS;
    }

    TInfoSinkBase *mCreationInfo;

    std::map<TString, CreatorFunctionData> mFunctions;
    CreatorFunctionData *mCurrentFunction;
    size_t mCurrentIndex;
};

// CallDAG

CallDAG::CallDAG()
{
}

CallDAG::~CallDAG()
{
}

const size_t CallDAG::InvalidIndex = std::numeric_limits<size_t>::max();

size_t CallDAG::findIndex(const TIntermAggregate *function) const
{
    TOperator op = function->getOp();
    ASSERT(op == EOpPrototype || op == EOpFunction || op == EOpFunctionCall);
    UNUSED_ASSERTION_VARIABLE(op);

    auto it = mFunctionIdToIndex.find(function->getFunctionId());

    if (it == mFunctionIdToIndex.end())
    {
        return InvalidIndex;
    }
    else
    {
        return it->second;
    }
}

const CallDAG::Record &CallDAG::getRecordFromIndex(size_t index) const
{
    ASSERT(index != InvalidIndex && index < mRecords.size());
    return mRecords[index];
}

const CallDAG::Record &CallDAG::getRecord(const TIntermAggregate *function) const
{
    size_t index = findIndex(function);
    ASSERT(index != InvalidIndex && index < mRecords.size());
    return mRecords[index];
}

size_t CallDAG::size() const
{
    return mRecords.size();
}

void CallDAG::clear()
{
    mRecords.clear();
    mFunctionIdToIndex.clear();
}

CallDAG::InitResult CallDAG::init(TIntermNode *root, TInfoSinkBase *info)
{
    CallDAGCreator creator(info);

    // Creates the mapping of functions to callees
    root->traverse(&creator);

    // Does the topological sort and detects recursions
    InitResult result = creator.assignIndices();
    if (result != INITDAG_SUCCESS)
    {
        return result;
    }

    creator.fillDataStructures(&mRecords, &mFunctionIdToIndex);
    return INITDAG_SUCCESS;
}
<commit_msg>Extend the CallDAG info log to report undefined functions<commit_after>//
// Copyright (c) 2002-2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// CallDAG.h: Implements a call graph DAG of functions to be re-used accross
// analyses, allows to efficiently traverse the functions in topological
// order.

#include "compiler/translator/CallDAG.h"
#include "compiler/translator/InfoSink.h"

// The CallDAGCreator does all the processing required to create the CallDAG
// structure so that the latter contains only the necessary variables.
class CallDAG::CallDAGCreator : public TIntermTraverser
{
  public:
    CallDAGCreator(TInfoSinkBase *info)
        : TIntermTraverser(true, false, true),
          mCreationInfo(info),
          mCurrentFunction(nullptr),
          mCurrentIndex(0)
    {
    }

    InitResult assignIndices()
    {
        int skipped = 0;
        for (auto &it : mFunctions)
        {
            // Skip unimplemented functions
            if (it.second.node)
            {
                InitResult result = assignIndicesInternal(&it.second);
                if (result != INITDAG_SUCCESS)
                {
                    *mCreationInfo << "\n";
                    return result;
                }
            }
            else
            {
                skipped++;
            }
        }
        ASSERT(mFunctions.size() == mCurrentIndex + skipped);
        return INITDAG_SUCCESS;
    }

    void fillDataStructures(std::vector<Record> *records, std::map<int, int> *idToIndex)
    {
        ASSERT(records->empty());
        ASSERT(idToIndex->empty());

        records->resize(mCurrentIndex);

        for (auto &it : mFunctions)
        {
            CreatorFunctionData &data = it.second;
            // Skip unimplemented functions
            if (!data.node)
            {
                continue;
            }
            ASSERT(data.index < records->size());
            Record &record = (*records)[data.index];

            record.name = data.name.data();
            record.node = data.node;

            record.callees.reserve(data.callees.size());
            for (auto &callee : data.callees)
            {
                record.callees.push_back(static_cast<int>(callee->index));
            }

            (*idToIndex)[data.node->getFunctionId()] = static_cast<int>(data.index);
        }
    }

  private:

    struct CreatorFunctionData
    {
        CreatorFunctionData()
            : node(nullptr),
              index(0),
              indexAssigned(false),
              visiting(false)
        {
        }

        std::set<CreatorFunctionData*> callees;
        TIntermAggregate *node;
        TString name;
        size_t index;
        bool indexAssigned;
        bool visiting;
    };

    // Aggregates the AST node for each function as well as the name of the functions called by it
    bool visitAggregate(Visit visit, TIntermAggregate *node) override
    {
        switch (node->getOp())
        {
          case EOpPrototype:
            if (visit == PreVisit)
            {
                // Function declaration, create an empty record.
                auto& record = mFunctions[node->getName()];
                record.name = node->getName();
            }
            break;
          case EOpFunction:
            {
                // Function definition, create the record if need be and remember the node.
                if (visit == PreVisit)
                {
                    auto it = mFunctions.find(node->getName());

                    if (it == mFunctions.end())
                    {
                        mCurrentFunction = &mFunctions[node->getName()];
                    }
                    else
                    {
                        mCurrentFunction = &it->second;
                    }

                    mCurrentFunction->node = node;
                    mCurrentFunction->name = node->getName();

                }
                else if (visit == PostVisit)
                {
                    mCurrentFunction = nullptr;
                }
                break;
            }
          case EOpFunctionCall:
            {
                // Function call, add the callees
                if (visit == PreVisit)
                {
                    // Do not handle calls to builtin functions
                    if (node->isUserDefined())
                    {
                        auto it = mFunctions.find(node->getName());
                        ASSERT(it != mFunctions.end());

                        // We might be in a top-level function call to set a global variable
                        if (mCurrentFunction)
                        {
                            mCurrentFunction->callees.insert(&it->second);
                        }
                    }
                }
                break;
            }
          default:
            break;
        }
        return true;
    }

    // Recursively assigns indices to a sub DAG
    InitResult assignIndicesInternal(CreatorFunctionData *function)
    {
        ASSERT(function);

        if (!function->node)
        {
            *mCreationInfo << "Undefined function '" << function->name
                           << ")' used in the following call chain:";
            return INITDAG_UNDEFINED;
        }

        if (function->indexAssigned)
        {
            return INITDAG_SUCCESS;
        }

        if (function->visiting)
        {
            if (mCreationInfo)
            {
                *mCreationInfo << "Recursive function call in the following call chain:" << function->name;
            }
            return INITDAG_RECURSION;
        }
        function->visiting = true;

        for (auto &callee : function->callees)
        {
            InitResult result = assignIndicesInternal(callee);
            if (result != INITDAG_SUCCESS)
            {
                // We know that there is an issue with the call chain in the AST,
                // print the link of the chain we were processing.
                if (mCreationInfo)
                {
                    *mCreationInfo << " <- " << function->name << ")";
                }
                return result;
            }
        }

        function->index = mCurrentIndex++;
        function->indexAssigned = true;

        function->visiting = false;
        return INITDAG_SUCCESS;
    }

    TInfoSinkBase *mCreationInfo;

    std::map<TString, CreatorFunctionData> mFunctions;
    CreatorFunctionData *mCurrentFunction;
    size_t mCurrentIndex;
};

// CallDAG

CallDAG::CallDAG()
{
}

CallDAG::~CallDAG()
{
}

const size_t CallDAG::InvalidIndex = std::numeric_limits<size_t>::max();

size_t CallDAG::findIndex(const TIntermAggregate *function) const
{
    TOperator op = function->getOp();
    ASSERT(op == EOpPrototype || op == EOpFunction || op == EOpFunctionCall);
    UNUSED_ASSERTION_VARIABLE(op);

    auto it = mFunctionIdToIndex.find(function->getFunctionId());

    if (it == mFunctionIdToIndex.end())
    {
        return InvalidIndex;
    }
    else
    {
        return it->second;
    }
}

const CallDAG::Record &CallDAG::getRecordFromIndex(size_t index) const
{
    ASSERT(index != InvalidIndex && index < mRecords.size());
    return mRecords[index];
}

const CallDAG::Record &CallDAG::getRecord(const TIntermAggregate *function) const
{
    size_t index = findIndex(function);
    ASSERT(index != InvalidIndex && index < mRecords.size());
    return mRecords[index];
}

size_t CallDAG::size() const
{
    return mRecords.size();
}

void CallDAG::clear()
{
    mRecords.clear();
    mFunctionIdToIndex.clear();
}

CallDAG::InitResult CallDAG::init(TIntermNode *root, TInfoSinkBase *info)
{
    CallDAGCreator creator(info);

    // Creates the mapping of functions to callees
    root->traverse(&creator);

    // Does the topological sort and detects recursions
    InitResult result = creator.assignIndices();
    if (result != INITDAG_SUCCESS)
    {
        return result;
    }

    creator.fillDataStructures(&mRecords, &mFunctionIdToIndex);
    return INITDAG_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Nathan Binkert
 *          Steve Reinhardt
 */

#include <algorithm>
#include <map>
#include <string>
#include <utility>

#include "base/debug.hh"
#include "base/trace.hh"
#include "config/full_system.hh"
#include "cpu/base.hh"
#include "cpu/pc_event.hh"
#include "cpu/thread_context.hh"
#include "debug/PCEvent.hh"
#include "sim/core.hh"
#include "sim/system.hh"

using namespace std;

PCEventQueue::PCEventQueue()
{}

PCEventQueue::~PCEventQueue()
{}

bool
PCEventQueue::remove(PCEvent *event)
{
    int removed = 0;
    range_t range = equal_range(event);
    for (iterator i = range.first; i != range.second; ++i) {
        if (*i == event) {
            DPRINTF(PCEvent, "PC based event removed at %#x: %s\n",
                    event->pc(), event->descr());
            pc_map.erase(i);
            ++removed;
        }
    }

    return removed > 0;
}

bool
PCEventQueue::schedule(PCEvent *event)
{
    pc_map.push_back(event);
    sort(pc_map.begin(), pc_map.end(), MapCompare());

    DPRINTF(PCEvent, "PC based event scheduled for %#x: %s\n",
            event->pc(), event->descr());

    return true;
}

bool
PCEventQueue::doService(ThreadContext *tc)
{
    Addr pc = tc->instAddr() & ~0x3;
    int serviced = 0;
    range_t range = equal_range(pc);
    for (iterator i = range.first; i != range.second; ++i) {
        // Make sure that the pc wasn't changed as the side effect of
        // another event.  This for example, prevents two invocations
        // of the SkipFuncEvent.  Maybe we should have separate PC
        // event queues for each processor?
        if (pc != (tc->instAddr() & ~0x3))
            continue;

        DPRINTF(PCEvent, "PC based event serviced at %#x: %s\n",
                (*i)->pc(), (*i)->descr());

        (*i)->process(tc);
        ++serviced;
    }

    return serviced > 0;
}

void
PCEventQueue::dump() const
{
    const_iterator i = pc_map.begin();
    const_iterator e = pc_map.end();

    for (; i != e; ++i)
        cprintf("%d: event at %#x: %s\n", curTick(), (*i)->pc(),
                (*i)->descr());
}

PCEventQueue::range_t
PCEventQueue::equal_range(Addr pc)
{
    return std::equal_range(pc_map.begin(), pc_map.end(), pc, MapCompare());
}

BreakPCEvent::BreakPCEvent(PCEventQueue *q, const std::string &desc, Addr addr,
                           bool del)
    : PCEvent(q, desc, addr), remove(del)
{
}

void
BreakPCEvent::process(ThreadContext *tc)
{
    StringWrap name(tc->getCpuPtr()->name() + ".break_event");
    DPRINTFN("break event %s triggered\n", descr());
    Debug::breakpoint();
    if (remove)
        delete this;
}

#if FULL_SYSTEM
void
sched_break_pc_sys(System *sys, Addr addr)
{
    new BreakPCEvent(&sys->pcEventQueue, "debug break", addr, true);
}

void
sched_break_pc(Addr addr)
{
     for (vector<System *>::iterator sysi = System::systemList.begin();
          sysi != System::systemList.end(); ++sysi) {
         sched_break_pc_sys(*sysi, addr);
    }

}
#endif
<commit_msg>CPU: Remove Alpha-specific PC alignment check.<commit_after>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Nathan Binkert
 *          Steve Reinhardt
 */

#include <algorithm>
#include <map>
#include <string>
#include <utility>

#include "base/debug.hh"
#include "base/trace.hh"
#include "config/full_system.hh"
#include "cpu/base.hh"
#include "cpu/pc_event.hh"
#include "cpu/thread_context.hh"
#include "debug/PCEvent.hh"
#include "sim/core.hh"
#include "sim/system.hh"

using namespace std;

PCEventQueue::PCEventQueue()
{}

PCEventQueue::~PCEventQueue()
{}

bool
PCEventQueue::remove(PCEvent *event)
{
    int removed = 0;
    range_t range = equal_range(event);
    for (iterator i = range.first; i != range.second; ++i) {
        if (*i == event) {
            DPRINTF(PCEvent, "PC based event removed at %#x: %s\n",
                    event->pc(), event->descr());
            pc_map.erase(i);
            ++removed;
        }
    }

    return removed > 0;
}

bool
PCEventQueue::schedule(PCEvent *event)
{
    pc_map.push_back(event);
    sort(pc_map.begin(), pc_map.end(), MapCompare());

    DPRINTF(PCEvent, "PC based event scheduled for %#x: %s\n",
            event->pc(), event->descr());

    return true;
}

bool
PCEventQueue::doService(ThreadContext *tc)
{
    // This will fail to break on Alpha PALcode addresses, but that is
    // a rare use case.
    Addr pc = tc->instAddr();
    int serviced = 0;
    range_t range = equal_range(pc);
    for (iterator i = range.first; i != range.second; ++i) {
        // Make sure that the pc wasn't changed as the side effect of
        // another event.  This for example, prevents two invocations
        // of the SkipFuncEvent.  Maybe we should have separate PC
        // event queues for each processor?
        if (pc != tc->instAddr())
            continue;

        DPRINTF(PCEvent, "PC based event serviced at %#x: %s\n",
                (*i)->pc(), (*i)->descr());

        (*i)->process(tc);
        ++serviced;
    }

    return serviced > 0;
}

void
PCEventQueue::dump() const
{
    const_iterator i = pc_map.begin();
    const_iterator e = pc_map.end();

    for (; i != e; ++i)
        cprintf("%d: event at %#x: %s\n", curTick(), (*i)->pc(),
                (*i)->descr());
}

PCEventQueue::range_t
PCEventQueue::equal_range(Addr pc)
{
    return std::equal_range(pc_map.begin(), pc_map.end(), pc, MapCompare());
}

BreakPCEvent::BreakPCEvent(PCEventQueue *q, const std::string &desc, Addr addr,
                           bool del)
    : PCEvent(q, desc, addr), remove(del)
{
}

void
BreakPCEvent::process(ThreadContext *tc)
{
    StringWrap name(tc->getCpuPtr()->name() + ".break_event");
    DPRINTFN("break event %s triggered\n", descr());
    Debug::breakpoint();
    if (remove)
        delete this;
}

#if FULL_SYSTEM
void
sched_break_pc_sys(System *sys, Addr addr)
{
    new BreakPCEvent(&sys->pcEventQueue, "debug break", addr, true);
}

void
sched_break_pc(Addr addr)
{
     for (vector<System *>::iterator sysi = System::systemList.begin();
          sysi != System::systemList.end(); ++sysi) {
         sched_break_pc_sys(*sysi, addr);
    }

}
#endif
<|endoftext|>