<commit_before>#include "stdafx.h"

class Puzzle
{
	AFTexRef tex;
	int panels[16];
	SpriteCommands cmds;
	void TryMove(int x, int y);
public:
	Puzzle();
	~Puzzle();
	void Update();
	void Draw();
};

static const char* puzzleClassName = "Puzzle";
#define GET_PZL \
	Puzzle* p = (Puzzle*)luaL_checkudata(L, 1, puzzleClassName); \
	if (!p) {	\
		return 0;	\
	} \

class PuzzleBinder {
public:
	PuzzleBinder() {
		GetLuaBindFuncContainer().push_back([](lua_State* L) {
			static luaL_Reg methods[] = {
				{ "Update", [](lua_State* L) { GET_PZL p->Update(); return 0; } },
				{ "Draw", [](lua_State* L) { GET_PZL p->Draw(); return 0; } },
				{ "__gc", [](lua_State* L) { GET_PZL p->~Puzzle(); return 0; } },
				{ nullptr, nullptr },
			};
			aflBindClass(L, "Puzzle", methods, [](lua_State* L) { void* u = lua_newuserdata(L, sizeof(Puzzle)); new (u) Puzzle(); return 1; });
		});
	}
} static puzzleBinder;

Puzzle::Puzzle()
{
	tex = afLoadTexture("models/jiji.dds");
	for (int i = 0; i < (int)dimof(panels); i++)
	{
		panels[i] = i;
	}
	panels[0] = -1;
	srand((unsigned int)time(0));
	for (int i = 0; i < 10000; i++)
	{
		TryMove(rand() % 4, rand() % 4);
	}
}

Puzzle::~Puzzle()
{
	afSafeDeleteTexture(tex);
}

void Puzzle::TryMove(int x, int y)
{
	auto TryOne = [&](int xx, int yy) {
		if (xx < 0 || xx >= 4 || yy < 0 || yy >= 4) {
			return;
		}
		if (panels[xx + yy * 4] < 0) {
			std::swap(panels[x + y * 4], panels[xx + yy * 4]);
		}
	};
	TryOne(x, y - 1);
	TryOne(x, y + 1);
	TryOne(x - 1, y);
	TryOne(x + 1, y);
}

void Puzzle::Update()
{
	cmds.clear();
	SpriteCommand cmd;
	cmd.tex = tex;

	const float pitch = 0.25f;

	Vec2 mouse = systemMisc.GetMousePos();
	auto isHit = [&](const Mat& m) {
		Vec3 v = transform(Vec3(mouse.x, mouse.y, 0), inv(m));
		return v.x >= 0 && v.y >= 0 && v.x < 1 && v.y < 1;
	};
	Vec2 scrSize = systemMisc.GetScreenSize();
	MatrixStack m;
	float mini = std::min(scrSize.x, scrSize.y);
	m.Mul(translate((scrSize.x - mini) / 2, (scrSize.y - mini) / 2, 0));
	m.Mul(scale(mini));
	for (int x = 0; x < 4; x++) {
		for (int y = 0; y < 4; y++) {
			int spr = panels[x + y * 4];
			if (spr < 0) {
				continue;
			}
			int xx = spr % 4;
			int yy = spr / 4;
			cmd.quad = Vec4(xx * pitch, yy * pitch, xx * pitch + pitch, yy * pitch + pitch);
			m.Push();
			m.Mul(translate(pitch * x, pitch * y, 0));
			m.Mul(scale(0.25f));
			cmd.matW = m.Get();
			if (isHit(m.Get())) {
				cmd.color = 0xff0000ff;
				if (systemMisc.mouseDown) {
					TryMove(x, y);
				}
			} else {
				cmd.color = 0xffffffff;
			}
			m.Pop();
			cmds.push_back(cmd);
		}
	}
}

void Puzzle::Draw()
{
	spriteRenderer.Draw(afGetCommandList(), cmds);
}
<commit_msg>Remove dependency of MatrixStack.<commit_after>#include "stdafx.h"

class Puzzle
{
	AFTexRef tex;
	int panels[16];
	SpriteCommands cmds;
	void TryMove(int x, int y);
public:
	Puzzle();
	~Puzzle();
	void Update();
	void Draw();
};

static const char* puzzleClassName = "Puzzle";
#define GET_PZL \
	Puzzle* p = (Puzzle*)luaL_checkudata(L, 1, puzzleClassName); \
	if (!p) {	\
		return 0;	\
	} \

class PuzzleBinder {
public:
	PuzzleBinder() {
		GetLuaBindFuncContainer().push_back([](lua_State* L) {
			static luaL_Reg methods[] = {
				{ "Update", [](lua_State* L) { GET_PZL p->Update(); return 0; } },
				{ "Draw", [](lua_State* L) { GET_PZL p->Draw(); return 0; } },
				{ "__gc", [](lua_State* L) { GET_PZL p->~Puzzle(); return 0; } },
				{ nullptr, nullptr },
			};
			aflBindClass(L, "Puzzle", methods, [](lua_State* L) { void* u = lua_newuserdata(L, sizeof(Puzzle)); new (u) Puzzle(); return 1; });
		});
	}
} static puzzleBinder;

Puzzle::Puzzle()
{
	tex = afLoadTexture("models/jiji.dds");
	for (int i = 0; i < (int)dimof(panels); i++)
	{
		panels[i] = i;
	}
	panels[0] = -1;
	srand((unsigned int)time(0));
	for (int i = 0; i < 10000; i++)
	{
		TryMove(rand() % 4, rand() % 4);
	}
}

Puzzle::~Puzzle()
{
	afSafeDeleteTexture(tex);
}

void Puzzle::TryMove(int x, int y)
{
	auto TryOne = [&](int xx, int yy) {
		if (xx < 0 || xx >= 4 || yy < 0 || yy >= 4) {
			return;
		}
		if (panels[xx + yy * 4] < 0) {
			std::swap(panels[x + y * 4], panels[xx + yy * 4]);
		}
	};
	TryOne(x, y - 1);
	TryOne(x, y + 1);
	TryOne(x - 1, y);
	TryOne(x + 1, y);
}

void Puzzle::Update()
{
	cmds.clear();
	SpriteCommand cmd;
	cmd.tex = tex;

	const float pitch = 0.25f;

	Vec2 mouse = systemMisc.GetMousePos();
	auto isHit = [&](const Mat& m) {
		Vec3 v = transform(Vec3(mouse.x, mouse.y, 0), inv(m));
		return v.x >= 0 && v.y >= 0 && v.x < 1 && v.y < 1;
	};
	Vec2 scrSize = systemMisc.GetScreenSize();
	float mini = std::min(scrSize.x, scrSize.y);
	for (int x = 0; x < 4; x++)
	{
		for (int y = 0; y < 4; y++)
		{
			int spr = panels[x + y * 4];
			if (spr < 0)
			{
				continue;
			}
			int xx = spr % 4;
			int yy = spr / 4;
			cmd.quad = Vec4(xx * pitch, yy * pitch, xx * pitch + pitch, yy * pitch + pitch);
			cmd.matW = scale(0.25f) * translate(pitch * x, pitch * y, 0) * scale(mini) * translate((scrSize.x - mini) / 2, (scrSize.y - mini) / 2, 0);
			if (isHit(cmd.matW))
			{
				cmd.color = 0xff0000ff;
				if (systemMisc.mouseDown)
				{
					TryMove(x, y);
				}
			}
			else
			{
				cmd.color = 0xffffffff;
			}
			cmds.push_back(cmd);
		}
	}
}

void Puzzle::Draw()
{
	spriteRenderer.Draw(afGetCommandList(), cmds);
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <unistd.h>

using namespace std;

void writepin(int state) {
  ofstream filehandler;
  string filename = "/dev/shm/pin_12";
  filehandler.open(filename.c_str());
  if (filehandler.is_open()) {
    filehandler << state << endl;
    filehandler.close();
  } else {
    cout << "ERROR: could not write to " << filename << endl;
  }
}

int main() {
  time_t now = time(0);
  struct tm *nowt = localtime(&now);
  unsigned short state = 0, laststate = 0;
  ofstream outhandler;
  ifstream inhandler;
  char buffer[128];
  unsigned short rainprobability = 256 / 4;
  unsigned long rainduration = 0;
  unsigned int rainstartsecond = 0, currentsecond = 0;
  string line;

  // startup
  cout << "starting up ..." << endl;
  cout << "creating rain directory" << endl;
  // mkdir did not work for some strange reason, so I'm lazy
  snprintf(buffer, sizeof(buffer), "mkdir -p /dev/shm/rain/");
  system(buffer);
  // calculate all rain times for the complete year
  // the seed is the actual year so we have persistent
  // states across reboots
  cout << "calculating rain days ... " << endl;
  srand(nowt->tm_year);
  for (int i = 0; i < 365; i++) {
    // cout << i << endl;
    if ((rand() % 255) < rainprobability) {
      state = 1;
      rainduration = rand() % 60 * 3 + 60;
      // we will rain between 13:00 and 18:00
      // so we will never start when the noon light is on
      // heating should recognize rain events and act
      // accordingly
      rainstartsecond = (13 + rand() % 4) * 3600 + rand() % 60 * 60 + rand() % 60;
      rainprobability = 0;
    } else {
      rainduration = 0;
      rainstartsecond = 0;
      rainprobability += 256 / 4;
    }
    snprintf(buffer, sizeof(buffer), "/dev/shm/rain/%d", i);
    outhandler.open(buffer);
    if (outhandler.is_open()) {
      outhandler << rainduration << endl;
      outhandler << rainstartsecond << endl;
      outhandler.close();
    } else {
      cout << "ERROR: could not write to " << buffer << endl;
    }
  }
  cout << "calculating done." << endl;

  // init the file with 0
  writepin(0);

  // now the loop starts :-)
  while (true) {
    now = time(0);
    nowt = localtime(&now);
    currentsecond = nowt->tm_hour * 3600 + nowt->tm_min * 60 + nowt->tm_sec;
    snprintf(buffer, sizeof(buffer), "/dev/shm/rain/%d", nowt->tm_yday);
    inhandler.open(buffer);
    if (inhandler.is_open()) {
      // read two lines from the file and convert them to long
      // the file format is well defined
      getline(inhandler, line);
      rainduration = strtol(line.c_str(), NULL, 10);
      getline(inhandler, line);
      rainstartsecond = strtol(line.c_str(), NULL, 10);
      inhandler.close();

      // check if we should set the pin to 1
      state = 0;
      if (rainduration > 0) {
        if ((currentsecond >= rainstartsecond) && (currentsecond < rainstartsecond + rainduration)) {
          state = 1;
        }
      }

      // cool down for ten seconds every minute
      if ((nowt->tm_sec >= 0) && (nowt->tm_sec < 10)) {
        state = 0;
      }

      // log and actual write of file
      if (laststate != state) {
        cout << "toggling state to " << state << endl;
        laststate = state;
        writepin(state);
      }
    } else {
      cout << "ERROR: could not read from " << buffer << endl;
    }
    // sleep for 10 seconds
    usleep(10000000);
  }
}<commit_msg>years for the raindaemon<commit_after>#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <unistd.h>

using namespace std;

void writepin(int state) {
  ofstream filehandler;
  string filename = "/dev/shm/pin_12";
  filehandler.open(filename.c_str());
  if (filehandler.is_open()) {
    filehandler << state << endl;
    filehandler.close();
  } else {
    cout << "ERROR: could not write to " << filename << endl;
  }
}

void createraindays() {
  // we use the current year as seed
  time_t now = time(0);
  struct tm *nowt = localtime(&now);

  // we will have to do every day of the year
  // and we'll let c++ do the calculation for us
  time_t calctime = time(0);
  struct tm *calctimet;

  // buffer for filename and the actual
  // file handler
  char buffer[128];
  ofstream outhandler;

  // definition of rain times.
  // rainpause = 4 => it will rain about every 4 days
  // raindurationmin/raindurationmax is in seconds
  // rainstarthour/rainstophour should be configured in
  // a way it does not interfere with the noon light
  static unsigned short RAINPROBMAX = 256;
  static unsigned short RAINPAUSE = 4;
  static unsigned short DURATIONMIN = 60;
  static unsigned short DURATIONMAX = 240;
  static unsigned short RAINSTARTOUR = 13;
  static unsigned short RAINSTOPHOUR = 20;

  unsigned short rainprobability = RAINPROBMAX / RAINPAUSE;
  unsigned long rainduration = 0;
  unsigned int rainstartsecond = 0;
  unsigned short state = 0;

  cout << "creating rain directory" << endl;
  // mkdir did not work for some strange reason, so I'm lazy
  snprintf(buffer, sizeof(buffer), "mkdir -p /dev/shm/rain/");
  system(buffer);
  // calculate all rain times for the complete year
  // the seed is the actual year so we have persistent
  // states across reboots
  cout << "calculating rain days ... " << endl;
  srand(nowt->tm_year);
  calctimet = localtime(&calctime);
  calctimet->tm_yday = 0;
  calctimet->tm_hour = 1;
  calctimet->tm_min = 0;
  calctimet->tm_sec = 0;
  calctime = mktime(calctimet);
  while (calctimet->tm_year == nowt->tm_year) {
    // cout << i << endl;
    if ((rand() % RAINPROBMAX) < rainprobability) {
      state = 1;
      rainduration = rand() % (DURATIONMAX - DURATIONMIN) + DURATIONMIN;
      // because we will add a random hour to the calculated value
      // we have to subtract one from the difference of rainstop and
      // rainstart
      rainstartsecond =
          (RAINSTARTOUR + rand() % (RAINSTOPHOUR - RAINSTARTOUR - 1)) * 3600 + rand() % 60 * 60 + rand() % 60;
      rainprobability = 0;
    } else {
      rainduration = 0;
      rainstartsecond = 0;
      rainprobability += RAINPROBMAX / RAINPAUSE;
    }
    snprintf(buffer, sizeof(buffer), "/dev/shm/rain/%d", calctimet->tm_yday);
    outhandler.open(buffer);
    if (outhandler.is_open()) {
      outhandler << rainduration << endl;
      outhandler << rainstartsecond << endl;
      outhandler.close();
    } else {
      cout << "ERROR: could not write to " << buffer << endl;
    }
    // we add two seconds more to each day to
    // compensate for leap seconds. this may be a bit overkill
    // but, hey ...
    // it will not be a problem in the long run, because we only
    // calculate times for one year and we only have 366*2 seconds
    // (leap year) which is less than a day.
    calctime += 86402;
    calctimet = localtime(&calctime);
  }
  cout << "calculating done." << endl;
}

int main() {
  time_t now = time(0);
  struct tm *nowt = localtime(&now);
  time_t start = time(0);
  struct tm *startt = localtime(&start);
  unsigned long rainduration = 0;
  unsigned int rainstartsecond = 0, currentsecond = 0;
  unsigned short state = 0, laststate = 0;
  ifstream inhandler;
  char buffer[128];
  string line;

  // startup
  cout << "starting up ..." << endl;

  // init the file with 0
  writepin(0);

  // now the loop starts :-)
  while (true) {
    now = time(0);
    nowt = localtime(&now);
    // compensate for a new year
    if (startt->tm_year!=nowt->tm_year) {
      createraindays();
    }
    currentsecond = nowt->tm_hour * 3600 + nowt->tm_min * 60 + nowt->tm_sec;
    snprintf(buffer, sizeof(buffer), "/dev/shm/rain/%d", nowt->tm_yday);
    inhandler.open(buffer);
    if (inhandler.is_open()) {
      // read two lines from the file and convert them to long
      // the file format is well defined
      getline(inhandler, line);
      rainduration = strtol(line.c_str(), NULL, 10);
      getline(inhandler, line);
      rainstartsecond = strtol(line.c_str(), NULL, 10);
      inhandler.close();

      // check if we should set the pin to 1
      state = 0;
      if (rainduration > 0) {
        if ((currentsecond >= rainstartsecond) && (currentsecond < rainstartsecond + rainduration)) {
          state = 1;
        }
      }

      // cool down for ten seconds every minute
      if ((nowt->tm_sec >= 0) && (nowt->tm_sec < 10)) {
        state = 0;
      }

      // log and actual write of file
      if (laststate != state) {
        cout << "toggling state to " << state << endl;
        laststate = state;
        writepin(state);
      }
    } else {
      cout << "ERROR: could not read from " << buffer << endl;
      cout << "trying to recalculate rain days" << endl;
      createraindays();
    }
    // sleep for 10 seconds
    usleep(10000000);
  }
}<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include <iostream>

#include <gsl/gsl_multimin.h>
#include <queso/GslVector.h>
#include <queso/VectorSpace.h>
#include <queso/ScalarFunction.h>
#include <queso/GslOptimizer.h>

namespace QUESO {

// We need to extern "C" because gsl needs a pointer to a C function to
// minimize
extern "C" {
  // This evaluate -log posterior
  double c_evaluate(const gsl_vector * x, void * context) {

    BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction =
      *(static_cast<BaseScalarFunction<GslVector, GslMatrix> * >(context));

    GslVector state(objectiveFunction.domainSet().vectorSpace().zeroVector());

    // DM: Doing this copy sucks, but whatever.  It'll do for now.
    for (unsigned int i = 0; i < state.sizeLocal(); i++) {
      state[i] = gsl_vector_get(x, i);
    }

    // Bail early if GSL tries to evaluate outside of the domain
    if (!objectiveFunction.domainSet().contains(state)) {
      return GSL_NAN;
    }

    // Should cache derivative here so we don't a) segfault in the user's code
    // and b) so we don't recompute stuff
    double result = -objectiveFunction.lnValue(state, NULL, NULL, NULL, NULL);

    return result;
  }

  // This evaluates the derivative of -log posterior
  void c_evaluate_derivative(const gsl_vector * x, void * context,
      gsl_vector * derivative) {
    BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction =
      *(static_cast<BaseScalarFunction<GslVector, GslMatrix> * >(context));

    GslVector state(objectiveFunction.domainSet().vectorSpace().zeroVector());
    GslVector deriv(objectiveFunction.domainSet().vectorSpace().zeroVector());

    // DM: Doing this copy sucks, but whatever.  It'll do for now.
    for (unsigned int i = 0; i < state.sizeLocal(); i++) {
      state[i] = gsl_vector_get(x, i);

      // We fill with GSL_NAN and use it as a flag to check later that the user
      // actually fills the derivative vector with stuff
      deriv[i] = GSL_NAN;
    }

    if (!objectiveFunction.domainSet().contains(state)) {
      // Fill derivative with error codes if the point is outside of the
      // domain
      for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
        gsl_vector_set(derivative, i, GSL_NAN);
      }
    }
    else {
      // We should cache the return value here so we don't recompute stuff
      double fx = -objectiveFunction.lnValue(state, NULL, &deriv, NULL, NULL);

      // Decide whether or not we need to do a finite difference based on
      // whether the user actually filled deriv with values that are not
      // GSL_NAN
      //
      // We're currently doing this check every time this function gets called.
      // We could probably pull this logic out of here and put it somewhere
      // where it only happens once
      bool userComputedDerivative = true;
      for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
        // If the user missed out a derivative in any direction, fall back to
        // a finite difference
        if (gsl_isnan(deriv[i])) {
          userComputedDerivative = false;
          break;
        }
      }

      if (userComputedDerivative) {
        for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
          gsl_vector_set(derivative, i, -deriv[i]);  // We need the minus sign
        }
      }
      else {
        // Finite difference step-size
        double h = 1e-4;

        // User did not provide a derivative, so do a finite difference
        for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
          double tempState = state[i];
          state[i] += h;

          // User didn't provide a derivative, so we don't bother passing in
          // the derivative vector again
          double fxph = -objectiveFunction.lnValue(state, NULL, NULL, NULL,
              NULL);

          // Reset the state back to what it was before
          state[i] = tempState;

          // Make sure we didn't do anything dumb and tell gsl if we did
          if (!gsl_isnan(fx) && !gsl_isnan(fxph)) {
            gsl_vector_set(derivative, i, (fxph - fx) / h);
          }
          else {
            gsl_vector_set(derivative, i, GSL_NAN);
          }
        }
      }
    }
  }

  // This evaluates -log posterior and the derivative of -log posterior
  void c_evaluate_with_derivative(const gsl_vector * x, void * context,
      double * f, gsl_vector * derivative) {
    // We don't need to call both of these
    *f = c_evaluate(x, context);
    c_evaluate_derivative(x, context, derivative);
  }
}  // End extern "C"

GslOptimizer::GslOptimizer(
    const BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction)
  : BaseOptimizer(),
    m_objectiveFunction(objectiveFunction)
{
}

GslOptimizer::~GslOptimizer()
{
}

const Vector *
GslOptimizer::minimize(const Vector & initialPoint) {
  size_t iter = 0;
  int status;
  unsigned int dim = this->m_objectiveFunction.domainSet().vectorSpace().
    zeroVector().sizeLocal();

  const gsl_multimin_fdfminimizer_type * T =
    gsl_multimin_fdfminimizer_vector_bfgs2;

  gsl_multimin_fdfminimizer * s =
    gsl_multimin_fdfminimizer_alloc(T, dim);

  gsl_multimin_function_fdf minusLogPosterior;
  minusLogPosterior.n = dim;
  minusLogPosterior.f = &c_evaluate;
  minusLogPosterior.df = &c_evaluate_derivative;
  minusLogPosterior.fdf = &c_evaluate_with_derivative;
  minusLogPosterior.params = (void *)(&(this->m_objectiveFunction));

  // Set initial point
  // DM: The dynamic cast is needed because the abstract base class does not
  // have a pure virtual operator[] method.  We can implement one and remove
  // this dynamic cast in the future.
  const GslVector & gslInitialPoint = dynamic_cast<const GslVector &>(
      initialPoint);
  gsl_vector * x = gsl_vector_alloc(dim);
  for (unsigned int i = 0; i < dim; i++) {
    gsl_vector_set(x, i, gslInitialPoint[i]);
  }

  /*!
   * \todo Allow the user to tweak these hard-coded values
   */
  gsl_multimin_fdfminimizer_set(s, &minusLogPosterior, x, 0.01, 0.1);

  do {
    iter++;
    status = gsl_multimin_fdfminimizer_iterate(s);

    if (status) {
      std::cerr << "Error while GSL does optimisation. "
                << "See below for GSL error type." << std::endl;
      std::cerr << "Gsl error: " << gsl_strerror(status) << std::endl;
      break;
    }

    // TODO: Allow the user to tweak this hard-coded value
    status = gsl_multimin_test_gradient(s->gradient, 1e-3);

  /*!
   * \todo We shouldn't be hard-coding the max number of iterations
   */
  } while (status == GSL_CONTINUE && iter < 100);

  // Get the minimizer
  GslVector * minimizer = new GslVector(this->m_objectiveFunction.domainSet().
      vectorSpace().zeroVector());
  for (unsigned int i = 0; i < dim; i++) {
    (*minimizer)[i] = gsl_vector_get(s->x, i);
  }

  // We're being good human beings and cleaning up the memory we allocated
  gsl_multimin_fdfminimizer_free(s);
  gsl_vector_free(x);

  // Return the minimizer.  That's all she wrote.
  return minimizer;
}

}  // End namespace QUESO
<commit_msg>Refactor GslOptimizer to use getters for params<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include <iostream>

#include <gsl/gsl_multimin.h>
#include <queso/GslVector.h>
#include <queso/VectorSpace.h>
#include <queso/ScalarFunction.h>
#include <queso/GslOptimizer.h>

namespace QUESO {

// We need to extern "C" because gsl needs a pointer to a C function to
// minimize
extern "C" {
  // This evaluate -log posterior
  double c_evaluate(const gsl_vector * x, void * context) {

    BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction =
      *(static_cast<BaseScalarFunction<GslVector, GslMatrix> * >(context));

    GslVector state(objectiveFunction.domainSet().vectorSpace().zeroVector());

    // DM: Doing this copy sucks, but whatever.  It'll do for now.
    for (unsigned int i = 0; i < state.sizeLocal(); i++) {
      state[i] = gsl_vector_get(x, i);
    }

    // Bail early if GSL tries to evaluate outside of the domain
    if (!objectiveFunction.domainSet().contains(state)) {
      return GSL_NAN;
    }

    // Should cache derivative here so we don't a) segfault in the user's code
    // and b) so we don't recompute stuff
    double result = -objectiveFunction.lnValue(state, NULL, NULL, NULL, NULL);

    return result;
  }

  // This evaluates the derivative of -log posterior
  void c_evaluate_derivative(const gsl_vector * x, void * context,
      gsl_vector * derivative) {
    BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction =
      *(static_cast<BaseScalarFunction<GslVector, GslMatrix> * >(context));

    GslVector state(objectiveFunction.domainSet().vectorSpace().zeroVector());
    GslVector deriv(objectiveFunction.domainSet().vectorSpace().zeroVector());

    // DM: Doing this copy sucks, but whatever.  It'll do for now.
    for (unsigned int i = 0; i < state.sizeLocal(); i++) {
      state[i] = gsl_vector_get(x, i);

      // We fill with GSL_NAN and use it as a flag to check later that the user
      // actually fills the derivative vector with stuff
      deriv[i] = GSL_NAN;
    }

    if (!objectiveFunction.domainSet().contains(state)) {
      // Fill derivative with error codes if the point is outside of the
      // domain
      for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
        gsl_vector_set(derivative, i, GSL_NAN);
      }
    }
    else {
      // We should cache the return value here so we don't recompute stuff
      double fx = -objectiveFunction.lnValue(state, NULL, &deriv, NULL, NULL);

      // Decide whether or not we need to do a finite difference based on
      // whether the user actually filled deriv with values that are not
      // GSL_NAN
      //
      // We're currently doing this check every time this function gets called.
      // We could probably pull this logic out of here and put it somewhere
      // where it only happens once
      bool userComputedDerivative = true;
      for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
        // If the user missed out a derivative in any direction, fall back to
        // a finite difference
        if (gsl_isnan(deriv[i])) {
          userComputedDerivative = false;
          break;
        }
      }

      if (userComputedDerivative) {
        for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
          gsl_vector_set(derivative, i, -deriv[i]);  // We need the minus sign
        }
      }
      else {
        // Finite difference step-size
        double h = this->getFiniteDifferenceStepSize();

        // User did not provide a derivative, so do a finite difference
        for (unsigned int i = 0; i < deriv.sizeLocal(); i++) {
          double tempState = state[i];
          state[i] += h;

          // User didn't provide a derivative, so we don't bother passing in
          // the derivative vector again
          double fxph = -objectiveFunction.lnValue(state, NULL, NULL, NULL,
              NULL);

          // Reset the state back to what it was before
          state[i] = tempState;

          // Make sure we didn't do anything dumb and tell gsl if we did
          if (!gsl_isnan(fx) && !gsl_isnan(fxph)) {
            gsl_vector_set(derivative, i, (fxph - fx) / h);
          }
          else {
            gsl_vector_set(derivative, i, GSL_NAN);
          }
        }
      }
    }
  }

  // This evaluates -log posterior and the derivative of -log posterior
  void c_evaluate_with_derivative(const gsl_vector * x, void * context,
      double * f, gsl_vector * derivative) {
    // We don't need to call both of these
    *f = c_evaluate(x, context);
    c_evaluate_derivative(x, context, derivative);
  }
}  // End extern "C"

GslOptimizer::GslOptimizer(
    const BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction)
  : BaseOptimizer(),
    m_objectiveFunction(objectiveFunction)
{
}

GslOptimizer::~GslOptimizer()
{
}

const Vector *
GslOptimizer::minimize(const Vector & initialPoint) {
  size_t iter = 0;
  int status;
  unsigned int dim = this->m_objectiveFunction.domainSet().vectorSpace().
    zeroVector().sizeLocal();

  const gsl_multimin_fdfminimizer_type * T =
    gsl_multimin_fdfminimizer_vector_bfgs2;

  gsl_multimin_fdfminimizer * s =
    gsl_multimin_fdfminimizer_alloc(T, dim);

  gsl_multimin_function_fdf minusLogPosterior;
  minusLogPosterior.n = dim;
  minusLogPosterior.f = &c_evaluate;
  minusLogPosterior.df = &c_evaluate_derivative;
  minusLogPosterior.fdf = &c_evaluate_with_derivative;
  minusLogPosterior.params = (void *)(&(this->m_objectiveFunction));

  // Set initial point
  // DM: The dynamic cast is needed because the abstract base class does not
  // have a pure virtual operator[] method.  We can implement one and remove
  // this dynamic cast in the future.
  const GslVector & gslInitialPoint = dynamic_cast<const GslVector &>(
      initialPoint);
  gsl_vector * x = gsl_vector_alloc(dim);
  for (unsigned int i = 0; i < dim; i++) {
    gsl_vector_set(x, i, gslInitialPoint[i]);
  }

  /*!
   * \todo Allow the user to tweak these hard-coded values
   */
  gsl_multimin_fdfminimizer_set(s, &minusLogPosterior, x, 0.01, 0.1);

  do {
    iter++;
    status = gsl_multimin_fdfminimizer_iterate(s);

    if (status) {
      std::cerr << "Error while GSL does optimisation. "
                << "See below for GSL error type." << std::endl;
      std::cerr << "Gsl error: " << gsl_strerror(status) << std::endl;
      break;
    }

    // TODO: Allow the user to tweak this hard-coded value
    status = gsl_multimin_test_gradient(s->gradient, this->getTolerance());

  /*!
   * \todo We shouldn't be hard-coding the max number of iterations
   */
  } while ((status == GSL_CONTINUE) && (iter < this->getMaxIterations()));

  // Get the minimizer
  GslVector * minimizer = new GslVector(this->m_objectiveFunction.domainSet().
      vectorSpace().zeroVector());
  for (unsigned int i = 0; i < dim; i++) {
    (*minimizer)[i] = gsl_vector_get(s->x, i);
  }

  // We're being good human beings and cleaning up the memory we allocated
  gsl_multimin_fdfminimizer_free(s);
  gsl_vector_free(x);

  // Return the minimizer.  That's all she wrote.
  return minimizer;
}

}  // End namespace QUESO
<|endoftext|>


<commit_before>#ifdef COSMOLOGY

#include"cosmology.h"
#include "../io.h"

Cosmology::Cosmology( void ){}

void Cosmology::Initialize( struct parameters *P, Grav3D &Grav, Particles_3D &Particles){

  chprintf( "Cosmological Simulation\n");

  H0 = P-> H0;
  cosmo_h = H0/100;
  H0 /= 1000;               //[km/s / kpc]
  Omega_M = P-> Omega_M;
  Omega_L = P-> Omega_L;
  Omega_K = 1 - ( Omega_M + Omega_L );

  if(strcmp(P->init, "Read_Grid")==0){
    // Read scale factor vaue from Particles
    current_z = Particles.current_z;
    current_a = Particles.current_a;
  }
  else{
    current_z = P->Init_redshift;
    current_a = 1. / ( current_z + 1 );
  }

  // Set Scale factor in Gravity
  Grav.current_a = current_a;

  // Gravitational Constant in Cosmological Units
  cosmo_G = G_COSMO;

  // Set gravitational constant to use for potential calculation
  Grav.Gconst = cosmo_G;

  max_delta_a = 0.001;
  delta_a = max_delta_a;

  // Initialize Time and set the time conversion
  t_secs = 0;
  time_conversion = KPC;

  // Set Normalization factors
  r_0_dm   = P->xlen/P->nx;
  t_0_dm   = 1. / H0;
  v_0_dm   = r_0_dm / t_0_dm / cosmo_h;
  rho_0_dm = 3*H0*H0 / ( 8*M_PI*cosmo_G ) * Omega_M /cosmo_h/cosmo_h;
  // dens_avrg = 0;

  r_0_gas = 1.0;
  rho_0_gas = 3*H0*H0 / ( 8*M_PI*cosmo_G ) * Omega_M /cosmo_h/cosmo_h;
  t_0_gas = 1/H0*cosmo_h;
  v_0_gas = r_0_gas / t_0_gas;
  phi_0_gas = v_0_gas * v_0_gas;
  p_0_gas = rho_0_gas * v_0_gas * v_0_gas;
  e_0_gas = v_0_gas * v_0_gas;

  chprintf( " H0: %f\n", H0 * 1000 );
  chprintf( " Omega_M: %f\n", Omega_M );
  chprintf( " Omega_L: %f\n", Omega_L );
  chprintf( " Omega_K: %f\n", Omega_K );
  chprintf( " Current_a: %f\n", current_a );
  chprintf( " Current_z: %f\n", current_z );
  chprintf( " rho_0: %f\n", rho_0_gas );
  chprintf( " v_0: %f \n", v_0_gas );
  chprintf( " Max delta_a: %f \n", MAX_DELTA_A);

  Load_Scale_Outputs( P );

}

#endif<commit_msg>Fixed bug on output of first current_z<commit_after>#ifdef COSMOLOGY

#include"cosmology.h"
#include "../io.h"

Cosmology::Cosmology( void ){}

void Cosmology::Initialize( struct parameters *P, Grav3D &Grav, Particles_3D &Particles){

  chprintf( "Cosmological Simulation\n");

  H0 = P-> H0;
  cosmo_h = H0/100;
  H0 /= 1000;               //[km/s / kpc]
  Omega_M = P-> Omega_M;
  Omega_L = P-> Omega_L;
  Omega_K = 1 - ( Omega_M + Omega_L );

  if(strcmp(P->init, "Read_Grid")==0){
    // Read scale factor vaue from Particles
    current_z = Particles.current_z;
    current_a = Particles.current_a;
  }
  else{
    current_z = P->Init_redshift;
    current_a = 1. / ( current_z + 1 );
    Particles.current_z = current_z;
    Particles.current_a = current_a;
  }

  // Set Scale factor in Gravity
  Grav.current_a = current_a;

  // Gravitational Constant in Cosmological Units
  cosmo_G = G_COSMO;

  // Set gravitational constant to use for potential calculation
  Grav.Gconst = cosmo_G;

  max_delta_a = 0.001;
  delta_a = max_delta_a;

  // Initialize Time and set the time conversion
  t_secs = 0;
  time_conversion = KPC;

  // Set Normalization factors
  r_0_dm   = P->xlen/P->nx;
  t_0_dm   = 1. / H0;
  v_0_dm   = r_0_dm / t_0_dm / cosmo_h;
  rho_0_dm = 3*H0*H0 / ( 8*M_PI*cosmo_G ) * Omega_M /cosmo_h/cosmo_h;
  // dens_avrg = 0;

  r_0_gas = 1.0;
  rho_0_gas = 3*H0*H0 / ( 8*M_PI*cosmo_G ) * Omega_M /cosmo_h/cosmo_h;
  t_0_gas = 1/H0*cosmo_h;
  v_0_gas = r_0_gas / t_0_gas;
  phi_0_gas = v_0_gas * v_0_gas;
  p_0_gas = rho_0_gas * v_0_gas * v_0_gas;
  e_0_gas = v_0_gas * v_0_gas;

  chprintf( " H0: %f\n", H0 * 1000 );
  chprintf( " Omega_M: %f\n", Omega_M );
  chprintf( " Omega_L: %f\n", Omega_L );
  chprintf( " Omega_K: %f\n", Omega_K );
  chprintf( " Current_a: %f\n", current_a );
  chprintf( " Current_z: %f\n", current_z );
  chprintf( " rho_0: %f\n", rho_0_gas );
  chprintf( " v_0: %f \n", v_0_gas );
  chprintf( " Max delta_a: %f \n", MAX_DELTA_A);

  Load_Scale_Outputs( P );

}

#endif<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2015 Paul Asmuth
 *   Copyright (c) 2015 Laura Schlimmer, FnordCorp B.V.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stx/stdtypes.h>
#include <stx/io/file.h>
#include <stx/test/unittest.h>
#include <cstable/CSTableWriter.h>
#include <cstable/CSTableReader.h>
#include <cstable/BitPackedIntColumnWriter.h>
#include <cstable/BooleanColumnWriter.h>
#include <cstable/DoubleColumnWriter.h>
#include <cstable/LEB128ColumnWriter.h>
#include <cstable/StringColumnWriter.h>
#include <cstable/UInt32ColumnWriter.h>
#include <cstable/UInt64ColumnWriter.h>

using namespace stx;

UNIT_TEST(CSTableTest);

TEST_CASE(CSTableTest, TestCSTableContainer, [] () {
  const String filename = "/tmp/__fnord__cstabletest1.cstable";
  auto num_records = 10;

  FileUtil::rm(filename);

  RefPtr<cstable::BitPackedIntColumnWriter> column1_writer = mkRef(
    new cstable::BitPackedIntColumnWriter(10, 10));
  RefPtr<cstable::BitPackedIntColumnWriter> column2_writer = mkRef(
    new cstable::BitPackedIntColumnWriter(10, 10));
  cstable::CSTableWriter tbl_writer(filename, num_records);

  tbl_writer.addColumn("key1", column1_writer.get());
  tbl_writer.addColumn("key2", column2_writer.get());
  tbl_writer.commit();

  cstable::CSTableReader tbl_reader(filename);
  EXPECT_EQ(tbl_reader.numRecords(), num_records);
  EXPECT_EQ(tbl_reader.hasColumn("key1"), true);
  EXPECT_EQ(tbl_reader.hasColumn("key2"), true);
});

TEST_CASE(CSTableTest, TestCSTableColumnWriterReader, [] () {
  const String filename = "/tmp/__fnord__cstabletest2.cstable";
  auto num_records = 4000;
  auto rep_max = 1;
  auto def_max = 1;

  FileUtil::rm(filename);

  RefPtr<cstable::BitPackedIntColumnWriter> bitpacked_writer = mkRef(
    new cstable::BitPackedIntColumnWriter(rep_max, def_max));
  RefPtr<cstable::BooleanColumnWriter> boolean_writer = mkRef(
    new cstable::BooleanColumnWriter(rep_max, def_max));
  RefPtr<cstable::DoubleColumnWriter> double_writer = mkRef(
    new cstable::DoubleColumnWriter(rep_max, def_max));
  RefPtr<cstable::LEB128ColumnWriter> leb128_writer = mkRef(
    new cstable::LEB128ColumnWriter(rep_max, def_max));
  RefPtr<cstable::StringColumnWriter> string_writer = mkRef(
    new cstable::StringColumnWriter(rep_max, def_max));
  RefPtr<cstable::UInt32ColumnWriter> uint32_writer = mkRef(
    new cstable::UInt32ColumnWriter(rep_max, def_max));
  RefPtr<cstable::UInt64ColumnWriter> uint64_writer = mkRef(
    new cstable::UInt64ColumnWriter(rep_max, def_max));

  for (auto i = 0; i < num_records; i++) {
    uint8_t boolean_v = i % 2;
    double double_v = i * 1.1;
    uint64_t uint64_v = static_cast<uint64_t>(i);
    const String string_v = "value";

    bitpacked_writer->addDatum(rep_max, def_max, &i, sizeof(i));
    boolean_writer->addDatum(rep_max, def_max, &boolean_v, sizeof(boolean_v));
    double_writer->addDatum(rep_max, def_max, &double_v, sizeof(double_v));
    leb128_writer->addDatum(rep_max, def_max, &i, sizeof(i));
    string_writer->addDatum(rep_max, def_max, &string_v, sizeof(string_v));
    uint32_writer->addDatum(rep_max, def_max, &i, sizeof(i));
    uint64_writer->addDatum(rep_max, def_max, &uint64_v, sizeof(uint64_v));
  }

  cstable::CSTableWriter tbl_writer(filename, num_records);
  tbl_writer.addColumn("bitpacked", bitpacked_writer.get());
  tbl_writer.addColumn("boolean", boolean_writer.get());
  tbl_writer.addColumn("double", double_writer.get());
  tbl_writer.addColumn("leb128", leb128_writer.get());
  tbl_writer.addColumn("string", string_writer.get());
  tbl_writer.addColumn("uint32", uint32_writer.get());
  tbl_writer.addColumn("uint64", uint64_writer.get());
  tbl_writer.commit();

  cstable::CSTableReader tbl_reader(filename);
  auto bitpacked_reader = tbl_reader.getColumnReader("bitpacked");
  auto boolean_reader = tbl_reader.getColumnReader("boolean");
  auto double_reader = tbl_reader.getColumnReader("double");
  auto leb128_reader = tbl_reader.getColumnReader("leb128");
  auto string_reader = tbl_reader.getColumnReader("string");
  auto uint32_reader = tbl_reader.getColumnReader("uint32");
  auto uint64_reader = tbl_reader.getColumnReader("uint64");

  EXPECT_EQ(bitpacked_reader->type() == msg::FieldType::UINT32, true);
  EXPECT_EQ(boolean_reader->type() == msg::FieldType::BOOLEAN, true);
  EXPECT_EQ(double_reader->type() == msg::FieldType::DOUBLE, true);
  EXPECT_EQ(leb128_reader->type() == msg::FieldType::UINT64, true);
  EXPECT_EQ(string_reader->type() == msg::FieldType::STRING, true);
  EXPECT_EQ(uint32_reader->type() == msg::FieldType::UINT32, true);
  EXPECT_EQ(uint64_reader->type() == msg::FieldType::UINT64, true);

  for (auto i = 0; i < num_records; i++) {
    uint64_t rep_level;
    uint64_t def_level;
    size_t size;
    void* data;

    EXPECT_EQ(
      bitpacked_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint32_t*>(data), i);

    EXPECT_EQ(
      boolean_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint8_t*>(data), i % 2);

    EXPECT_EQ(
      double_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<double*>(data), i * 1.1);

    EXPECT_EQ(
      leb128_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint64_t*>(data), i);

    EXPECT_EQ(
      string_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<String*>(data), "value");

    EXPECT_EQ(
      uint32_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint32_t*>(data), i);

    EXPECT_EQ(
      uint64_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint64_t*>(data), static_cast<uint64_t>(i));
  }
});

<commit_msg>use auto for column writer<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2015 Paul Asmuth
 *   Copyright (c) 2015 Laura Schlimmer, FnordCorp B.V.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stx/stdtypes.h>
#include <stx/io/file.h>
#include <stx/test/unittest.h>
#include <cstable/CSTableWriter.h>
#include <cstable/CSTableReader.h>
#include <cstable/BitPackedIntColumnWriter.h>
#include <cstable/BooleanColumnWriter.h>
#include <cstable/DoubleColumnWriter.h>
#include <cstable/LEB128ColumnWriter.h>
#include <cstable/StringColumnWriter.h>
#include <cstable/UInt32ColumnWriter.h>
#include <cstable/UInt64ColumnWriter.h>

using namespace stx;

UNIT_TEST(CSTableTest);

TEST_CASE(CSTableTest, TestCSTableContainer, [] () {
  auto filename = "/tmp/__fnord__cstabletest1.cstable";
  auto num_records = 10;

  FileUtil::rm(filename);

  auto column1_writer = mkRef(new cstable::BitPackedIntColumnWriter(10, 10));
  auto column2_writer = mkRef(new cstable::BitPackedIntColumnWriter(10, 10));
  cstable::CSTableWriter tbl_writer(filename, num_records);

  tbl_writer.addColumn("key1", column1_writer.get());
  tbl_writer.addColumn("key2", column2_writer.get());
  tbl_writer.commit();

  cstable::CSTableReader tbl_reader(filename);
  EXPECT_EQ(tbl_reader.numRecords(), num_records);
  EXPECT_EQ(tbl_reader.hasColumn("key1"), true);
  EXPECT_EQ(tbl_reader.hasColumn("key2"), true);
});

TEST_CASE(CSTableTest, TestCSTableColumnWriterReader, [] () {
  auto filename = "/tmp/__fnord__cstabletest2.cstable";
  auto num_records = 4000;
  auto rep_max = 1;
  auto def_max = 1;

  FileUtil::rm(filename);

  auto bitpacked_writer = mkRef(
    new cstable::BitPackedIntColumnWriter(rep_max, def_max));
  auto boolean_writer = mkRef(
    new cstable::BooleanColumnWriter(rep_max, def_max));
  auto double_writer = mkRef(
    new cstable::DoubleColumnWriter(rep_max, def_max));
  auto leb128_writer = mkRef(
    new cstable::LEB128ColumnWriter(rep_max, def_max));
  auto string_writer = mkRef(
    new cstable::StringColumnWriter(rep_max, def_max));
  auto uint32_writer = mkRef(
    new cstable::UInt32ColumnWriter(rep_max, def_max));
  auto uint64_writer = mkRef(
    new cstable::UInt64ColumnWriter(rep_max, def_max));

  for (auto i = 0; i < num_records; i++) {
    uint8_t boolean_v = i % 2;
    double double_v = i * 1.1;
    uint64_t uint64_v = static_cast<uint64_t>(i);
    const String string_v = "value";

    bitpacked_writer->addDatum(rep_max, def_max, &i, sizeof(i));
    boolean_writer->addDatum(rep_max, def_max, &boolean_v, sizeof(boolean_v));
    double_writer->addDatum(rep_max, def_max, &double_v, sizeof(double_v));
    leb128_writer->addDatum(rep_max, def_max, &i, sizeof(i));
    string_writer->addDatum(rep_max, def_max, &string_v, sizeof(string_v));
    uint32_writer->addDatum(rep_max, def_max, &i, sizeof(i));
    uint64_writer->addDatum(rep_max, def_max, &uint64_v, sizeof(uint64_v));
  }

  cstable::CSTableWriter tbl_writer(filename, num_records);
  tbl_writer.addColumn("bitpacked", bitpacked_writer.get());
  tbl_writer.addColumn("boolean", boolean_writer.get());
  tbl_writer.addColumn("double", double_writer.get());
  tbl_writer.addColumn("leb128", leb128_writer.get());
  tbl_writer.addColumn("string", string_writer.get());
  tbl_writer.addColumn("uint32", uint32_writer.get());
  tbl_writer.addColumn("uint64", uint64_writer.get());
  tbl_writer.commit();

  cstable::CSTableReader tbl_reader(filename);
  auto bitpacked_reader = tbl_reader.getColumnReader("bitpacked");
  auto boolean_reader = tbl_reader.getColumnReader("boolean");
  auto double_reader = tbl_reader.getColumnReader("double");
  auto leb128_reader = tbl_reader.getColumnReader("leb128");
  auto string_reader = tbl_reader.getColumnReader("string");
  auto uint32_reader = tbl_reader.getColumnReader("uint32");
  auto uint64_reader = tbl_reader.getColumnReader("uint64");

  EXPECT_EQ(bitpacked_reader->type() == msg::FieldType::UINT32, true);
  EXPECT_EQ(boolean_reader->type() == msg::FieldType::BOOLEAN, true);
  EXPECT_EQ(double_reader->type() == msg::FieldType::DOUBLE, true);
  EXPECT_EQ(leb128_reader->type() == msg::FieldType::UINT64, true);
  EXPECT_EQ(string_reader->type() == msg::FieldType::STRING, true);
  EXPECT_EQ(uint32_reader->type() == msg::FieldType::UINT32, true);
  EXPECT_EQ(uint64_reader->type() == msg::FieldType::UINT64, true);

  for (auto i = 0; i < num_records; i++) {
    uint64_t rep_level;
    uint64_t def_level;
    size_t size;
    void* data;

    EXPECT_EQ(
      bitpacked_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint32_t*>(data), i);

    EXPECT_EQ(
      boolean_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint8_t*>(data), i % 2);

    EXPECT_EQ(
      double_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<double*>(data), i * 1.1);

    EXPECT_EQ(
      leb128_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint64_t*>(data), i);

    EXPECT_EQ(
      string_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<String*>(data), "value");

    EXPECT_EQ(
      uint32_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint32_t*>(data), i);

    EXPECT_EQ(
      uint64_reader->next(&rep_level, &def_level, &data, &size),
      true);
    EXPECT_EQ(*static_cast<uint64_t*>(data), static_cast<uint64_t>(i));
  }
});

<|endoftext|>


<commit_before>#include <adbase/Utility.hpp>
#include <adbase/Logging.hpp>

int main() {
    adbase::Buffer buffer;

    // write data

    LOG_INFO << "Init readable length: " << buffer.readableBytes();
    LOG_INFO << "Init readable length: " << buffer.writableBytes();
    return 0;
}
<commit_msg>example buffer<commit_after>#include <adbase/Utility.hpp>
#include <adbase/Logging.hpp>

int main() {
    adbase::Buffer buffer;

    // write data
    LOG_INFO << "Init readable length: " << buffer.readableBytes();
    LOG_INFO << "Init writable length: " << buffer.writableBytes();

    const char* c = "bar";
    buffer.append(c, 3);
    LOG_INFO << "input char* readable length: " << buffer.readableBytes();
    LOG_INFO << "input char* writable length: " << buffer.writableBytes();

    std::string str = "hello";
    buffer.append(str);
    LOG_INFO << "input std::string readable length: " << buffer.readableBytes();
    LOG_INFO << "input std::string writable length: " << buffer.writableBytes();

    int64_t int64 = 123;
    buffer.appendInt64(int64);
    LOG_INFO << "input int64_t readable length: " << buffer.readableBytes();
    LOG_INFO << "input int64_t writable length: " << buffer.writableBytes();

    int32_t int32 = 123;
    buffer.appendInt32(int32);
    LOG_INFO << "input int32_t readable length: " << buffer.readableBytes();
    LOG_INFO << "input int32_t writable length: " << buffer.writableBytes();

    int16_t int16 = 123;
    buffer.appendInt16(int16);
    LOG_INFO << "input int16_t readable length: " << buffer.readableBytes();
    LOG_INFO << "input int16_t writable length: " << buffer.writableBytes();

    int8_t int8 = 123;
    buffer.appendInt8(int8);
    LOG_INFO << "input int8_t readable length: " << buffer.readableBytes();
    LOG_INFO << "input int8_t writable length: " << buffer.writableBytes();

    // read data
    LOG_INFO << std::string(buffer.peek(), 3);
    buffer.retrieve(3);
    LOG_INFO << "output char 3 readable length: " << buffer.readableBytes();
    LOG_INFO << "output char 3 writable length: " << buffer.writableBytes();

    LOG_INFO << std::string(buffer.peek(), 5);
    buffer.retrieve(5);
    LOG_INFO << "output char 5 readable length: " << buffer.readableBytes();
    LOG_INFO << "output char 5 writable length: " << buffer.writableBytes();

    LOG_INFO << buffer.readInt64();
    LOG_INFO << "output int64_t readable length: " << buffer.readableBytes();
    LOG_INFO << "output int64_t writable length: " << buffer.writableBytes();

    LOG_INFO << buffer.readInt32();
    LOG_INFO << "output int32_t readable length: " << buffer.readableBytes();
    LOG_INFO << "output int32_t writable length: " << buffer.writableBytes();

    LOG_INFO << buffer.readInt16();
    LOG_INFO << "output int16_t readable length: " << buffer.readableBytes();
    LOG_INFO << "output int16_t writable length: " << buffer.writableBytes();

    LOG_INFO << buffer.readInt8();
    LOG_INFO << "output int8_t readable length: " << buffer.readableBytes();
    LOG_INFO << "output int8_t writable length: " << buffer.writableBytes();
    return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <glowutils/RawFile.h>

#include <algorithm>
#include <fstream>

#include <glow/logging.h>

namespace glowutils
{

template<typename T>
RawFile<T>::RawFile(const std::string & filePath)
:   m_filePath(filePath)
,   m_valid(false)
{
    read();
}

template<typename T>
RawFile<T>::~RawFile()
{
}

template<typename T>
bool RawFile<T>::valid() const
{
    return m_valid;
}

template<typename T>
const T * RawFile<T>::data() const
{
    return &m_data.data()[0];
}

template<typename T>
size_t RawFile<T>::size() const
{
    return m_data.size();
}

template<typename T>
bool RawFile<T>::read()
{
    std::ifstream ifs(m_filePath, std::ios::in | std::ios::binary | std::ios::ate);

    if (!ifs)
    {
        glow::warning() << "Reading from file \"" << m_filePath << "\" failed.";
        return false;
    }

    const std::streampos tmpSize = ifs.tellg();
    if (tmpSize > std::numeric_limits<std::streamsize>::max())
    {
        glow::warning() << "File \"" << m_filePath << "\" is too big to be read.";
        return false;
    }
    const std::streamsize size = static_cast<const std::streamsize>(tmpSize);

    ifs.seekg(0, std::ios::beg);

    m_data.resize(size / sizeof(T));

    ifs.read(reinterpret_cast<char*>(&m_data[0]), size);
    ifs.close();

    m_valid = true;
    return true;
}

} // namespace glowutils
<commit_msg>Fix CID #49512<commit_after>#pragma once

#include <glowutils/RawFile.h>

#include <algorithm>
#include <fstream>

#include <glow/logging.h>

namespace glowutils
{

template<typename T>
RawFile<T>::RawFile(const std::string & filePath)
:   m_filePath(filePath)
,   m_valid(false)
{
    read();
}

template<typename T>
RawFile<T>::~RawFile()
{
}

template<typename T>
bool RawFile<T>::valid() const
{
    return m_valid;
}

template<typename T>
const T * RawFile<T>::data() const
{
    return &m_data.data()[0];
}

template<typename T>
size_t RawFile<T>::size() const
{
    return m_data.size();
}

template<typename T>
bool RawFile<T>::read()
{
    std::ifstream ifs(m_filePath, std::ios::in | std::ios::binary | std::ios::ate);

    if (!ifs)
    {
        glow::warning() << "Reading from file \"" << m_filePath << "\" failed.";
        return false;
    }

    const std::streamsize size = static_cast<const std::streamsize>(ifs.tellg());

    ifs.seekg(0, std::ios::beg);

    m_data.resize(size / sizeof(T));

    ifs.read(reinterpret_cast<char*>(&m_data[0]), size);
    ifs.close();

    m_valid = true;
    return true;
}

} // namespace glowutils
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef ROUTES_SQUIRRELS_HPP
#define ROUTES_SQUIRRELS_HPP
#include <router.hpp>
#include <models/squirrel.hpp>
#include <bucket.hpp>
#include <json.hpp>

namespace acorn {
namespace routes {

class Squirrels : public server::Router {

  using SquirrelBucket = bucket::Bucket<Squirrel>;

public:

  Squirrels(std::shared_ptr<SquirrelBucket> squirrels)
  {
    // GET /
    on_get("/",
    [squirrels] (auto, auto res)
    {
      //printf("[Squirrels@GET:/] Responding with content inside SquirrelBucket\n");
      using namespace rapidjson;
      StringBuffer sb;
      Writer<StringBuffer> writer(sb);
      squirrels->serialize(writer);
      res->send_json(sb.GetString());
    });

    // POST /
    on_post("/",
    [squirrels] (server::Request_ptr req, auto res)
    {
      using namespace json;
      auto json = req->get_attribute<Json_doc>();
      if(!json) {
        res->error({http::Internal_Server_Error, "Server Error", "Server needs to be sprinkled with Parsley"});
      }
      else {
        auto& doc = json->doc();
        try {
          // create an empty model
          acorn::Squirrel s;
          // deserialize it
          s.deserialize(doc);
          // add to bucket
          auto id = squirrels->capture(s);
          assert(id == s.key);
          printf("[Squirrels@POST:/] Squirrel captured: %s\n", s.get_name().c_str());
          // setup the response
          // location to the newly created resource
          using namespace std;
          res->add_header(http::header_fields::Response::Location, req->uri().path()); // return back end loc i guess?
          // status code 201 Created
          res->set_status_code(http::Created);
          // send the created entity as response
          res->send_json(s.json());
        }
        catch(Assert_error e) {
          printf("[Squirrels@POST:/] Assert_error: %s\n", e.what());
          res->error({"Parsing Error", "Could not parse data."});
        }
        catch(bucket::ConstraintException e) {
          printf("[Squirrels@POST:/] ConstraintException: %s\n", e.what());
          res->error({"Constraint Exception", e.what()});
        }
        catch(bucket::BucketException e) {
          printf("[Squirrels@POST:/] BucketException: %s\n", e.what());
          res->error({"Bucket Exception", e.what()});
        }
      }
    });

  }
};

} // < namespace routes
} // < namespace acorn

#endif
<commit_msg>App: Catching exceptions by reference<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef ROUTES_SQUIRRELS_HPP
#define ROUTES_SQUIRRELS_HPP
#include <router.hpp>
#include <models/squirrel.hpp>
#include <bucket.hpp>
#include <json.hpp>

namespace acorn {
namespace routes {

class Squirrels : public server::Router {

  using SquirrelBucket = bucket::Bucket<Squirrel>;

public:

  Squirrels(std::shared_ptr<SquirrelBucket> squirrels)
  {
    // GET /
    on_get("/",
    [squirrels] (auto, auto res)
    {
      //printf("[Squirrels@GET:/] Responding with content inside SquirrelBucket\n");
      using namespace rapidjson;
      StringBuffer sb;
      Writer<StringBuffer> writer(sb);
      squirrels->serialize(writer);
      res->send_json(sb.GetString());
    });

    // POST /
    on_post("/",
    [squirrels] (server::Request_ptr req, auto res)
    {
      using namespace json;
      auto json = req->get_attribute<Json_doc>();
      if(!json) {
        res->error({http::Internal_Server_Error, "Server Error", "Server needs to be sprinkled with Parsley"});
      }
      else {
        auto& doc = json->doc();
        try {
          // create an empty model
          acorn::Squirrel s;
          // deserialize it
          s.deserialize(doc);
          // add to bucket
          auto id = squirrels->capture(s);
          assert(id == s.key);
          printf("[Squirrels@POST:/] Squirrel captured: %s\n", s.get_name().c_str());
          // setup the response
          // location to the newly created resource
          using namespace std;
          res->add_header(http::header_fields::Response::Location, req->uri().path()); // return back end loc i guess?
          // status code 201 Created
          res->set_status_code(http::Created);
          // send the created entity as response
          res->send_json(s.json());
        }
        catch(const Assert_error& e) {
          printf("[Squirrels@POST:/] Assert_error: %s\n", e.what());
          res->error({"Parsing Error", "Could not parse data."});
        }
        catch(const bucket::ConstraintException& e) {
          printf("[Squirrels@POST:/] ConstraintException: %s\n", e.what());
          res->error({"Constraint Exception", e.what()});
        }
        catch(const bucket::BucketException& e) {
          printf("[Squirrels@POST:/] BucketException: %s\n", e.what());
          res->error({"Bucket Exception", e.what()});
        }
      }
    });

  }
};

} // < namespace routes
} // < namespace acorn

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <Leap.h>
#include <unistd.h>
#include <cstdlib>

#include "task_runner.h"

#define CIRCLE_THRESHOLD .4
#define MIN_RADIUS 50 //default 5mm
#define MIN_ARC 3     //default 1.5*pi radians
#define MIN_SWIPE_LENGHT 75  //default 150
#define MIN_VELOCITY 650      //default 1000

using namespace Leap;

const std::string fingerNames[] = {"Thumb", "Index", "Middle", "Ring", "Pinky"};
const std::string boneNames[] = {"Metacarpal", "Proximal", "Middle", "Distal"};
const std::string stateNames[] = {"STATE_INVALID", "STATE_START", "STATE_UPDATE", "STATE_STOP"};

class GestureListener : public Listener {
  public:
    // virtual void onInit(const Controller&);
    virtual void onConnect(const Controller&);
    // virtual void onDisconnect(const Controller&);
    // virtual void onExit(const Controller&);
    virtual void onFrame(const Controller&);
    // virtual void onFocusGained(const Controller&);
    // virtual void onFocusLost(const Controller&);
    // virtual void onDeviceChange(const Controller&);
    // virtual void onServiceConnect(const Controller&);
    // virtual void onServiceDisconnect(const Controller&);

  private:
};

void GestureListener::onConnect(const Controller& controller) {
  std::cout << "Connected" << std::endl;
  controller.enableGesture(Gesture::TYPE_CIRCLE);
  controller.enableGesture(Gesture::TYPE_KEY_TAP);
  controller.enableGesture(Gesture::TYPE_SCREEN_TAP);
  controller.enableGesture(Gesture::TYPE_SWIPE);
}

float circle_counter = 0; //how much of a circle has been made
bool doing_gesture = false;
bool doing_circle = false;
bool doing_swipe = false;

void GestureListener::onFrame(const Controller& controller) {
  // Get the most recent frame
  const Frame frame = controller.frame();

  // report some basic information
  // std::cout << "Frame id: " << frame.id()
  //           << ", timestamp: " << frame.timestamp()
  //           << ", hands: " << frame.hands().count()
  //           << ", fingers: " << frame.fingers().count()
  //           << ", tools: " << frame.tools().count()
  //           << ", gestures: " << frame.gestures().count() << std::endl;

  // get hand info
  HandList hands = frame.hands();
  for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
    // Get the first hand
    const Hand hand = *hl;
    std::string handType = hand.isLeft() ? "Left hand" : "Right hand";
    // std::cout << std::string(2, ' ') << handType << ", id: " << hand.id()
    //           << ", palm position: " << hand.palmPosition() << std::endl;
    // Get the hand's normal vector and direction
    const Vector normal = hand.palmNormal();
    const Vector direction = hand.direction();

    // Calculate the hand's pitch, roll, and yaw angles
    // std::cout << std::string(2, ' ') <<  "pitch: " << direction.pitch() * RAD_TO_DEG << " degrees, "
    //           << "roll: " << normal.roll() * RAD_TO_DEG << " degrees, "
    //           << "yaw: " << direction.yaw() * RAD_TO_DEG << " degrees" << std::endl;

    // Get the Arm bone
    Arm arm = hand.arm();
    // std::cout << std::string(2, ' ') <<  "Arm direction: " << arm.direction()
    //           << " wrist position: " << arm.wristPosition()
    //           << " elbow position: " << arm.elbowPosition() << std::endl;

    // Get index finger
    Finger index = hand.fingers().fingerType(Finger::TYPE_INDEX)[0];

    if (index.isExtended()){
      Vector pos = index.tipPosition();
      Vector dir = index.direction();

      move_mouse(pos,dir);
    }

  }

  // Get tools
  const ToolList tools = frame.tools();
  for (ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) {
    const Tool tool = *tl;
    // std::cout << std::string(2, ' ') <<  "Tool, id: " << tool.id()
    //           << ", position: " << tool.tipPosition()
    //           << ", direction: " << tool.direction() << std::endl;
  }

  // Get gestures
  const GestureList gestures = frame.gestures();

  for (int g = 0; g < gestures.count(); ++g) {
    Gesture gesture = gestures[g];

    switch (gesture.type()) {
      case Gesture::TYPE_CIRCLE:
      {
        CircleGesture circle = gesture;
        std::string clockwiseness;
        bool clockwise = false;

        if (circle.pointable().direction().angleTo(circle.normal()) <= PI/2) {
          clockwiseness = "clockwise";
          clockwise = true;
        } else {
          clockwiseness = "counterclockwise";
          clockwise = false;
        }

        if(circle.pointables().count() > 1){
            break;
        }

        if(circle.state() == Gesture::STATE_START && !doing_gesture){
          doing_gesture = true;
          doing_circle = true;
        }
        // Calculate angle swept since last frame
        float sweptAngle = 0;
        if (circle.state() != Gesture::STATE_START && doing_circle) {

          CircleGesture previousUpdate = CircleGesture(controller.frame(1).gesture(circle.id()));
          sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;
          circle_counter += sweptAngle;

          if(circle_counter >= CIRCLE_THRESHOLD){
            circle_counter = 0;
            circle_action(clockwise);
            std::cout << "scroll" << std::endl;
          }

          std::cout << std::string(2, ' ')
                  << "Circle id: " << gesture.id()
                  << ", state: " << stateNames[gesture.state()]
                  << ", progress: " << circle.progress()
                  << ", radius: " << circle.radius()
                  << ", angle " << sweptAngle * RAD_TO_DEG
                  <<  ", " << clockwiseness
                  << ", timestamp: " << frame.timestamp()
                  << ", counter: " << circle_counter
                  << std::endl;
        }

        if(circle.state() == Gesture::STATE_STOP && doing_gesture && doing_circle){
          doing_gesture = false;
          doing_circle = false;
        }

        break;
      }
      case Gesture::TYPE_SWIPE:
      {
        SwipeGesture swipe = gesture;

        if(swipe.state() == Gesture::STATE_START && !doing_gesture){

          doing_gesture = true;
          doing_swipe = true;

          Vector direction = swipe.direction();
          swipe_action(direction);

          std::cout << std::string(2, ' ')
          << "Swipe id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", direction: " << swipe.direction()
          << ", speed: " << swipe.speed()
          << ", timestamp: " << frame.timestamp()
          << std::endl;

        } else if(swipe.state() == Gesture::STATE_STOP && doing_gesture && doing_swipe){
          doing_gesture = false;
          doing_swipe = false;

          std::cout << std::string(2, ' ')
          << "Swipe id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", direction: " << swipe.direction()
          << ", speed: " << swipe.speed()
          << ", timestamp: " << frame.timestamp()
          << std::endl;

          usleep(250000); // half second wait
        }

        break;
      }
      case Gesture::TYPE_KEY_TAP:
      {
        // KeyTapGesture tap = gesture;
        // std::cout << std::string(2, ' ')
        //   << "Key Tap id: " << gesture.id()
        //   << ", state: " << stateNames[gesture.state()]
        //   << ", position: " << tap.position()
        //   << ", direction: " << tap.direction()
        //   << std::endl;
        break;
      }
      case Gesture::TYPE_SCREEN_TAP:
      {

        HandList hands = frame.hands();
        for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
          // Get the first hand
          const Hand hand = *hl;

          // Get index finger
          Finger index = hand.fingers().fingerType(Finger::TYPE_INDEX)[0];

          if (index.isExtended()){
            Vector pos = index.stabilizedTipPosition();
            Vector dir = index.direction();

            ScreenTapGesture screentap = gesture;
            std::cout << std::string(2, ' ')
                << "Screen Tap id: " << gesture.id()
                << ", state: " << stateNames[gesture.state()]
                << ", position: " << screentap.position()
                << ", direction: " << screentap.direction()
                << ", timestamp: " << frame.timestamp()
                << std::endl;

            mouse_click(pos,dir);
          }
        }

        break;
      }
      default:
        std::cout << std::string(2, ' ')  << "Unknown gesture type." << std::endl;
        break;
    }
  }
}

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

    // Create a sample listener and controller
    GestureListener listener;
    Controller controller;
    // Have the sample listener receive events from the controller
    controller.addListener(listener);

    //change size of min circle
    controller.config().setFloat("Gesture.Circle.MinRadius", MIN_RADIUS);

    //change min arc of a circle
    controller.config().setFloat("Gesture.Circle.MinArc", MIN_ARC);

    //change min length of a swipe
    controller.config().setFloat("Gesture.Swipe.MinLength", MIN_SWIPE_LENGHT);

    //change min swipe velocity
    controller.config().setFloat("Gesture.Swipe.MinVelocity", MIN_VELOCITY);

    controller.config().save();

    //set the controller to recieve frames even when not in foreground
    controller.setPolicyFlags(Leap::Controller::POLICY_BACKGROUND_FRAMES);

    // if (argc > 1 && strcmp(argv[1], "--bg") == 0)
    //   controller.setPolicyFlags(Leap::Controller::POLICY_BACKGROUND_FRAMES);

    // Keep this process running until Enter is pressed
    std::cout << "Press Enter to quit..." << std::endl;
    std::cin.get();

    // Remove the sample listener when done
    controller.removeListener(listener);

    return 0;
}
<commit_msg>Hopefully make swipe easier to do.<commit_after>#include <iostream>
#include <string.h>
#include <Leap.h>
#include <unistd.h>
#include <cstdlib>

#include "task_runner.h"

#define CIRCLE_THRESHOLD .4
#define MIN_RADIUS 50 //default 5mm
#define MIN_ARC 3     //default 1.5*pi radians
#define MIN_SWIPE_LENGHT 75  //default 150
#define MIN_VELOCITY 650      //default 1000

using namespace Leap;

const std::string fingerNames[] = {"Thumb", "Index", "Middle", "Ring", "Pinky"};
const std::string boneNames[] = {"Metacarpal", "Proximal", "Middle", "Distal"};
const std::string stateNames[] = {"STATE_INVALID", "STATE_START", "STATE_UPDATE", "STATE_STOP"};

class GestureListener : public Listener {
  public:
    // virtual void onInit(const Controller&);
    virtual void onConnect(const Controller&);
    // virtual void onDisconnect(const Controller&);
    // virtual void onExit(const Controller&);
    virtual void onFrame(const Controller&);
    // virtual void onFocusGained(const Controller&);
    // virtual void onFocusLost(const Controller&);
    // virtual void onDeviceChange(const Controller&);
    // virtual void onServiceConnect(const Controller&);
    // virtual void onServiceDisconnect(const Controller&);

  private:
};

void GestureListener::onConnect(const Controller& controller) {
  std::cout << "Connected" << std::endl;
  controller.enableGesture(Gesture::TYPE_CIRCLE);
  controller.enableGesture(Gesture::TYPE_KEY_TAP);
  controller.enableGesture(Gesture::TYPE_SCREEN_TAP);
  controller.enableGesture(Gesture::TYPE_SWIPE);
}

float circle_counter = 0; //how much of a circle has been made
bool doing_gesture = false;
bool doing_circle = false;
bool doing_swipe = false;

void GestureListener::onFrame(const Controller& controller) {
  // Get the most recent frame
  const Frame frame = controller.frame();

  // report some basic information
  // std::cout << "Frame id: " << frame.id()
  //           << ", timestamp: " << frame.timestamp()
  //           << ", hands: " << frame.hands().count()
  //           << ", fingers: " << frame.fingers().count()
  //           << ", tools: " << frame.tools().count()
  //           << ", gestures: " << frame.gestures().count() << std::endl;

  // get hand info
  HandList hands = frame.hands();
  for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
    // Get the first hand
    const Hand hand = *hl;
    std::string handType = hand.isLeft() ? "Left hand" : "Right hand";
    // std::cout << std::string(2, ' ') << handType << ", id: " << hand.id()
    //           << ", palm position: " << hand.palmPosition() << std::endl;
    // Get the hand's normal vector and direction
    const Vector normal = hand.palmNormal();
    const Vector direction = hand.direction();

    // Calculate the hand's pitch, roll, and yaw angles
    // std::cout << std::string(2, ' ') <<  "pitch: " << direction.pitch() * RAD_TO_DEG << " degrees, "
    //           << "roll: " << normal.roll() * RAD_TO_DEG << " degrees, "
    //           << "yaw: " << direction.yaw() * RAD_TO_DEG << " degrees" << std::endl;

    // Get the Arm bone
    Arm arm = hand.arm();
    // std::cout << std::string(2, ' ') <<  "Arm direction: " << arm.direction()
    //           << " wrist position: " << arm.wristPosition()
    //           << " elbow position: " << arm.elbowPosition() << std::endl;

    // Get index finger
    Finger index = hand.fingers().fingerType(Finger::TYPE_INDEX)[0];

    if (index.isExtended()){
      Vector pos = index.tipPosition();
      Vector dir = index.direction();

      move_mouse(pos,dir);
    }

  }

  // Get tools
  const ToolList tools = frame.tools();
  for (ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) {
    const Tool tool = *tl;
    // std::cout << std::string(2, ' ') <<  "Tool, id: " << tool.id()
    //           << ", position: " << tool.tipPosition()
    //           << ", direction: " << tool.direction() << std::endl;
  }

  // Get gestures
  const GestureList gestures = frame.gestures();

  for (int g = 0; g < gestures.count(); ++g) {
    Gesture gesture = gestures[g];

    switch (gesture.type()) {
      case Gesture::TYPE_CIRCLE:
      {
        CircleGesture circle = gesture;
        std::string clockwiseness;
        bool clockwise = false;

        if (circle.pointable().direction().angleTo(circle.normal()) <= PI/2) {
          clockwiseness = "clockwise";
          clockwise = true;
        } else {
          clockwiseness = "counterclockwise";
          clockwise = false;
        }

        if(circle.pointables().count() > 1){
            break;
        }

        if(circle.state() == Gesture::STATE_START && !doing_gesture){
          doing_gesture = true;
          doing_circle = true;
        }
        // Calculate angle swept since last frame
        float sweptAngle = 0;
        if (circle.state() != Gesture::STATE_START && doing_circle) {

          CircleGesture previousUpdate = CircleGesture(controller.frame(1).gesture(circle.id()));
          sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;
          if (sweptAngle < 0.00008) {
            //circle.state() = Gesture::STATE_STOP;
            doing_gesture = false;
            doing_circle = false;
          }
          circle_counter += sweptAngle;

          if(circle_counter >= CIRCLE_THRESHOLD){
            circle_counter = 0;
            circle_action(clockwise);
            std::cout << "scroll" << std::endl;
          }

          std::cout << std::string(2, ' ')
                  << "Circle id: " << gesture.id()
                  << ", state: " << stateNames[gesture.state()]
                  << ", progress: " << circle.progress()
                  << ", radius: " << circle.radius()
                  << ", angle " << sweptAngle * RAD_TO_DEG
                  <<  ", " << clockwiseness
                  << ", timestamp: " << frame.timestamp()
                  << ", counter: " << circle_counter
                  << std::endl;
        }

        if(circle.state() == Gesture::STATE_STOP && doing_gesture && doing_circle){
          doing_gesture = false;
          doing_circle = false;
        }

        break;
      }
      case Gesture::TYPE_SWIPE:
      {
        SwipeGesture swipe = gesture;

        if(swipe.state() == Gesture::STATE_START && !doing_gesture){

          doing_gesture = true;
          doing_swipe = true;

          Vector direction = swipe.direction();
          swipe_action(direction);

          std::cout << std::string(2, ' ')
          << "Swipe id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", direction: " << swipe.direction()
          << ", speed: " << swipe.speed()
          << ", timestamp: " << frame.timestamp()
          << std::endl;

        } else if(swipe.state() == Gesture::STATE_STOP && doing_gesture && doing_swipe){
          doing_gesture = false;
          doing_swipe = false;

          std::cout << std::string(2, ' ')
          << "Swipe id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", direction: " << swipe.direction()
          << ", speed: " << swipe.speed()
          << ", timestamp: " << frame.timestamp()
          << std::endl;

          usleep(250000); // half second wait
        }

        break;
      }
      case Gesture::TYPE_KEY_TAP:
      {
        // KeyTapGesture tap = gesture;
        // std::cout << std::string(2, ' ')
        //   << "Key Tap id: " << gesture.id()
        //   << ", state: " << stateNames[gesture.state()]
        //   << ", position: " << tap.position()
        //   << ", direction: " << tap.direction()
        //   << std::endl;
        break;
      }
      case Gesture::TYPE_SCREEN_TAP:
      {

        HandList hands = frame.hands();
        for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
          // Get the first hand
          const Hand hand = *hl;

          // Get index finger
          Finger index = hand.fingers().fingerType(Finger::TYPE_INDEX)[0];

          if (index.isExtended()){
            Vector pos = index.stabilizedTipPosition();
            Vector dir = index.direction();

            ScreenTapGesture screentap = gesture;
            std::cout << std::string(2, ' ')
                << "Screen Tap id: " << gesture.id()
                << ", state: " << stateNames[gesture.state()]
                << ", position: " << screentap.position()
                << ", direction: " << screentap.direction()
                << ", timestamp: " << frame.timestamp()
                << std::endl;

            mouse_click(pos,dir);
          }
        }

        break;
      }
      default:
        std::cout << std::string(2, ' ')  << "Unknown gesture type." << std::endl;
        break;
    }
  }
}

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

    // Create a sample listener and controller
    GestureListener listener;
    Controller controller;
    // Have the sample listener receive events from the controller
    controller.addListener(listener);

    //change size of min circle
    controller.config().setFloat("Gesture.Circle.MinRadius", MIN_RADIUS);

    //change min arc of a circle
    controller.config().setFloat("Gesture.Circle.MinArc", MIN_ARC);

    //change min length of a swipe
    controller.config().setFloat("Gesture.Swipe.MinLength", MIN_SWIPE_LENGHT);

    //change min swipe velocity
    controller.config().setFloat("Gesture.Swipe.MinVelocity", MIN_VELOCITY);

    controller.config().save();

    //set the controller to recieve frames even when not in foreground
    controller.setPolicyFlags(Leap::Controller::POLICY_BACKGROUND_FRAMES);

    // if (argc > 1 && strcmp(argv[1], "--bg") == 0)
    //   controller.setPolicyFlags(Leap::Controller::POLICY_BACKGROUND_FRAMES);

    // Keep this process running until Enter is pressed
    std::cout << "Press Enter to quit..." << std::endl;
    std::cin.get();

    // Remove the sample listener when done
    controller.removeListener(listener);

    return 0;
}
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2019 Alexander Samoilov
//
// 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

#include <iostream>
#include <algorithm>
#include <functional>
#include <array>
#include <vector>
#include <set>
#include <functional>
#include <boost/range/algorithm.hpp>

template <typename T>
struct Inserter
{
    using Type = T;
    using OutputIterator = typename T::iterator;
    OutputIterator operator()(Type& cont) { return cont.begin(); }
    size_t dist(const Type& cont, OutputIterator it)
    {
        return std::distance<typename T::const_iterator>(cont.begin(), it);
    }
};

template <typename T, typename... Rest>
struct Inserter<std::vector<T, Rest...>>
{
    using Type = std::vector<T, Rest...>;
    using OutputIterator = std::back_insert_iterator<Type>;
    OutputIterator operator()(Type& cont) { return std::back_inserter(cont); }
    size_t dist(const Type& cont, OutputIterator)
    {
        return cont.size();
    }
};

template <typename T>
typename Inserter<T>::OutputIterator append(T& cont)
{
    Inserter<T> inserter;
    return inserter(cont);
}

template <typename T>
size_t dist(const T& cont, typename Inserter<T>::OutputIterator it)
{
    return Inserter<T>().dist(cont, it);
}

template <typename RetCont, typename AIterator, typename BIterator, typename SetOp>
int setOpIndices(RetCont& result,
                 AIterator contAbegin, AIterator contAend,
                 BIterator contBbegin, BIterator contBend,
                 SetOp setOp)
{
    RetCont contAcopy, contBcopy;
    std::copy(contAbegin, contAend, append(contAcopy));
    std::copy(contBbegin, contBend, append(contBcopy));
    boost::sort(contAcopy);
    boost::sort(contBcopy);
    auto initialPosition = append(result);
    auto pos = setOp(contAcopy, contBcopy, append(result));
    return dist(result, pos);
}

template <typename RetCont, typename AIterator, typename BIterator,
          typename OutputIterator = typename RetCont::iterator>
int diffIndices(RetCont& result,
                AIterator contAbegin, AIterator contAend,
                BIterator contBbegin, BIterator contBend)
{
    return setOpIndices(result, contAbegin, contAend, contBbegin, contBend,
      boost::set_difference<RetCont, RetCont, OutputIterator>);
}

template <typename RetCont, typename AIterator, typename BIterator,
          typename OutputIterator = typename RetCont::iterator>
int intersectIndices(RetCont& result,
                     AIterator contAbegin, AIterator contAend,
                     BIterator contBbegin, BIterator contBend)
{
    return setOpIndices(result, contAbegin, contAend, contBbegin, contBend,
      boost::set_intersection<RetCont, RetCont, OutputIterator>);
}

// range-based syntax sugar BEWARE uses std::back_inserter
template <typename RetCont, typename ARange, typename BRange>
int diffIndicesRange(RetCont& result, const ARange& acont, const BRange& bcont)
{
    result.clear();
    return diffIndices<RetCont, typename ARange::const_iterator, typename BRange::const_iterator,
                       std::back_insert_iterator<RetCont>>
      (result, begin(acont), end(acont), begin(bcont), end(bcont));
}

template <typename RetCont, typename ARange, typename BRange>
int intersectIndicesRange(RetCont& result, const ARange& acont, const BRange& bcont)
{
    result.clear();
    return intersectIndices<RetCont, typename ARange::const_iterator, typename BRange::const_iterator,
                            std::back_insert_iterator<RetCont>>
      (result, begin(acont), end(acont), begin(bcont), end(bcont));
}

#include <gtest/gtest.h>

TEST(SetOps, FixedSizeContainer)
{
    std::array<int, 3> a{1, 2, 3}, b{3, 4, 5}, c;
    size_t size = diffIndices(c, begin(a), end(a), begin(b), end(b));
    ASSERT_EQ(size, 2);
    ASSERT_EQ(c[0], 1);
    ASSERT_EQ(c[1], 2);
    size = intersectIndices(c, begin(a), end(a), begin(b), end(b));
    ASSERT_EQ(size, 1);
    ASSERT_EQ(c[0], 3);
}

TEST(SetOps, VariableSizeContainer)
{
    std::vector<int> a{1, 2, 3}, b{3, 4, 5}, c;
    size_t size = diffIndicesRange(c, a, b);
    ASSERT_EQ(size, 2);
    ASSERT_EQ(c[0], 1);
    ASSERT_EQ(c[1], 2);
    size = intersectIndicesRange(c, a, b);
    ASSERT_EQ(size, 1);
    ASSERT_EQ(c[0], 3);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>removed dead code from specialization sample<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2019 Alexander Samoilov
//
// 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

#include <iostream>
#include <algorithm>
#include <functional>
#include <array>
#include <vector>
#include <set>
#include <functional>
#include <boost/range/algorithm.hpp>

template <typename T>
struct Inserter
{
    using Type = T;
    using OutputIterator = typename T::iterator;
    OutputIterator operator()(Type& cont) { return cont.begin(); }
    size_t dist(const Type& cont, OutputIterator it)
    {
        return std::distance<typename T::const_iterator>(cont.begin(), it);
    }
};

template <typename T, typename... Rest>
struct Inserter<std::vector<T, Rest...>>
{
    using Type = std::vector<T, Rest...>;
    using OutputIterator = std::back_insert_iterator<Type>;
    OutputIterator operator()(Type& cont) { return std::back_inserter(cont); }
    size_t dist(const Type& cont, OutputIterator)
    {
        return cont.size();
    }
};

template <typename T>
typename Inserter<T>::OutputIterator append(T& cont)
{
    Inserter<T> inserter;
    return inserter(cont);
}

template <typename T>
size_t dist(const T& cont, typename Inserter<T>::OutputIterator it)
{
    return Inserter<T>().dist(cont, it);
}

template <typename RetCont, typename AIterator, typename BIterator, typename SetOp>
int setOpIndices(RetCont& result,
                 AIterator contAbegin, AIterator contAend,
                 BIterator contBbegin, BIterator contBend,
                 SetOp setOp)
{
    RetCont contAcopy, contBcopy;
    std::copy(contAbegin, contAend, append(contAcopy));
    std::copy(contBbegin, contBend, append(contBcopy));
    boost::sort(contAcopy);
    boost::sort(contBcopy);
    auto pos = setOp(contAcopy, contBcopy, append(result));
    return dist(result, pos);
}

template <typename RetCont, typename AIterator, typename BIterator,
          typename OutputIterator = typename RetCont::iterator>
int diffIndices(RetCont& result,
                AIterator contAbegin, AIterator contAend,
                BIterator contBbegin, BIterator contBend)
{
    return setOpIndices(result, contAbegin, contAend, contBbegin, contBend,
      boost::set_difference<RetCont, RetCont, OutputIterator>);
}

template <typename RetCont, typename AIterator, typename BIterator,
          typename OutputIterator = typename RetCont::iterator>
int intersectIndices(RetCont& result,
                     AIterator contAbegin, AIterator contAend,
                     BIterator contBbegin, BIterator contBend)
{
    return setOpIndices(result, contAbegin, contAend, contBbegin, contBend,
      boost::set_intersection<RetCont, RetCont, OutputIterator>);
}

// range-based syntax sugar BEWARE uses std::back_inserter
template <typename RetCont, typename ARange, typename BRange>
int diffIndicesRange(RetCont& result, const ARange& acont, const BRange& bcont)
{
    result.clear();
    return diffIndices<RetCont, typename ARange::const_iterator, typename BRange::const_iterator,
                       std::back_insert_iterator<RetCont>>
      (result, begin(acont), end(acont), begin(bcont), end(bcont));
}

template <typename RetCont, typename ARange, typename BRange>
int intersectIndicesRange(RetCont& result, const ARange& acont, const BRange& bcont)
{
    result.clear();
    return intersectIndices<RetCont, typename ARange::const_iterator, typename BRange::const_iterator,
                            std::back_insert_iterator<RetCont>>
      (result, begin(acont), end(acont), begin(bcont), end(bcont));
}

#include <gtest/gtest.h>

TEST(SetOps, FixedSizeContainer)
{
    std::array<int, 3> a{1, 2, 3}, b{3, 4, 5}, c;
    size_t size = diffIndices(c, begin(a), end(a), begin(b), end(b));
    ASSERT_EQ(size, 2);
    ASSERT_EQ(c[0], 1);
    ASSERT_EQ(c[1], 2);
    size = intersectIndices(c, begin(a), end(a), begin(b), end(b));
    ASSERT_EQ(size, 1);
    ASSERT_EQ(c[0], 3);
}

TEST(SetOps, VariableSizeContainer)
{
    std::vector<int> a{1, 2, 3}, b{3, 4, 5}, c;
    size_t size = diffIndicesRange(c, a, b);
    ASSERT_EQ(size, 2);
    ASSERT_EQ(c[0], 1);
    ASSERT_EQ(c[1], 2);
    size = intersectIndicesRange(c, a, b);
    ASSERT_EQ(size, 1);
    ASSERT_EQ(c[0], 3);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>