<commit_before>// SketchOp.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "SketchOp.h"
#include "CNCConfig.h"
#include "ProgramCanvas.h"
#include "Program.h"
#include "interface/PropertyInt.h"
#include "interface/PropertyDouble.h"
#include "interface/PropertyLength.h"
#include "interface/PropertyString.h"
#include "tinyxml/tinyxml.h"
#include "interface/Tool.h"
#include "CTool.h"
#include "Reselect.h"

CSketchOp & CSketchOp::operator= ( const CSketchOp & rhs )
{
	if (this != &rhs)
	{
		m_sketch = rhs.m_sketch;
		CDepthOp::operator=( rhs );
	}

	return(*this);
}

CSketchOp::CSketchOp( const CSketchOp & rhs ) : CDepthOp(rhs)
{
	m_sketch = rhs.m_sketch;
}

void CSketchOp::ReloadPointers()
{
	CDepthOp::ReloadPointers();
}

void CSketchOp::GetBox(CBox &box)
{
	HeeksObj* sketch = heeksCAD->GetIDObject(SketchType, m_sketch);
	if (sketch)sketch->GetBox(box);
}

void CSketchOp::glCommands(bool select, bool marked, bool no_color)
{
	CDepthOp::glCommands(select, marked, no_color);

	if (select || marked)
	{
		// allow sketch operations to be selected
		HeeksObj* sketch = heeksCAD->GetIDObject(SketchType, m_sketch);
		if (sketch)sketch->glCommands(select, marked, no_color);
	}
}

void CSketchOp::WriteBaseXML(TiXmlElement *element)
{
	// write sketch id
	element->SetAttribute( "sketch", m_sketch);

	CDepthOp::WriteBaseXML(element);
}

void CSketchOp::ReadBaseXML(TiXmlElement* element)
{
	element->Attribute("sketch", &m_sketch);

	// get old sketch child item
	TiXmlElement* e = heeksCAD->FirstNamedXMLChildElement(element, "sketch");
	if(e)
	{
		int id = 0;
		if(e->Attribute("id", &id))
			m_sketch = id;
	}

	CDepthOp::ReadBaseXML(element);
}

void on_set_sketch(int value, HeeksObj* object)
{
	((CSketchOp*)object)->m_sketch = value;
}

void CSketchOp::GetProperties(std::list<Property *> *list)
{
	list->push_back(new PropertyInt(_("sketch id"), m_sketch, this, on_set_sketch));
	CDepthOp::GetProperties(list);
}

Python CSketchOp::AppendTextToProgram()
{
	Python python;
    python << CDepthOp::AppendTextToProgram();
	return(python);
}

static ReselectSketch reselect_sketch;

void CSketchOp::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	reselect_sketch.m_sketch = m_sketch;
	reselect_sketch.m_object = this;
	t_list->push_back(&reselect_sketch);
    CDepthOp::GetTools( t_list, p );
}

bool CSketchOp::operator== ( const CSketchOp & rhs ) const
{
	return(CDepthOp::operator==(rhs));
}
<commit_msg>Fixed a bug where clicking on an operation which links to an Area object was crashing<commit_after>// SketchOp.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "SketchOp.h"
#include "CNCConfig.h"
#include "ProgramCanvas.h"
#include "Program.h"
#include "interface/PropertyInt.h"
#include "interface/PropertyDouble.h"
#include "interface/PropertyLength.h"
#include "interface/PropertyString.h"
#include "tinyxml/tinyxml.h"
#include "interface/Tool.h"
#include "CTool.h"
#include "Reselect.h"

CSketchOp & CSketchOp::operator= ( const CSketchOp & rhs )
{
	if (this != &rhs)
	{
		m_sketch = rhs.m_sketch;
		CDepthOp::operator=( rhs );
	}

	return(*this);
}

CSketchOp::CSketchOp( const CSketchOp & rhs ) : CDepthOp(rhs)
{
	m_sketch = rhs.m_sketch;
}

void CSketchOp::ReloadPointers()
{
	CDepthOp::ReloadPointers();
}

void CSketchOp::GetBox(CBox &box)
{
	HeeksObj* sketch = heeksCAD->GetIDObject(SketchType, m_sketch);
	if (sketch)sketch->GetBox(box);
}

void CSketchOp::glCommands(bool select, bool marked, bool no_color)
{
	CDepthOp::glCommands(select, marked, no_color);

	if (select || marked)
	{
		// allow sketch operations to be selected
		HeeksObj* sketch = heeksCAD->GetIDObject(SketchType, m_sketch);
		if (sketch)
		{
			if (select)glPushName(sketch->GetIndex());
			sketch->glCommands(select, marked, no_color);
			if (select)glPopName();
		}
	}
}

void CSketchOp::WriteBaseXML(TiXmlElement *element)
{
	// write sketch id
	element->SetAttribute( "sketch", m_sketch);

	CDepthOp::WriteBaseXML(element);
}

void CSketchOp::ReadBaseXML(TiXmlElement* element)
{
	element->Attribute("sketch", &m_sketch);

	// get old sketch child item
	TiXmlElement* e = heeksCAD->FirstNamedXMLChildElement(element, "sketch");
	if(e)
	{
		int id = 0;
		if(e->Attribute("id", &id))
			m_sketch = id;
	}

	CDepthOp::ReadBaseXML(element);
}

void on_set_sketch(int value, HeeksObj* object)
{
	((CSketchOp*)object)->m_sketch = value;
}

void CSketchOp::GetProperties(std::list<Property *> *list)
{
	list->push_back(new PropertyInt(_("sketch id"), m_sketch, this, on_set_sketch));
	CDepthOp::GetProperties(list);
}

Python CSketchOp::AppendTextToProgram()
{
	Python python;
    python << CDepthOp::AppendTextToProgram();
	return(python);
}

static ReselectSketch reselect_sketch;

void CSketchOp::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	reselect_sketch.m_sketch = m_sketch;
	reselect_sketch.m_object = this;
	t_list->push_back(&reselect_sketch);
    CDepthOp::GetTools( t_list, p );
}

bool CSketchOp::operator== ( const CSketchOp & rhs ) const
{
	return(CDepthOp::operator==(rhs));
}
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * 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 <fnordmetric/environment.h>
#include <fnordmetric/query/query.h>
#include <fnordmetric/query/queryservice.h>
#include <fnordmetric/sql/runtime/queryplannode.h>
#include <fnordmetric/sql/runtime/resultlist.h>
#include <fnordmetric/sql/runtime/tablerepository.h>
#include <fnordmetric/ui/svgtarget.h>
#include <fnordmetric/util/inputstream.h>
#include <fnordmetric/util/jsonoutputstream.h>

namespace fnordmetric {
namespace query {

QueryService::QueryService() {}

void QueryService::executeQuery(
    std::shared_ptr<util::InputStream> input_stream,
    kFormat output_format,
    std::shared_ptr<util::OutputStream> output_stream) {
  std::unique_ptr<TableRepository> table_repo(new TableRepository());
  executeQuery(
      input_stream,
      output_format,
      output_stream,
      std::move(table_repo));
}

void QueryService::executeQuery(
    std::shared_ptr<util::InputStream> input_stream,
    kFormat output_format,
    std::shared_ptr<util::OutputStream> output_stream,
    std::unique_ptr<TableRepository> table_repo,
    int width /* = -1 */,
    int height /* = -1 */) {
  std::string query_string;
  input_stream->readUntilEOF(&query_string);

  if (fnordmetric::env()->verbose()) {
    fnordmetric::env()->logger()->printf(
        "DEBUG",
        "Executing ChartSQL query: %s",
        query_string.c_str());
  }

  try {
    Query query(query_string, &runtime_, std::move(table_repo));
    query.execute();

    switch (output_format) {
      case FORMAT_SVG: {
        ui::SVGTarget target(output_stream.get());
        renderCharts(&query, &target, width, height);
        break;
      }

      case FORMAT_JSON: {
        util::JSONOutputStream target(output_stream);
        renderJSON(&query, &target, width, height);
        break;
      }

      case FORMAT_TABLE: {
        renderTables(&query, output_stream.get());
        break;
      }

      default:
        RAISE(kRuntimeError, "can't handle this output format");

    }
  } catch (util::RuntimeException e) {
    e.appendMessage(" while executing query: %s", query_string.c_str());
    throw e;
  }
}

void QueryService::registerBackend(std::unique_ptr<Backend>&& backend) {
  runtime_.addBackend(std::move(backend));
}

void QueryService::renderCharts(
    Query* query,
    ui::RenderTarget* target,
    int width,
    int height) const {
  for (int i = 0; i < query->getNumCharts(); ++i) {
    auto chart = query->getChart(i);
    chart->setDimensions(width, height);
    chart->render(target);
  }
}

void QueryService::renderJSON(
    Query* query,
    util::JSONOutputStream* target,
    int width,
    int height) const {
  target->beginObject();

  if (query->getNumResultLists() > 0) {
    target->addObjectEntry("tables");
    target->beginArray();
    for (int i = 0; i < query->getNumResultLists(); ++i) {
      const auto result_list = query->getResultList(i);
      target->beginObject();

      target->addObjectEntry("columns");
      target->beginArray();

      auto columns = result_list->getColumns();
      for (int i = 0; i < columns.size(); ++i) {
        if (i > 0) {
          target->addComma();
        }
        target->addString(columns[i]);
      }
      target->endArray();
      target->addComma();

      target->addObjectEntry("rows");
      target->beginArray();
      for (int j = 0; j < result_list->getNumRows(); ++j) {
        const auto& row = result_list->getRow(j);

        target->beginArray();
        for (const auto& col : row) {
          target->addString(col);
          if (col != row.back()) {
            target->addComma();
          }
        }
        target->endArray();

        if (j < result_list->getNumRows() - 1) {
          target->addComma();
        }
      }
      target->endArray();
      target->endObject();

      if (i < query->getNumResultLists() - 1) {
        target->addComma();
      }
    }
    target->endArray();
    target->addComma();
  }

  if (query->getNumCharts() > 0) {
    target->addObjectEntry("charts");
    target->beginArray();

    for (int i = 0; i < query->getNumCharts(); ++i) {
      std::string svg_data;
      auto string_stream = util::StringOutputStream::fromString(&svg_data);
      ui::SVGTarget svg_target(string_stream.get());
      auto chart = query->getChart(i);
      chart->setDimensions(width, height);
      chart->render(&svg_target);

      target->beginObject();
      target->addObjectEntry("svg");
      target->addString(svg_data);
      target->endObject();

      if (i < query->getNumCharts() - 1) {
        target->addComma();
      }
    }

    target->endArray();
    target->addComma();
  }

  target->addObjectEntry("status");
  target->addString("success");

  target->endObject();
}

void QueryService::renderTables(Query* query, util::OutputStream* out) const {
  for (int i = 0; i < query->getNumResultLists(); ++i) {
    const auto result_list = query->getResultList(i);
    result_list->debugPrint();
  }
}

}
}
<commit_msg>fixes<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * 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 <fnordmetric/environment.h>
#include <fnordmetric/query/query.h>
#include <fnordmetric/query/queryservice.h>
#include <fnordmetric/sql/runtime/queryplannode.h>
#include <fnordmetric/sql/runtime/resultlist.h>
#include <fnordmetric/sql/runtime/tablerepository.h>
#include <fnordmetric/ui/svgtarget.h>
#include <fnordmetric/util/inputstream.h>
#include <fnordmetric/util/jsonoutputstream.h>

namespace fnordmetric {
namespace query {

QueryService::QueryService() {}

void QueryService::executeQuery(
    std::shared_ptr<util::InputStream> input_stream,
    kFormat output_format,
    std::shared_ptr<util::OutputStream> output_stream) {
  std::unique_ptr<TableRepository> table_repo(new TableRepository());
  executeQuery(
      input_stream,
      output_format,
      output_stream,
      std::move(table_repo));
}

void QueryService::executeQuery(
    std::shared_ptr<util::InputStream> input_stream,
    kFormat output_format,
    std::shared_ptr<util::OutputStream> output_stream,
    std::unique_ptr<TableRepository> table_repo,
    int width /* = -1 */,
    int height /* = -1 */) {
  std::string query_string;
  input_stream->readUntilEOF(&query_string);

  if (fnordmetric::env()->verbose()) {
    fnordmetric::env()->logger()->printf(
        "DEBUG",
        "Executing ChartSQL query: %s",
        query_string.c_str());
  }

  try {
    Query query(query_string, &runtime_, std::move(table_repo));
    query.execute();

    switch (output_format) {
      case FORMAT_SVG: {
        ui::SVGTarget target(output_stream.get());
        renderCharts(&query, &target, width, height);
        break;
      }

      case FORMAT_JSON: {
        util::JSONOutputStream target(output_stream);
        renderJSON(&query, &target, width, height);
        break;
      }

      case FORMAT_TABLE: {
        renderTables(&query, output_stream.get());
        break;
      }

      default:
        RAISE(kRuntimeError, "can't handle this output format");

    }
  } catch (util::RuntimeException e) {
    e.appendMessage(" while executing query: %s", query_string.c_str());
    throw e;
  }
}

void QueryService::registerBackend(std::unique_ptr<Backend>&& backend) {
  runtime_.addBackend(std::move(backend));
}

void QueryService::renderCharts(
    Query* query,
    ui::RenderTarget* target,
    int width,
    int height) const {
  for (int i = 0; i < query->getNumCharts(); ++i) {
    auto chart = query->getChart(i);
    chart->setDimensions(width, height);
    chart->render(target);
  }
}

void QueryService::renderJSON(
    Query* query,
    util::JSONOutputStream* target,
    int width,
    int height) const {
  target->beginObject();

  if (query->getNumResultLists() > 0) {
    target->addObjectEntry("tables");
    target->beginArray();
    for (int i = 0; i < query->getNumResultLists(); ++i) {
      const auto result_list = query->getResultList(i);
      target->beginObject();

      target->addObjectEntry("columns");
      target->beginArray();

      auto columns = result_list->getColumns();
      for (int i = 0; i < columns.size(); ++i) {
        if (i > 0) {
          target->addComma();
        }
        target->addString(columns[i]);
      }
      target->endArray();
      target->addComma();

      target->addObjectEntry("rows");
      target->beginArray();
      for (int j = 0; j < result_list->getNumRows(); ++j) {
        const auto& row = result_list->getRow(j);

        target->beginArray();
        for (int i = 0; i < row.size(); ++i) {
          if (i > 0) {
            target->addComma();
          }

          target->addString(row[i]);
        }
        target->endArray();

        if (j < result_list->getNumRows() - 1) {
          target->addComma();
        }
      }
      target->endArray();
      target->endObject();

      if (i < query->getNumResultLists() - 1) {
        target->addComma();
      }
    }
    target->endArray();
    target->addComma();
  }

  if (query->getNumCharts() > 0) {
    target->addObjectEntry("charts");
    target->beginArray();

    for (int i = 0; i < query->getNumCharts(); ++i) {
      std::string svg_data;
      auto string_stream = util::StringOutputStream::fromString(&svg_data);
      ui::SVGTarget svg_target(string_stream.get());
      auto chart = query->getChart(i);
      chart->setDimensions(width, height);
      chart->render(&svg_target);

      target->beginObject();
      target->addObjectEntry("svg");
      target->addString(svg_data);
      target->endObject();

      if (i < query->getNumCharts() - 1) {
        target->addComma();
      }
    }

    target->endArray();
    target->addComma();
  }

  target->addObjectEntry("status");
  target->addString("success");

  target->endObject();
}

void QueryService::renderTables(Query* query, util::OutputStream* out) const {
  for (int i = 0; i < query->getNumResultLists(); ++i) {
    const auto result_list = query->getResultList(i);
    result_list->debugPrint();
  }
}

}
}
<|endoftext|>


<commit_before>// RUN: %clangxx_msan %s -O0 -fsanitize=memory -fsanitize-memory-use-after-dtor -o %t && MSAN_OPTIONS=poison_in_dtor=1 %run %t >%t.out 2>&1

// RUN: %clangxx_msan %s -O1 -fsanitize=memory -fsanitize-memory-use-after-dtor -o %t && MSAN_OPTIONS=poison_in_dtor=1 %run %t >%t.out 2>&1

// RUN: %clangxx_msan %s -O2 -fsanitize=memory -fsanitize-memory-use-after-dtor -o %t && MSAN_OPTIONS=poison_in_dtor=1 %run %t >%t.out 2>&1

// XFAIL: *

#include <sanitizer/msan_interface.h>
#include <assert.h>

class Base {
 public:
  int *x_ptr;
  Base(int *y_ptr) {
    // store value of subclass member
    x_ptr = y_ptr;
  }
  virtual ~Base();
};

class Derived : public Base {
 public:
  int y;
  Derived():Base(&y) {
    y = 10;
  }
  ~Derived();
};

Base::~Base() {
  // ok access its own member
  assert(__msan_test_shadow(&this->x_ptr, sizeof(this->x_ptr)) == -1);
  // bad access subclass member
  assert(__msan_test_shadow(this->x_ptr, sizeof(*this->x_ptr)) != -1);
}

Derived::~Derived() {
  // ok to access its own members
  assert(__msan_test_shadow(&this->y, sizeof(this->y)) == -1);
  // ok access base class members
  assert(__msan_test_shadow(&this->x_ptr, sizeof(this->x_ptr)) == -1);
}

int main() {
  Derived *d = new Derived();
  assert(__msan_test_shadow(&d->x_ptr, sizeof(d->x_ptr)) == -1);
  d->~Derived();
  assert(__msan_test_shadow(&d->x_ptr, sizeof(d->x_ptr)) != -1);
  return 0;
}
<commit_msg>Removed xfail, since test is passing in line with expanded dtor sanitizing functionality<commit_after>// RUN: %clangxx_msan %s -O0 -fsanitize=memory -fsanitize-memory-use-after-dtor -o %t && MSAN_OPTIONS=poison_in_dtor=1 %run %t >%t.out 2>&1

// RUN: %clangxx_msan %s -O1 -fsanitize=memory -fsanitize-memory-use-after-dtor -o %t && MSAN_OPTIONS=poison_in_dtor=1 %run %t >%t.out 2>&1

// RUN: %clangxx_msan %s -O2 -fsanitize=memory -fsanitize-memory-use-after-dtor -o %t && MSAN_OPTIONS=poison_in_dtor=1 %run %t >%t.out 2>&1

#include <sanitizer/msan_interface.h>
#include <assert.h>

class Base {
 public:
  int *x_ptr;
  Base(int *y_ptr) {
    // store value of subclass member
    x_ptr = y_ptr;
  }
  virtual ~Base();
};

class Derived : public Base {
 public:
  int y;
  Derived():Base(&y) {
    y = 10;
  }
  ~Derived();
};

Base::~Base() {
  // ok access its own member
  assert(__msan_test_shadow(&this->x_ptr, sizeof(this->x_ptr)) == -1);
  // bad access subclass member
  assert(__msan_test_shadow(this->x_ptr, sizeof(*this->x_ptr)) != -1);
}

Derived::~Derived() {
  // ok to access its own members
  assert(__msan_test_shadow(&this->y, sizeof(this->y)) == -1);
  // ok access base class members
  assert(__msan_test_shadow(&this->x_ptr, sizeof(this->x_ptr)) == -1);
}

int main() {
  Derived *d = new Derived();
  assert(__msan_test_shadow(&d->x_ptr, sizeof(d->x_ptr)) == -1);
  d->~Derived();
  assert(__msan_test_shadow(&d->x_ptr, sizeof(d->x_ptr)) != -1);
  return 0;
}
<|endoftext|>


<commit_before>//- Standard Library -
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>

//- Beach Judge -
#include <BeachJudge/Base.h>
#include <BeachJudge/Competition.h>
#include <BeachJudge/Problem.h>
#include <BeachJudge/Question.h>

#ifdef _WIN32
	#define SPRINTF sprintf_s
#else
	#define SPRINTF	sprintf
#endif

using namespace std;

namespace beachjudge
{
	Competition *g_currentCompetition = 0;

	Competition *Competition::GetCurrent()
	{
		return g_currentCompetition;
	}
	Competition *Competition::CreateFromFile(string file)
	{
		if(!fileExists(file.c_str()))
			return 0;

		Competition *competition = new Competition();

		string in;
		ifstream inFile(file.c_str());

		while(getline(inFile, in, '\t'))
		{
			if(!in.compare("duration"))
			{
				getline(inFile, in);
				competition->m_duration = atoi(in.c_str());
			}
			else if(!in.compare("endTime"))
			{
				getline(inFile, in);
				competition->m_endTimeMS = atol(in.c_str());
				competition->m_startTimeMS = competition->m_endTimeMS - competition->m_duration; //- TODO: Clean this up -
			}
			else if(!in.compare("questions"))
			{
				getline(inFile, in, '\t');
				Problem *problem = Problem::LookupByID(atoi(in.c_str()));
				getline(inFile, in);
				stringstream questionsStream(in);
				while(getline(questionsStream, in, '\t'))
				{
					stringstream questionInfo(in);
					unsigned short tID;
					bool answered;
					questionInfo >> tID >> answered;
					string text, answer;
					Team *team = Team::LookupByID(tID);
					getline(questionsStream, text, '\t');
					if(answered)
						getline(questionsStream, answer, '\t');
					Question *question = Question::Create(text, team, problem);
					if(answered)
						question->Answer(answer);
				}
			}
			else if(!in.compare("submissions"))
			{
				getline(inFile, in);
				stringstream submissionsStream(in);
				while(getline(submissionsStream, in, '\t'))
				{
					stringstream submissionInfo(in);
					unsigned short sID, tID, pID, cType, sStatus;
					unsigned long long timeMS;
					submissionInfo >> sID >> tID >> pID >> cType >> sStatus >> timeMS;
					Team *team = Team::LookupByID(tID);
					Problem *problem = Problem::LookupByID(pID);
					Submission::Create(team, problem, (CodeType)cType, timeMS, (SubStatus)sStatus, sID);
				}
			}
		}

		inFile.close();

		return competition;
	}
	Competition *Competition::Create(unsigned long long duration)
	{
		Competition *competition = new Competition();
		competition->m_duration = duration;
		return competition;
	}

	Competition::Competition()
	{
		m_startTimeMS = m_endTimeMS = m_duration = 0;
		m_isRunning = false;
	}
	Competition::~Competition()
	{
	}
	void Competition::Start()
	{
		if(m_startTimeMS == 0)
		{
			m_startTimeMS = getRealTimeMS();
			m_endTimeMS = m_startTimeMS + m_duration;
		}
		m_isRunning = true;
	}
	void Competition::Stop()
	{
		m_isRunning = false;
		m_startTimeMS = 0;
		m_endTimeMS = 0;
	}
	bool Competition::IsRunning() const
	{
		return m_isRunning;
	}
	unsigned long long Competition::GetTimeLeft() const
	{
		unsigned long long currTimeMS = getRealTimeMS();
		if(currTimeMS > m_endTimeMS)
			return 0;
		else
			return m_endTimeMS - currTimeMS;
	}
	unsigned long long Competition::GetDuration() const
	{
		return m_duration;
	}
	unsigned long long Competition::CalculateTimeScore(unsigned long long timeMS)
	{
		return m_duration - (m_endTimeMS - timeMS);
	}
	void Competition::SetCurrent()
	{
		g_currentCompetition = this;
	}
	void Competition::SaveToFile(string file)
	{
		createFolder(filePath(file.c_str()).c_str());
		ofstream outFile(file.c_str());
		outFile << "duration\t" << m_duration << endl;
		outFile << "endTime\t" << m_endTimeMS << endl;
		map<Problem *, vector<Question *> > &questionByProblem = Question::GetQuestionsByProblem();
		for(map<Problem *, vector<Question *> >::iterator it = questionByProblem.begin(); it != questionByProblem.end(); it++)
		{
			Problem *problem = it->first;
			outFile << "questions\t" << problem->GetID();
			vector<Question *> &questions = it->second;
			for(vector<Question *>::iterator itB = questions.begin(); itB != questions.end(); itB++)
			{
				Question *question = *itB;
				bool isAnswered = question->IsAnswered();
				outFile << "\t" << question->GetTeam()->GetID() << " " << isAnswered << "\t" << question->GetText();
				if(isAnswered)
					outFile << "\t" << question->GetAnswer();
			}
			outFile << endl;
		}
		map<unsigned short, Submission *> &submissions = Submission::GetSubmissionsByID();
		if(submissions.size())
		{
			outFile << "submissions";
			for(map<unsigned short, Submission *>::iterator it = submissions.begin(); it != submissions.end(); it++)
			{
				Submission *submission = it->second;
				Team *team = submission->GetTeam();
				Problem *problem = submission->GetProblem();
				outFile << "\t" << submission->GetID() << " " << team->GetID() << " " << problem->GetID() << " " << submission->GetCodeType() << " " << submission->GetStatus() << " " << submission->GetTimeMS();
			}
			outFile << endl;
		}

		outFile.close();
	}
	void Competition::ClearAll()
	{
		map<unsigned short, Submission *> &submissions = Submission::GetSubmissionsByID();
		if(submissions.size())
			for(map<unsigned short, Submission *>::iterator it = submissions.begin(); it != submissions.end(); it++)
			{
				Submission *submission = it->second;
				fileDelete(submission->GetSourceFile().c_str());
				string base = submission->GetBase();
				string logFile(base), execFile(base);
				logFile.append(".log");
				execFile.append(".out");
				fileDelete(logFile.c_str());
				fileDelete(execFile.c_str());
			}
		map<unsigned short, Team *> &teamsByID = Team::GetTeamsByID();
		for(map<unsigned short, Team *>::iterator it = teamsByID.begin(); it != teamsByID.end(); it++)
		{
			Team *team = it->second;
			team->Reset();
		}
		Problem::ClearSolvers();
		Question::Cleanup();
		Submission::Cleanup();
		fileDelete("compo/compo.txt");
		fileDelete("compo/scores.txt");
	}
}
<commit_msg>Replaced atol with atoll to compliment the last commit<commit_after>//- Standard Library -
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>

//- Beach Judge -
#include <BeachJudge/Base.h>
#include <BeachJudge/Competition.h>
#include <BeachJudge/Problem.h>
#include <BeachJudge/Question.h>

#ifdef _WIN32
	#define SPRINTF sprintf_s
#else
	#define SPRINTF	sprintf
#endif

using namespace std;

namespace beachjudge
{
	Competition *g_currentCompetition = 0;

	Competition *Competition::GetCurrent()
	{
		return g_currentCompetition;
	}
	Competition *Competition::CreateFromFile(string file)
	{
		if(!fileExists(file.c_str()))
			return 0;

		Competition *competition = new Competition();

		string in;
		ifstream inFile(file.c_str());

		while(getline(inFile, in, '\t'))
		{
			if(!in.compare("duration"))
			{
				getline(inFile, in);
				competition->m_duration = atoll(in.c_str());
			}
			else if(!in.compare("endTime"))
			{
				getline(inFile, in);
				competition->m_endTimeMS = atoll(in.c_str());
				competition->m_startTimeMS = competition->m_endTimeMS - competition->m_duration; //- TODO: Clean this up -
			}
			else if(!in.compare("questions"))
			{
				getline(inFile, in, '\t');
				Problem *problem = Problem::LookupByID(atoi(in.c_str()));
				getline(inFile, in);
				stringstream questionsStream(in);
				while(getline(questionsStream, in, '\t'))
				{
					stringstream questionInfo(in);
					unsigned short tID;
					bool answered;
					questionInfo >> tID >> answered;
					string text, answer;
					Team *team = Team::LookupByID(tID);
					getline(questionsStream, text, '\t');
					if(answered)
						getline(questionsStream, answer, '\t');
					Question *question = Question::Create(text, team, problem);
					if(answered)
						question->Answer(answer);
				}
			}
			else if(!in.compare("submissions"))
			{
				getline(inFile, in);
				stringstream submissionsStream(in);
				while(getline(submissionsStream, in, '\t'))
				{
					stringstream submissionInfo(in);
					unsigned short sID, tID, pID, cType, sStatus;
					unsigned long long timeMS;
					submissionInfo >> sID >> tID >> pID >> cType >> sStatus >> timeMS;
					Team *team = Team::LookupByID(tID);
					Problem *problem = Problem::LookupByID(pID);
					Submission::Create(team, problem, (CodeType)cType, timeMS, (SubStatus)sStatus, sID);
				}
			}
		}

		inFile.close();

		return competition;
	}
	Competition *Competition::Create(unsigned long long duration)
	{
		Competition *competition = new Competition();
		competition->m_duration = duration;
		return competition;
	}

	Competition::Competition()
	{
		m_startTimeMS = m_endTimeMS = m_duration = 0;
		m_isRunning = false;
	}
	Competition::~Competition()
	{
	}
	void Competition::Start()
	{
		if(m_startTimeMS == 0)
		{
			m_startTimeMS = getRealTimeMS();
			m_endTimeMS = m_startTimeMS + m_duration;
		}
		m_isRunning = true;
	}
	void Competition::Stop()
	{
		m_isRunning = false;
		m_startTimeMS = 0;
		m_endTimeMS = 0;
	}
	bool Competition::IsRunning() const
	{
		return m_isRunning;
	}
	unsigned long long Competition::GetTimeLeft() const
	{
		unsigned long long currTimeMS = getRealTimeMS();
		if(currTimeMS > m_endTimeMS)
			return 0;
		else
			return m_endTimeMS - currTimeMS;
	}
	unsigned long long Competition::GetDuration() const
	{
		return m_duration;
	}
	unsigned long long Competition::CalculateTimeScore(unsigned long long timeMS)
	{
		return m_duration - (m_endTimeMS - timeMS);
	}
	void Competition::SetCurrent()
	{
		g_currentCompetition = this;
	}
	void Competition::SaveToFile(string file)
	{
		createFolder(filePath(file.c_str()).c_str());
		ofstream outFile(file.c_str());
		outFile << "duration\t" << m_duration << endl;
		outFile << "endTime\t" << m_endTimeMS << endl;
		map<Problem *, vector<Question *> > &questionByProblem = Question::GetQuestionsByProblem();
		for(map<Problem *, vector<Question *> >::iterator it = questionByProblem.begin(); it != questionByProblem.end(); it++)
		{
			Problem *problem = it->first;
			outFile << "questions\t" << problem->GetID();
			vector<Question *> &questions = it->second;
			for(vector<Question *>::iterator itB = questions.begin(); itB != questions.end(); itB++)
			{
				Question *question = *itB;
				bool isAnswered = question->IsAnswered();
				outFile << "\t" << question->GetTeam()->GetID() << " " << isAnswered << "\t" << question->GetText();
				if(isAnswered)
					outFile << "\t" << question->GetAnswer();
			}
			outFile << endl;
		}
		map<unsigned short, Submission *> &submissions = Submission::GetSubmissionsByID();
		if(submissions.size())
		{
			outFile << "submissions";
			for(map<unsigned short, Submission *>::iterator it = submissions.begin(); it != submissions.end(); it++)
			{
				Submission *submission = it->second;
				Team *team = submission->GetTeam();
				Problem *problem = submission->GetProblem();
				outFile << "\t" << submission->GetID() << " " << team->GetID() << " " << problem->GetID() << " " << submission->GetCodeType() << " " << submission->GetStatus() << " " << submission->GetTimeMS();
			}
			outFile << endl;
		}

		outFile.close();
	}
	void Competition::ClearAll()
	{
		map<unsigned short, Submission *> &submissions = Submission::GetSubmissionsByID();
		if(submissions.size())
			for(map<unsigned short, Submission *>::iterator it = submissions.begin(); it != submissions.end(); it++)
			{
				Submission *submission = it->second;
				fileDelete(submission->GetSourceFile().c_str());
				string base = submission->GetBase();
				string logFile(base), execFile(base);
				logFile.append(".log");
				execFile.append(".out");
				fileDelete(logFile.c_str());
				fileDelete(execFile.c_str());
			}
		map<unsigned short, Team *> &teamsByID = Team::GetTeamsByID();
		for(map<unsigned short, Team *>::iterator it = teamsByID.begin(); it != teamsByID.end(); it++)
		{
			Team *team = it->second;
			team->Reset();
		}
		Problem::ClearSolvers();
		Question::Cleanup();
		Submission::Cleanup();
		fileDelete("compo/compo.txt");
		fileDelete("compo/scores.txt");
	}
}
<|endoftext|>


<commit_before>//************************************************************/
//
//	Spectrum
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		19.09.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/

#include <iostream>

#include "SPXROOT.h"
#include "SPXAtlasStyle.h"
#include "SPXSteeringFile.h"
#include "SPXAnalysis.h"
#include "SPXException.h"

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

	if((argc - 1) < 1) {
		std::cout << "@usage: Spectrum [-p] <steering_file>" << std::endl;
		exit(0);
	}

	std::string file;

	Test::TestFeatures = false;
	bool drawApplication = true;

	std::cout << "==================================" << std::endl;
	std::cout << "      	   Spectrum		        " << std::endl;
	std::cout << "==================================" << std::endl <<std::endl;

	//Process arguments
	for(int i = 1; i < argc; i++) {
		std::string arg = std::string(argv[i]);

		//PNG Only mode
		if(!arg.compare("-p")) {
			drawApplication = false;
		}

		//Test mode (implements test features)
		else if(!arg.compare("-t")) {
			Test::TestFeatures = true;
		}

		//No known flag: Treat as file name
		else {
			file = arg;
		}
	}

	//Set Atlas Style (SPXAtlasStyle.h)
	SetAtlasStyle();

	TApplication *spectrum;

	if(drawApplication) {
		spectrum = new TApplication("Spectrum",0,0);
		spectrum->SetReturnFromRun(true);
	}

	SPXSteeringFile steeringFile = SPXSteeringFile(file);

	//=========================================================
	//   Configuration
	//=========================================================
    try {
    	steeringFile.ParseAll(false);
		steeringFile.PrintAll();
    } catch(const SPXException &e) {
    	std::cerr << e.what() << std::endl;
    	std::cerr << "FATAL: Could not parse the steering file: " << file << std::endl;
    	exit(-1);
    }

    	//=========================================================
	//     Analysis
	//=========================================================
    try {
    	SPXAnalysis analysis = SPXAnalysis(&steeringFile);
    	analysis.Run();
    } catch(const SPXException &e) {
    	std::cerr << e.what() << std::endl;
    	std::cerr << "FATAL: Unable to perform successful analysis" << std::endl;
    	exit(-1);
    }

	if(drawApplication) {
		spectrum->Run(kTRUE);
	}

	return 0;
}
<commit_msg>Adding -t flag for testing features<commit_after>//************************************************************/
//
//	Spectrum
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		19.09.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/

#include <iostream>

#include "SPXROOT.h"
#include "SPXAtlasStyle.h"
#include "SPXSteeringFile.h"
#include "SPXAnalysis.h"
#include "SPXException.h"

namespace Test {
	bool TestFeatures = false;
}

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

	if((argc - 1) < 1) {
		std::cout << "@usage: Spectrum [-p] <steering_file>" << std::endl;
		exit(0);
	}

	std::string file;

	Test::TestFeatures = false;
	bool drawApplication = true;

	std::cout << "==================================" << std::endl;
	std::cout << "      	   Spectrum		        " << std::endl;
	std::cout << "==================================" << std::endl <<std::endl;

	//Process arguments
	for(int i = 1; i < argc; i++) {
		std::string arg = std::string(argv[i]);

		//PNG Only mode
		if(!arg.compare("-p")) {
			drawApplication = false;
		}

		//Test mode (implements test features)
		else if(!arg.compare("-t")) {
			Test::TestFeatures = true;
		}

		//No known flag: Treat as file name
		else {
			file = arg;
		}
	}

	//Set Atlas Style (SPXAtlasStyle.h)
	SetAtlasStyle();

	TApplication *spectrum;

	if(drawApplication) {
		spectrum = new TApplication("Spectrum",0,0);
		spectrum->SetReturnFromRun(true);
	}

	SPXSteeringFile steeringFile = SPXSteeringFile(file);

	//=========================================================
	//   Configuration
	//=========================================================
    try {
    	steeringFile.ParseAll(false);
		steeringFile.PrintAll();
    } catch(const SPXException &e) {
    	std::cerr << e.what() << std::endl;
    	std::cerr << "FATAL: Could not parse the steering file: " << file << std::endl;
    	exit(-1);
    }

    	//=========================================================
	//     Analysis
	//=========================================================
    try {
    	SPXAnalysis analysis = SPXAnalysis(&steeringFile);
    	analysis.Run();
    } catch(const SPXException &e) {
    	std::cerr << e.what() << std::endl;
    	std::cerr << "FATAL: Unable to perform successful analysis" << std::endl;
    	exit(-1);
    }

	if(drawApplication) {
		spectrum->Run(kTRUE);
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * C S O U N D
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "Soundfile.hpp"
#include "Conversions.hpp"

namespace csound
{
  Soundfile::Soundfile()
  {
    initialize();
  }
  Soundfile::~Soundfile()
  {
    close();
  }
  void Soundfile::initialize()
  {
    sndfile = 0;
    std::memset(&sf_info, 0, sizeof(sf_info));
  }
  int Soundfile::getFramesPerSecond() const
  {
    return sf_info.samplerate;
  }
  void Soundfile::setFramesPerSecond(int framesPerSecond)
  {
    sf_info.samplerate = framesPerSecond;
  }
  int Soundfile::getChannelsPerFrame() const
  {
    return sf_info.channels;
  }
  void Soundfile::setChannelsPerFrame(int channelsPerFrame)
  {
    sf_info.channels = channelsPerFrame;
  }
  int Soundfile::getFormat() const
  {
    return sf_info.format;
  }
  void Soundfile::setFormat(int format)
  {
    sf_info.format = format;
  }
  int Soundfile::getFrames() const
  {
    return (int) sf_info.frames;
  }
  int Soundfile::open(std::string filename)
  {
    close();
    sndfile = sf_open(filename.c_str(), SFM_RDWR, &sf_info);
    if (!sndfile) {
      error();
      return -1;
    }
    return 0;
  }
  int Soundfile::create(std::string filename, int framesPerSecond, int channelsPerFrame, int format)
  {
    close();
    sf_info.samplerate = framesPerSecond;
    sf_info.channels = channelsPerFrame;
    sf_info.format = format;
    sndfile = sf_open(filename.c_str(), SFM_RDWR, &sf_info);
    if (!sndfile) {
      error();
      return -1;
    }
    return 0;
  }
  int Soundfile::seek(int frames, int whence)
  {
    int frame = sf_seek(sndfile, frames, whence);
    if (frame == -1) {
      error();
    }
    return frame;
  }
  double Soundfile::seekSeconds(double seconds, int whence)
  {
    int frame = int(seconds * double(sf_info.samplerate));
    frame = sf_seek(sndfile, frame, whence);
    if (frame == -1) {
      error();
    }
    return frame;
  }
  int Soundfile::readFrame(double *outputFrame)
  {
    return sf_readf_double(sndfile, outputFrame, 1);
  }
  int Soundfile::writeFrame(double *inputFrame)
  {
    return sf_writef_double(sndfile, inputFrame, 1);
  }
  int Soundfile::readFrames(double *outputFrames, int samples)
  {
    return sf_read_double(sndfile, outputFrames, samples);
  }
  int Soundfile::writeFrames(double *inputFrames, int samples)
  {
    return sf_write_double(sndfile, inputFrames, samples);
  }
  int Soundfile::mixFrames(double *inputFrames, int samples, double *mixedFrames)
  {
    size_t position = sf_seek(sndfile, 0, SEEK_CUR);
    sf_readf_double(sndfile, mixedFrames, samples);
    for (int i = 0; i < samples; i++) {
      mixedFrames[i] += inputFrames[i];
    }
    sf_seek(sndfile, position, SEEK_SET);
    return sf_writef_double(sndfile, mixedFrames, samples);
  }
  void Soundfile::updateHeader()
  {
    /* int status = */ sf_command(sndfile, SFC_UPDATE_HEADER_NOW, 0, 0);
  }
  int Soundfile::close()
  {
    int status = 0;
    if (sndfile) {
      status = sf_close(sndfile);
      if (status) {
        std::cerr << sf_error_number(status) << std::endl;
      }
    }
    initialize();
    return status;
  }
  void Soundfile::error() const
  {
    std::cerr << sf_strerror(sndfile) << std::endl;
  }

  void Soundfile::blank(double duration)
  {
    seekSeconds(0.0);
    std::vector<double> frame;
    frame.resize(getChannelsPerFrame());
    int framesToWrite = int(duration * getFramesPerSecond());
    for (int i = 0; i < framesToWrite; i++) {
      sf_writef_double(sndfile, &frame.front(), 1);
    }
    updateHeader();
    seekSeconds(0.0);
  }

  void Soundfile::jonesParksGrain(double centerTimeSeconds,
                                  double durationSeconds,
                                  double beginningFrequencyHz,
                                  double centerFrequencyHz,
                                  double centerAmplitude,
                                  double centerPhaseOffsetRadians,
                                  double pan,
                                  bool synchronousPhase,
                                  bool buffer)
  {
    if (synchronousPhase) {
      double wavelengthSeconds = 1.0 / centerFrequencyHz;
      double wavelengths = centerTimeSeconds / wavelengthSeconds;
      double wholecycles = 0;
      double fractionalCycle = std::modf(wavelengths, &wholecycles);
      centerPhaseOffsetRadians = Conversions::get2PI() * fractionalCycle;
    }
    double leftGain = Conversions::leftPan(pan);
    double rightGain = Conversions::rightPan(pan);
    double centerTime = - (durationSeconds / 2.0);
    int samplingRate = getFramesPerSecond();
    double samplingInterval = 1.0 / double(samplingRate);
    size_t frameCount = size_t(2.0 * durationSeconds / samplingInterval);
    double gaussianWidth = std::exp(1.0) / std::pow(durationSeconds / 4.0, 2.0);
    double endingFrequencyHz = centerFrequencyHz + (centerFrequencyHz - beginningFrequencyHz);
    double chirpRate = (endingFrequencyHz - beginningFrequencyHz) / durationSeconds;
    double omega = Conversions::get2PI() * centerFrequencyHz;
    std::complex<double> c0(log(centerAmplitude) - (gaussianWidth * std::pow(centerTime, 2.0)),
                            (centerPhaseOffsetRadians - (chirpRate / 2.0) * centerTime) - (omega * centerTime));
    std::complex<double> c1(-2.0 * gaussianWidth * samplingInterval * centerTime,
                            - (samplingInterval * (chirpRate * centerTime + omega)));
    std::complex<double> c2 = (-std::complex<double>(gaussianWidth, chirpRate / 2.0)) * std::pow(samplingInterval, 2.0);
    std::complex<double> exp_2_c2 = std::exp(2.0 * c2);
    std::complex<double> h0 = std::exp(c1 + c2);
    std::complex<double> h1(0.0, 0.0);
    std::complex<double> f0 = std::exp(c0);
    std::complex<double> f1(0.0, 0.0);
    size_t channelCount = getChannelsPerFrame();
    grainOutput.resize(frameCount, channelCount);
    grainBuffer.resize(frameCount, channelCount);
    for(size_t frameI = 0; frameI < frameCount; frameI++) {
      double sample = f0.real();
      //std::cout << sample << std::endl;
      if (channelCount == 2) {
        grainOutput(frameI, 0) += (leftGain * sample);
        grainOutput(frameI, 1) += (rightGain * sample);
      } else if (channelCount == 1) {
        grainOutput(frameI, 0) += sample;
      } else {
        for(size_t channelI = 0; channelI < channelCount; channelI++) {
          grainOutput(frameI, channelI) += sample;
        }
      }
      h1 = h0 * exp_2_c2;
      h0 = h1;
      f1 = h1 * f0;
      f0 = f1;
    }
    sampleCount = frameCount * channelCount;
    startTimeSeconds = centerTimeSeconds - (durationSeconds / 2.0);
    if (!buffer) {
      mixGrain();
    }
  }

  void Soundfile::cosineGrain(double centerTimeSeconds,
                              double durationSeconds,
                              double frequencyHz,
                              double amplitude,
                              double phaseOffsetRadians,
                              double pan,
                              bool synchronousPhase,
                              bool buffer)
  {
    if (synchronousPhase) {
      double wavelengthSeconds = 1.0 / frequencyHz;
      double wavelengths = centerTimeSeconds / wavelengthSeconds;
      double wholecycles = 0;
      double fractionalCycle = std::modf(wavelengths, &wholecycles);
      phaseOffsetRadians = Conversions::get2PI() * fractionalCycle;
    }
    size_t frameN = size_t(Conversions::round(durationSeconds * getFramesPerSecond()));
    size_t channelN = getChannelsPerFrame();
    grainOutput.resize(frameN, channelN);
    grainBuffer.resize(frameN, channelN);
    double leftGain = Conversions::leftPan(pan);
    double rightGain = Conversions::rightPan(pan);
    // The signal is a cosine sinusoid.
    double framesPerSecond = double(getFramesPerSecond());
    double sinusoidRadiansPerFrame = Conversions::get2PI() * frequencyHz / framesPerSecond;
    double sinusoidCoefficient = 2.0 * std::cos(sinusoidRadiansPerFrame);
    // The initial frame.
    double sinusoid1 = std::cos(phaseOffsetRadians);
    // What would have been the previous frame.
    double sinusoid2 = std::cos(-sinusoidRadiansPerFrame + phaseOffsetRadians);
    // The envelope is exactly 1 cycle of a cosine sinusoid, offset by -1.
    double envelopeFrequencyHz = 1.0 / durationSeconds;
    double envelopeRadiansPerFrame =  Conversions::get2PI() * envelopeFrequencyHz / framesPerSecond;
    double envelopeCoefficient = 2.0 * std::cos(envelopeRadiansPerFrame);
    // The initial frame.
    double envelope1 = std::cos(0.0);
    // What would have been the previous frame.
    double envelope2 = std::cos(-envelopeRadiansPerFrame);
     // Precompute grain into buffer.
    double signal = 0.0;
    double temporary = 0.0;
    double envelopeTemp = 0.0;
    for(size_t frameI = 0; frameI < frameN; frameI++)
      {
        signal = (sinusoid1 * (envelope1 - 1.0)) * amplitude;
        if (channelN == 2) {
          grainOutput(frameI, 0) += (leftGain * signal);
          grainOutput(frameI, 1) += (rightGain * signal);
        } else if (channelN == 1) {
          grainOutput(frameI, 0) += signal;
        } else {
          for(size_t channelI = 0; channelI < channelN; channelI++) {
            grainOutput(frameI, channelI) += signal;
          }
        }
        temporary = sinusoid1;
        sinusoid1 = sinusoidCoefficient * sinusoid1 - sinusoid2;
        sinusoid2 = temporary;
        temporary = envelope1;
        envelope1 = envelopeCoefficient * envelope1 - envelope2;
        envelope2 = temporary;
      }
    sampleCount = frameN * channelN;
    startTimeSeconds = centerTimeSeconds - (durationSeconds / 2.0);
    if (!buffer) {
      mixGrain();
    }
  }

  void Soundfile::mixGrain()
  {
    seekSeconds(startTimeSeconds);
    mixFrames(&grainOutput(0, 0), sampleCount, &grainBuffer(0, 0));
    grainOutput *= 0.0;
  }
}

<commit_msg>no message<commit_after>/*
 * C S O U N D
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "Soundfile.hpp"
#include "Conversions.hpp"

namespace csound
{
  Soundfile::Soundfile()
  {
    initialize();
  }
  Soundfile::~Soundfile()
  {
    close();
  }
  void Soundfile::initialize()
  {
    sndfile = 0;
    std::memset(&sf_info, 0, sizeof(sf_info));
  }
  int Soundfile::getFramesPerSecond() const
  {
    return sf_info.samplerate;
  }
  void Soundfile::setFramesPerSecond(int framesPerSecond)
  {
    sf_info.samplerate = framesPerSecond;
  }
  int Soundfile::getChannelsPerFrame() const
  {
    return sf_info.channels;
  }
  void Soundfile::setChannelsPerFrame(int channelsPerFrame)
  {
    sf_info.channels = channelsPerFrame;
  }
  int Soundfile::getFormat() const
  {
    return sf_info.format;
  }
  void Soundfile::setFormat(int format)
  {
    sf_info.format = format;
  }
  int Soundfile::getFrames() const
  {
    return (int) sf_info.frames;
  }
  int Soundfile::open(std::string filename)
  {
    close();
    sndfile = sf_open(filename.c_str(), SFM_RDWR, &sf_info);
    if (!sndfile) {
      error();
      return -1;
    }
    return 0;
  }
  int Soundfile::create(std::string filename, int framesPerSecond, int channelsPerFrame, int format)
  {
    close();
    sf_info.samplerate = framesPerSecond;
    sf_info.channels = channelsPerFrame;
    sf_info.format = format;
    sndfile = sf_open(filename.c_str(), SFM_RDWR, &sf_info);
    if (!sndfile) {
      error();
      return -1;
    }
    return 0;
  }
  int Soundfile::seek(int frames, int whence)
  {
    int frame = sf_seek(sndfile, frames, whence);
    if (frame == -1) {
      error();
    }
    return frame;
  }
  double Soundfile::seekSeconds(double seconds, int whence)
  {
    int frame = int(seconds * double(sf_info.samplerate));
    frame = sf_seek(sndfile, frame, whence);
    if (frame == -1) {
      error();
    }
    return frame;
  }
  int Soundfile::readFrame(double *outputFrame)
  {
    return sf_readf_double(sndfile, outputFrame, 1);
  }
  int Soundfile::writeFrame(double *inputFrame)
  {
    return sf_writef_double(sndfile, inputFrame, 1);
  }
  int Soundfile::readFrames(double *outputFrames, int samples)
  {
    return sf_read_double(sndfile, outputFrames, samples);
  }
  int Soundfile::writeFrames(double *inputFrames, int samples)
  {
    return sf_write_double(sndfile, inputFrames, samples);
  }
  int Soundfile::mixFrames(double *inputFrames, int samples, double *mixedFrames)
  {
    size_t position = sf_seek(sndfile, 0, SEEK_CUR);
    sf_readf_double(sndfile, mixedFrames, samples);
    for (int i = 0; i < samples; i++) {
      mixedFrames[i] += inputFrames[i];
    }
    sf_seek(sndfile, position, SEEK_SET);
    return sf_writef_double(sndfile, mixedFrames, samples);
  }
  void Soundfile::updateHeader()
  {
    /* int status = */ sf_command(sndfile, SFC_UPDATE_HEADER_NOW, 0, 0);
  }
  int Soundfile::close()
  {
    int status = 0;
    if (sndfile) {
      status = sf_close(sndfile);
      if (status) {
        std::cerr << sf_error_number(status) << std::endl;
      }
    }
    initialize();
    return status;
  }
  void Soundfile::error() const
  {
    std::cerr << sf_strerror(sndfile) << std::endl;
  }

  void Soundfile::blank(double duration)
  {
    seekSeconds(0.0);
    std::vector<double> frame;
    frame.resize(getChannelsPerFrame());
    int framesToWrite = int(duration * getFramesPerSecond());
    for (int i = 0; i < framesToWrite; i++) {
      sf_writef_double(sndfile, &frame.front(), 1);
    }
    updateHeader();
    seekSeconds(0.0);
  }

  void Soundfile::jonesParksGrain(double centerTimeSeconds,
                                  double durationSeconds,
                                  double beginningFrequencyHz,
                                  double centerFrequencyHz,
                                  double centerAmplitude,
                                  double centerPhaseOffsetRadians,
                                  double pan,
                                  bool synchronousPhase,
                                  bool buffer)
  {
    if (synchronousPhase) {
      double wavelengthSeconds = 1.0 / centerFrequencyHz;
      double wavelengths = centerTimeSeconds / wavelengthSeconds;
      double wholecycles = 0;
      double fractionalCycle = std::modf(wavelengths, &wholecycles);
      centerPhaseOffsetRadians = Conversions::get2PI() * fractionalCycle;
    }
    double leftGain = Conversions::leftPan(pan);
    double rightGain = Conversions::rightPan(pan);
    double centerTime = - (durationSeconds / 2.0);
    int samplingRate = getFramesPerSecond();
    double samplingInterval = 1.0 / double(samplingRate);
    size_t frameCount = size_t(2.0 * durationSeconds / samplingInterval);
    double gaussianWidth = std::exp(1.0) / std::pow(durationSeconds / 4.0, 2.0);
    double endingFrequencyHz = centerFrequencyHz + (centerFrequencyHz - beginningFrequencyHz);
    double chirpRate = (endingFrequencyHz - beginningFrequencyHz) / durationSeconds;
    double omega = Conversions::get2PI() * centerFrequencyHz;
    std::complex<double> c0(log(centerAmplitude) - (gaussianWidth * std::pow(centerTime, 2.0)),
                            (centerPhaseOffsetRadians - (chirpRate / 2.0) * centerTime) - (omega * centerTime));
    std::complex<double> c1(-2.0 * gaussianWidth * samplingInterval * centerTime,
                            - (samplingInterval * (chirpRate * centerTime + omega)));
    std::complex<double> c2 = (-std::complex<double>(gaussianWidth, chirpRate / 2.0)) * std::pow(samplingInterval, 2.0);
    std::complex<double> exp_2_c2 = std::exp(2.0 * c2);
    std::complex<double> h0 = std::exp(c1 + c2);
    std::complex<double> h1(0.0, 0.0);
    std::complex<double> f0 = std::exp(c0);
    std::complex<double> f1(0.0, 0.0);
    size_t channelCount = getChannelsPerFrame();
    grainOutput.resize(frameCount, channelCount);
    grainBuffer.resize(frameCount, channelCount);
    for(size_t frameI = 0; frameI < frameCount; frameI++) {
      double sample = f0.real();
      //std::cout << sample << std::endl;
      if (channelCount == 2) {
        grainOutput(frameI, 0) += (leftGain * sample);
        grainOutput(frameI, 1) += (rightGain * sample);
      } else if (channelCount == 1) {
        grainOutput(frameI, 0) += sample;
      } else {
        for(size_t channelI = 0; channelI < channelCount; channelI++) {
          grainOutput(frameI, channelI) += sample;
        }
      }
      h1 = h0 * exp_2_c2;
      h0 = h1;
      f1 = h1 * f0;
      f0 = f1;
    }
    sampleCount = frameCount * channelCount;
    startTimeSeconds = centerTimeSeconds - (durationSeconds / 2.0);
    if (!buffer) {
      mixGrain();
    }
  }

  void Soundfile::cosineGrain(double centerTimeSeconds,
                              double durationSeconds,
                              double frequencyHz,
                              double amplitude,
                              double phaseOffsetRadians,
                              double pan,
                              bool synchronousPhase,
                              bool buffer)
  {
    if (synchronousPhase) {
      double wavelengthSeconds = 1.0 / frequencyHz;
      double wavelengths = centerTimeSeconds / wavelengthSeconds;
      double wholecycles = 0;
      double fractionalCycle = std::modf(wavelengths, &wholecycles);
      phaseOffsetRadians = Conversions::get2PI() * fractionalCycle;
    }
    size_t frameN = size_t(Conversions::round(durationSeconds * getFramesPerSecond()));
    size_t channelN = getChannelsPerFrame();
    grainOutput.resize(frameN, channelN);
    grainBuffer.resize(frameN, channelN);
    double leftGain = Conversions::leftPan(pan);
    double rightGain = Conversions::rightPan(pan);
    // The signal is a cosine sinusoid.
    double framesPerSecond = double(getFramesPerSecond());
    double sinusoidRadiansPerFrame = Conversions::get2PI() * frequencyHz / framesPerSecond;
    double sinusoidCoefficient = 2.0 * std::cos(sinusoidRadiansPerFrame);
    // The initial frame.
    double sinusoid1 = std::cos(phaseOffsetRadians);
    // What would have been the previous frame.
    double sinusoid2 = std::cos(-sinusoidRadiansPerFrame + phaseOffsetRadians);
    // The envelope is exactly 1 cycle of a cosine sinusoid, offset by -1.
    double envelopeFrequencyHz = 1.0 / durationSeconds;
    double envelopeRadiansPerFrame =  Conversions::get2PI() * envelopeFrequencyHz / framesPerSecond;
    double envelopeCoefficient = 2.0 * std::cos(envelopeRadiansPerFrame);
    // The initial frame.
    double envelope1 = std::cos(0.0);
    // What would have been the previous frame.
    double envelope2 = std::cos(-envelopeRadiansPerFrame);
     // Precompute grain into buffer.
    double signal = 0.0;
    double temporary = 0.0;
    for(size_t frameI = 0; frameI < frameN; frameI++)
      {
        signal = (sinusoid1 * (envelope1 - 1.0)) * amplitude;
        if (channelN == 2) {
          grainOutput(frameI, 0) += (leftGain * signal);
          grainOutput(frameI, 1) += (rightGain * signal);
        } else if (channelN == 1) {
          grainOutput(frameI, 0) += signal;
        } else {
          for(size_t channelI = 0; channelI < channelN; channelI++) {
            grainOutput(frameI, channelI) += signal;
          }
        }
        temporary = sinusoid1;
        sinusoid1 = sinusoidCoefficient * sinusoid1 - sinusoid2;
        sinusoid2 = temporary;
        temporary = envelope1;
        envelope1 = envelopeCoefficient * envelope1 - envelope2;
        envelope2 = temporary;
      }
    sampleCount = frameN * channelN;
    startTimeSeconds = centerTimeSeconds - (durationSeconds / 2.0);
    if (!buffer) {
      mixGrain();
    }
  }

  void Soundfile::mixGrain()
  {
    seekSeconds(startTimeSeconds);
    mixFrames(&grainOutput(0, 0), sampleCount, &grainBuffer(0, 0));
    grainOutput *= 0.0;
  }
}

<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: preferences.C,v 1.2 2003/08/26 15:01:11 amoll Exp $
//

#include <BALL/VIEW/DIALOGS/preferences.h>
#include <BALL/FORMAT/INIFile.h>

namespace BALL
{
	namespace VIEW
	{

		Preferences::Preferences(QWidget* parent, const char* name, int width, int height)
			throw()
			:	QTabDialog(parent, name, FALSE, 208),
				number_of_tabs_(0)
		{
			setApplyButton();
			setCancelButton();

			resize(width,height);
			setMinimumSize(width, height);
			setMaximumSize(width, height);

			connect(this, SIGNAL(cancelButtonPressed()), SLOT(hide()));
		}

		Preferences::~Preferences()
			throw()
		{
			#ifdef BALL_VIEW_DEBUG
				Log.info() << "Destructing object " << (void *)this
									 << " of class " << RTTI::getName<Preferences>() << std::endl;
			#endif

			clear();
		}

		void Preferences::clear()
			throw()
		{
		}

		bool Preferences::hasTabs()
			throw()
		{
			return (number_of_tabs_ > 0);
		}

		void Preferences::insertTab(QWidget *child, const QString &name)
			throw()
		{
			++number_of_tabs_;
			addTab(child, name);
		}

		void Preferences::removeTab(QWidget *child)
			throw()
		{
			--number_of_tabs_;
			removePage(child);
		}

		void Preferences::fetchPreferences(INIFile& inifile)
			throw()
		{
			//
			// the geometry of the preferences window
			//
			int x_pos = x();
			int y_pos = y();

			if (inifile.hasEntry("WINDOWS", "Preferences::x"))
			{
				x_pos = inifile.getValue("WINDOWS", "Preferences::x").toInt();
			}
			if (inifile.hasEntry("WINDOWS", "Preferences::y"))
			{
				y_pos = inifile.getValue("WINDOWS", "Preferences::y").toInt();
			}

			move(x_pos, y_pos);
		}

		void Preferences::writePreferences(INIFile& inifile)
			throw()
		{
			// the display window position
			inifile.insertValue("WINDOWS", "Preferences::x", String(x()));
			inifile.insertValue("WINDOWS", "Preferences::y", String(y()));
		}

		void Preferences::openDialog()
		{
			show();
			raise();
		}

	} // namespace VIEW
} // namespace BALL

<commit_msg>now setting size of all child tabs<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: preferences.C,v 1.3 2003/08/28 21:28:20 amoll Exp $
//

#include <BALL/VIEW/DIALOGS/preferences.h>
#include <BALL/FORMAT/INIFile.h>

namespace BALL
{
	namespace VIEW
	{

		Preferences::Preferences(QWidget* parent, const char* name, int width, int height)
			throw()
			:	QTabDialog(parent, name, FALSE, 208),
				number_of_tabs_(0)
		{
			setApplyButton();
			setCancelButton();

			resize(width,height);
			setMinimumSize(width, height);
			setMaximumSize(width, height);

			connect(this, SIGNAL(cancelButtonPressed()), SLOT(hide()));
		}

		Preferences::~Preferences()
			throw()
		{
			#ifdef BALL_VIEW_DEBUG
				Log.info() << "Destructing object " << (void *)this
									 << " of class " << RTTI::getName<Preferences>() << std::endl;
			#endif

			clear();
		}

		void Preferences::clear()
			throw()
		{
		}

		bool Preferences::hasTabs()
			throw()
		{
			return (number_of_tabs_ > 0);
		}

		void Preferences::insertTab(QWidget *child, const QString &name)
			throw()
		{
			++number_of_tabs_;
			addTab(child, name);

			// set size for all child tabs
			child->resize(380,210);
		}

		void Preferences::removeTab(QWidget *child)
			throw()
		{
			--number_of_tabs_;
			removePage(child);
		}

		void Preferences::fetchPreferences(INIFile& inifile)
			throw()
		{
			//
			// the geometry of the preferences window
			//
			int x_pos = x();
			int y_pos = y();

			if (inifile.hasEntry("WINDOWS", "Preferences::x"))
			{
				x_pos = inifile.getValue("WINDOWS", "Preferences::x").toInt();
			}
			if (inifile.hasEntry("WINDOWS", "Preferences::y"))
			{
				y_pos = inifile.getValue("WINDOWS", "Preferences::y").toInt();
			}

			move(x_pos, y_pos);
		}

		void Preferences::writePreferences(INIFile& inifile)
			throw()
		{
			// the display window position
			inifile.insertValue("WINDOWS", "Preferences::x", String(x()));
			inifile.insertValue("WINDOWS", "Preferences::y", String(y()));
		}

		void Preferences::openDialog()
		{
			show();
			raise();
		}

	} // namespace VIEW
} // namespace BALL

<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * ADIOS is freely available under the terms of the BSD license described
 * in the COPYING file in the top level directory of this source distribution.
 *
 * Copyright (c) 2008 - 2009.  UT-BATTELLE, LLC. All rights reserved.

   A dummy MPI implementation for the BP READ API, to have an MPI-free version
   of the API
*/

#include "mpidummy.h"

#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <numeric>

#include <chrono>
#include <string>

// remove warnings on Windows
#ifdef _WIN32
#pragma warning(disable : 4996) // fopen
#pragma warning(disable : 4477) // strcpy, sprintf
#endif

namespace adios2
{
namespace helper
{
namespace mpidummy
{

int MPI_Init(int * /*argc*/, char *** /*argv*/) { return MPI_SUCCESS; }

int MPI_Finalize() { return MPI_SUCCESS; }

int MPI_Initialized(int *flag)
{
    *flag = 1;
    return MPI_SUCCESS;
}

int MPI_Finalized(int *flag)
{
    *flag = 0;
    return MPI_SUCCESS;
}

int MPI_Comm_split(MPI_Comm /*comm*/, int /*color*/, int /*key*/,
                   MPI_Comm * /*comm_out*/)
{
    return MPI_SUCCESS;
}

int MPI_Barrier(MPI_Comm /*comm*/) { return MPI_SUCCESS; }

int MPI_Bcast(void * /*buffer*/, int /*count*/, MPI_Datatype /*datatype*/,
              int /*root*/, MPI_Comm /*comm*/)
{
    return MPI_SUCCESS;
}

int MPI_Comm_dup(MPI_Comm comm, MPI_Comm *newcomm)
{
    *newcomm = comm;
    return MPI_SUCCESS;
}

int MPI_Comm_rank(MPI_Comm /*comm*/, int *rank)
{
    *rank = 0;
    return MPI_SUCCESS;
}

int MPI_Comm_size(MPI_Comm /*comm*/, int *size)
{
    *size = 1;
    return MPI_SUCCESS;
}

int MPI_Comm_free(MPI_Comm *comm)
{
    *comm = 0;
    return MPI_SUCCESS;
}

#ifndef ADIOS2_HAVE_MPI
MPI_Comm MPI_Comm_f2c(MPI_Fint comm) { return comm; }
#endif

int MPI_Gather(const void *sendbuf, int sendcnt, MPI_Datatype sendtype,
               void *recvbuf, int recvcnt, MPI_Datatype recvtype, int root,
               MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    int n;
    size_t nsent = 0, nrecv = 0;
    if (sendcnt > 0 && !sendbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (recvcnt > 0 && !recvbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (root != 0)
    {
        return MPI_ERR_ROOT;
    }
    if (comm == MPI_COMM_NULL)
    {
        return MPI_ERR_COMM;
    }

    ier = mpidummy::MPI_Type_size(sendtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nsent = n * sendcnt;

    ier = mpidummy::MPI_Type_size(recvtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nrecv = n * recvcnt;

    if (nrecv != nsent)
    {
        ier = MPI_ERR_COUNT;
    }

    if (ier == MPI_SUCCESS)
    {
        std::memcpy(recvbuf, sendbuf, nsent);
    }

    return ier;
}

int MPI_Gatherv(const void *sendbuf, int sendcnt, MPI_Datatype sendtype,
                void *recvbuf, const int *recvcnts, const int * /*displs */,
                MPI_Datatype recvtype, int root, MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    if (*recvcnts != sendcnt)
    {
        ier = MPI_ERR_COUNT;
        return ier;
    }

    ier = mpidummy::MPI_Gather(sendbuf, sendcnt, sendtype, recvbuf, *recvcnts,
                               recvtype, root, comm);
    return ier;
}

int MPI_Allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
                  void *recvbuf, int recvcount, MPI_Datatype recvtype,
                  MPI_Comm comm)
{
    return mpidummy::MPI_Gather(sendbuf, sendcount, sendtype, recvbuf,
                                recvcount, recvtype, 0, comm);
}

int MPI_Scatter(const void *sendbuf, int sendcnt, MPI_Datatype sendtype,
                void *recvbuf, int recvcnt, MPI_Datatype recvtype, int root,
                MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    int n;
    size_t nsent = 0, nrecv = 0;
    if (sendcnt > 0 && !sendbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (recvcnt > 0 && !recvbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (root != 0)
    {
        return MPI_ERR_ROOT;
    }
    if (comm == MPI_COMM_NULL)
    {
        return MPI_ERR_COMM;
    }

    ier = mpidummy::MPI_Type_size(sendtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nsent = n * sendcnt;

    ier = mpidummy::MPI_Type_size(recvtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nrecv = n * recvcnt;

    if (nrecv != nsent)
    {
        ier = MPI_ERR_COUNT;
    }

    if (ier == MPI_SUCCESS)
    {
        std::memcpy(recvbuf, sendbuf, nsent);
    }

    return ier;
}

int MPI_Scatterv(const void *sendbuf, const int *sendcnts, const int *displs,
                 MPI_Datatype sendtype, void *recvbuf, int recvcnt,
                 MPI_Datatype recvtype, int root, MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    if (!sendcnts || !displs)
    {
        ier = MPI_ERR_BUFFER;
    }

    if (ier == MPI_SUCCESS)
    {
        ier = mpidummy::MPI_Scatter(sendbuf, *sendcnts, sendtype, recvbuf,
                                    recvcnt, recvtype, root, comm);
    }

    return ier;
}

int MPI_Recv(void * /*recvbuffer*/, int /*count*/, MPI_Datatype /*type*/,
             int /*source*/, int /*tag*/, MPI_Comm /*comm*/,
             MPI_Status * /*status*/)
{
    return 0;
}

int MPI_Irecv(void * /*recvbuffer*/, int /*count*/, MPI_Datatype /*type*/,
              int /*source*/, int /*tag*/, MPI_Comm /*comm*/,
              MPI_Request * /*request*/)

{
    return 0;
}

int MPI_Send(const void * /*sendbuffer*/, int /*count*/, MPI_Datatype /*type*/,
             int /*destination*/, int /*tag*/, MPI_Comm /*comm*/)
{
    return 0;
}

int MPI_Isend(const void * /*recvbuffer*/, int /*count*/, MPI_Datatype /*type*/,
              int /*source*/, int /*tag*/, MPI_Comm /*comm*/,
              MPI_Request * /*request*/)
{
    return 0;
}

int MPI_Wait(MPI_Request * /*request*/, MPI_Status * /*status*/) { return 0; }

#ifndef ADIOS2_HAVE_MPI

int MPI_File_open(MPI_Comm /*comm*/, const char *filename, int amode,
                  MPI_Info /*info*/, MPI_File *fh)
{
    std::string mode;
    if (amode | MPI_MODE_RDONLY)
    {
        mode += "r";
    }
    if (amode | MPI_MODE_WRONLY)
    {
        mode += "w";
    }
    if (amode | MPI_MODE_APPEND)
    {
        mode += "a";
    }
    mode += "b";

    *fh = std::fopen(filename, mode.c_str());
    if (!*fh)
    {
        return -1;
    }
    return MPI_SUCCESS;
}

int MPI_File_close(MPI_File *fh) { return fclose(*fh); }

int MPI_File_get_size(MPI_File fh, MPI_Offset *size)
{
    long curpos = std::ftell(fh);
    fseek(fh, 0, SEEK_END); // go to end, returned is the size in bytes
    long endpos = std::ftell(fh);
    std::fseek(fh, curpos, SEEK_SET); // go back where we were
    *size = static_cast<MPI_Offset>(endpos);
    // printf("MPI_File_get_size: fh=%d, size=%lld\n", fh, *size);
    return MPI_SUCCESS;
}

int MPI_File_read(MPI_File fh, void *buf, int count, MPI_Datatype datatype,
                  MPI_Status *status)
{
    // FIXME: int count can read only 2GB (*datatype size) array at max
    size_t bytes_to_read = static_cast<size_t>(count) * datatype;
    size_t bytes_read;
    bytes_read = std::fread(buf, 1, bytes_to_read, fh);
    if (bytes_read != bytes_to_read)
    {
        return -2;
    }
    *status = bytes_read;
    // printf("MPI_File_read: fh=%d, count=%d, typesize=%d, bytes read=%lld\n",
    // fh, count, datatype, *status);
    return MPI_SUCCESS;
}

int MPI_File_seek(MPI_File fh, MPI_Offset offset, int whence)
{
    return std::fseek(fh, offset, whence) == MPI_SUCCESS;
}

int MPI_Get_count(const MPI_Status *status, MPI_Datatype, int *count)
{
    *count = static_cast<int>(*status);
    return MPI_SUCCESS;
}

#endif

double MPI_Wtime()
{
    std::chrono::duration<double> now =
        std::chrono::high_resolution_clock::now().time_since_epoch();
    return now.count();
}

int MPI_Get_processor_name(char *name, int *resultlen)
{
    std::sprintf(name, "0");
    *resultlen = 1;
    return 0;
}

int MPI_Reduce(const void *sendbuf, void *recvbuf, int count,
               MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm)
{
    if (datatype == MPI_CHAR)
    {
        if (op == MPI_SUM)
        {
            char *recvBuffer = reinterpret_cast<char *>(recvbuf);
            const char *sendBuffer = reinterpret_cast<const char *>(sendbuf);
            *recvBuffer = std::accumulate(sendBuffer, sendBuffer + count, 0);
        }
    }
    else if (datatype == MPI_INT)
    {
        if (op == MPI_SUM)
        {
            int *recvBuffer = reinterpret_cast<int *>(recvbuf);
            const int *sendBuffer = reinterpret_cast<const int *>(sendbuf);
            *recvBuffer = std::accumulate(sendBuffer, sendBuffer + count, 0);
        }
    }
    else if (datatype == MPI_UNSIGNED)
    {
        if (op == MPI_SUM)
        {
            unsigned int *recvBuffer =
                reinterpret_cast<unsigned int *>(recvbuf);
            const unsigned int *sendBuffer =
                reinterpret_cast<const unsigned int *>(sendbuf);
            *recvBuffer = std::accumulate(sendBuffer, sendBuffer + count, 0);
        }
    }
    else if (datatype == MPI_UNSIGNED_LONG)
    {
        if (op == MPI_SUM)
        {
            unsigned long int *recvBuffer =
                reinterpret_cast<unsigned long int *>(recvbuf);
            const unsigned long int *sendBuffer =
                reinterpret_cast<const unsigned long int *>(sendbuf);
            *recvBuffer = std::accumulate(sendBuffer, sendBuffer + count, 0);
        }
    }
    else if (datatype == MPI_UNSIGNED_LONG_LONG)
    {
        if (op == MPI_SUM)
        {
            unsigned long long int *recvBuffer =
                reinterpret_cast<unsigned long long int *>(recvbuf);
            const unsigned long long int *sendBuffer =
                reinterpret_cast<const unsigned long long int *>(sendbuf);
            *recvBuffer =
                std::accumulate(sendBuffer, sendBuffer + count,
                                static_cast<unsigned long long int>(0));
        }
    }
    else
    {
        return MPI_ERR_TYPE;
    }

    return 0;
}

int MPI_Allreduce(const void *sendbuf, void *recvbuf, int count,
                  MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
{
    return mpidummy::MPI_Reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
}

int MPI_Type_size(MPI_Datatype datatype, int *size)
{
    if (datatype == MPI_CHAR)
    {
        *size = sizeof(char);
    }
    else if (datatype == MPI_INT)
    {
        *size = sizeof(int);
    }
    else if (datatype == MPI_UNSIGNED)
    {
        *size = sizeof(unsigned int);
    }
    else if (datatype == MPI_UNSIGNED_LONG)
    {
        *size = sizeof(unsigned long);
    }
    else if (datatype == MPI_UNSIGNED_LONG_LONG)
    {
        *size = sizeof(unsigned long long);
    }
    else
    {
        return MPI_ERR_TYPE;
    }
    return MPI_SUCCESS;
}

} // end namespace mpidummy
} // end namespace helper
} // end namespace adios2
<commit_msg>mpidummy: fix MPI_Reduce<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * ADIOS is freely available under the terms of the BSD license described
 * in the COPYING file in the top level directory of this source distribution.
 *
 * Copyright (c) 2008 - 2009.  UT-BATTELLE, LLC. All rights reserved.

   A dummy MPI implementation for the BP READ API, to have an MPI-free version
   of the API
*/

#include "mpidummy.h"

#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <numeric>

#include <chrono>
#include <string>

// remove warnings on Windows
#ifdef _WIN32
#pragma warning(disable : 4996) // fopen
#pragma warning(disable : 4477) // strcpy, sprintf
#endif

namespace adios2
{
namespace helper
{
namespace mpidummy
{

int MPI_Init(int * /*argc*/, char *** /*argv*/) { return MPI_SUCCESS; }

int MPI_Finalize() { return MPI_SUCCESS; }

int MPI_Initialized(int *flag)
{
    *flag = 1;
    return MPI_SUCCESS;
}

int MPI_Finalized(int *flag)
{
    *flag = 0;
    return MPI_SUCCESS;
}

int MPI_Comm_split(MPI_Comm /*comm*/, int /*color*/, int /*key*/,
                   MPI_Comm * /*comm_out*/)
{
    return MPI_SUCCESS;
}

int MPI_Barrier(MPI_Comm /*comm*/) { return MPI_SUCCESS; }

int MPI_Bcast(void * /*buffer*/, int /*count*/, MPI_Datatype /*datatype*/,
              int /*root*/, MPI_Comm /*comm*/)
{
    return MPI_SUCCESS;
}

int MPI_Comm_dup(MPI_Comm comm, MPI_Comm *newcomm)
{
    *newcomm = comm;
    return MPI_SUCCESS;
}

int MPI_Comm_rank(MPI_Comm /*comm*/, int *rank)
{
    *rank = 0;
    return MPI_SUCCESS;
}

int MPI_Comm_size(MPI_Comm /*comm*/, int *size)
{
    *size = 1;
    return MPI_SUCCESS;
}

int MPI_Comm_free(MPI_Comm *comm)
{
    *comm = 0;
    return MPI_SUCCESS;
}

#ifndef ADIOS2_HAVE_MPI
MPI_Comm MPI_Comm_f2c(MPI_Fint comm) { return comm; }
#endif

int MPI_Gather(const void *sendbuf, int sendcnt, MPI_Datatype sendtype,
               void *recvbuf, int recvcnt, MPI_Datatype recvtype, int root,
               MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    int n;
    size_t nsent = 0, nrecv = 0;
    if (sendcnt > 0 && !sendbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (recvcnt > 0 && !recvbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (root != 0)
    {
        return MPI_ERR_ROOT;
    }
    if (comm == MPI_COMM_NULL)
    {
        return MPI_ERR_COMM;
    }

    ier = mpidummy::MPI_Type_size(sendtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nsent = n * sendcnt;

    ier = mpidummy::MPI_Type_size(recvtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nrecv = n * recvcnt;

    if (nrecv != nsent)
    {
        ier = MPI_ERR_COUNT;
    }

    if (ier == MPI_SUCCESS)
    {
        std::memcpy(recvbuf, sendbuf, nsent);
    }

    return ier;
}

int MPI_Gatherv(const void *sendbuf, int sendcnt, MPI_Datatype sendtype,
                void *recvbuf, const int *recvcnts, const int * /*displs */,
                MPI_Datatype recvtype, int root, MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    if (*recvcnts != sendcnt)
    {
        ier = MPI_ERR_COUNT;
        return ier;
    }

    ier = mpidummy::MPI_Gather(sendbuf, sendcnt, sendtype, recvbuf, *recvcnts,
                               recvtype, root, comm);
    return ier;
}

int MPI_Allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
                  void *recvbuf, int recvcount, MPI_Datatype recvtype,
                  MPI_Comm comm)
{
    return mpidummy::MPI_Gather(sendbuf, sendcount, sendtype, recvbuf,
                                recvcount, recvtype, 0, comm);
}

int MPI_Scatter(const void *sendbuf, int sendcnt, MPI_Datatype sendtype,
                void *recvbuf, int recvcnt, MPI_Datatype recvtype, int root,
                MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    int n;
    size_t nsent = 0, nrecv = 0;
    if (sendcnt > 0 && !sendbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (recvcnt > 0 && !recvbuf)
    {
        return MPI_ERR_BUFFER;
    }
    if (root != 0)
    {
        return MPI_ERR_ROOT;
    }
    if (comm == MPI_COMM_NULL)
    {
        return MPI_ERR_COMM;
    }

    ier = mpidummy::MPI_Type_size(sendtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nsent = n * sendcnt;

    ier = mpidummy::MPI_Type_size(recvtype, &n);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }
    nrecv = n * recvcnt;

    if (nrecv != nsent)
    {
        ier = MPI_ERR_COUNT;
    }

    if (ier == MPI_SUCCESS)
    {
        std::memcpy(recvbuf, sendbuf, nsent);
    }

    return ier;
}

int MPI_Scatterv(const void *sendbuf, const int *sendcnts, const int *displs,
                 MPI_Datatype sendtype, void *recvbuf, int recvcnt,
                 MPI_Datatype recvtype, int root, MPI_Comm comm)
{
    int ier = MPI_SUCCESS;
    if (!sendcnts || !displs)
    {
        ier = MPI_ERR_BUFFER;
    }

    if (ier == MPI_SUCCESS)
    {
        ier = mpidummy::MPI_Scatter(sendbuf, *sendcnts, sendtype, recvbuf,
                                    recvcnt, recvtype, root, comm);
    }

    return ier;
}

int MPI_Recv(void * /*recvbuffer*/, int /*count*/, MPI_Datatype /*type*/,
             int /*source*/, int /*tag*/, MPI_Comm /*comm*/,
             MPI_Status * /*status*/)
{
    return 0;
}

int MPI_Irecv(void * /*recvbuffer*/, int /*count*/, MPI_Datatype /*type*/,
              int /*source*/, int /*tag*/, MPI_Comm /*comm*/,
              MPI_Request * /*request*/)

{
    return 0;
}

int MPI_Send(const void * /*sendbuffer*/, int /*count*/, MPI_Datatype /*type*/,
             int /*destination*/, int /*tag*/, MPI_Comm /*comm*/)
{
    return 0;
}

int MPI_Isend(const void * /*recvbuffer*/, int /*count*/, MPI_Datatype /*type*/,
              int /*source*/, int /*tag*/, MPI_Comm /*comm*/,
              MPI_Request * /*request*/)
{
    return 0;
}

int MPI_Wait(MPI_Request * /*request*/, MPI_Status * /*status*/) { return 0; }

#ifndef ADIOS2_HAVE_MPI

int MPI_File_open(MPI_Comm /*comm*/, const char *filename, int amode,
                  MPI_Info /*info*/, MPI_File *fh)
{
    std::string mode;
    if (amode | MPI_MODE_RDONLY)
    {
        mode += "r";
    }
    if (amode | MPI_MODE_WRONLY)
    {
        mode += "w";
    }
    if (amode | MPI_MODE_APPEND)
    {
        mode += "a";
    }
    mode += "b";

    *fh = std::fopen(filename, mode.c_str());
    if (!*fh)
    {
        return -1;
    }
    return MPI_SUCCESS;
}

int MPI_File_close(MPI_File *fh) { return fclose(*fh); }

int MPI_File_get_size(MPI_File fh, MPI_Offset *size)
{
    long curpos = std::ftell(fh);
    fseek(fh, 0, SEEK_END); // go to end, returned is the size in bytes
    long endpos = std::ftell(fh);
    std::fseek(fh, curpos, SEEK_SET); // go back where we were
    *size = static_cast<MPI_Offset>(endpos);
    // printf("MPI_File_get_size: fh=%d, size=%lld\n", fh, *size);
    return MPI_SUCCESS;
}

int MPI_File_read(MPI_File fh, void *buf, int count, MPI_Datatype datatype,
                  MPI_Status *status)
{
    // FIXME: int count can read only 2GB (*datatype size) array at max
    size_t bytes_to_read = static_cast<size_t>(count) * datatype;
    size_t bytes_read;
    bytes_read = std::fread(buf, 1, bytes_to_read, fh);
    if (bytes_read != bytes_to_read)
    {
        return -2;
    }
    *status = bytes_read;
    // printf("MPI_File_read: fh=%d, count=%d, typesize=%d, bytes read=%lld\n",
    // fh, count, datatype, *status);
    return MPI_SUCCESS;
}

int MPI_File_seek(MPI_File fh, MPI_Offset offset, int whence)
{
    return std::fseek(fh, offset, whence) == MPI_SUCCESS;
}

int MPI_Get_count(const MPI_Status *status, MPI_Datatype, int *count)
{
    *count = static_cast<int>(*status);
    return MPI_SUCCESS;
}

#endif

double MPI_Wtime()
{
    std::chrono::duration<double> now =
        std::chrono::high_resolution_clock::now().time_since_epoch();
    return now.count();
}

int MPI_Get_processor_name(char *name, int *resultlen)
{
    std::sprintf(name, "0");
    *resultlen = 1;
    return 0;
}

int MPI_Reduce(const void *sendbuf, void *recvbuf, int count,
               MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm)
{
    int ier, size_of_type;
    ier = mpidummy::MPI_Type_size(datatype, &size_of_type);
    if (ier != MPI_SUCCESS)
    {
        return ier;
    }

    std::memcpy(recvbuf, sendbuf, count * static_cast<size_t>(size_of_type));
    return MPI_SUCCESS;
}

int MPI_Allreduce(const void *sendbuf, void *recvbuf, int count,
                  MPI_Datatype datatype, MPI_Op op, MPI_Comm comm)
{
    return mpidummy::MPI_Reduce(sendbuf, recvbuf, count, datatype, op, 0, comm);
}

int MPI_Type_size(MPI_Datatype datatype, int *size)
{
    if (datatype == MPI_CHAR)
    {
        *size = sizeof(char);
    }
    else if (datatype == MPI_INT)
    {
        *size = sizeof(int);
    }
    else if (datatype == MPI_UNSIGNED)
    {
        *size = sizeof(unsigned int);
    }
    else if (datatype == MPI_UNSIGNED_LONG)
    {
        *size = sizeof(unsigned long);
    }
    else if (datatype == MPI_UNSIGNED_LONG_LONG)
    {
        *size = sizeof(unsigned long long);
    }
    else
    {
        return MPI_ERR_TYPE;
    }
    return MPI_SUCCESS;
}

} // end namespace mpidummy
} // end namespace helper
} // end namespace adios2
<|endoftext|>


<commit_before>#include "SparseGibbsSampler.h"
#include "../data_structures/SparseIterator.h"
#include "../math/VectorMath.h"

#include <bitset>

#define GAPS_SQ(x) ((x) * (x))

#define COUNT_LOWER_BITS(u, pos) __builtin_popcountll((u) & ((1ull << (pos)) - 1ull))
#define CLEAR_LOWER_BITS(u, pos) (((pos) == 63) ? 0 : (u) & ~((1ull << ((pos) + 1ull)) - 1ull))
#define COUNT_BITS(u) __builtin_popcountll(u)
#define GET_FIRST_SET_BIT(u) (__builtin_ffsll(u) - 1)

/////////// SparseGibbsSampler Function Definitions //////////////

float SparseGibbsSampler::chiSq() const
{
    float chisq = 0.f;
    for (unsigned j = 0; j < mDMatrix.nCol(); ++j)
    {
        for (unsigned i = 0; i < mDMatrix.nRow(); ++i)
        {
            float dot = gaps::dot(mMatrix.getRow(j), mOtherMatrix->getRow(i));
            chisq -= dot * dot;
        }

        SparseIterator<1> it(mDMatrix.getCol(j));
        while (!it.atEnd())
        {
            float dot = gaps::dot(mMatrix.getRow(j), mOtherMatrix->getRow(it.getIndex()));
            float dsq = get<1>(it) * get<1>(it);
            chisq += 1 + dot * (dot - 2 * get<1>(it) + dsq * dot) / dsq;
            it.next();
        }
    }
    return chisq * mBeta;
}

void SparseGibbsSampler::sync(const SparseGibbsSampler &sampler, unsigned nThreads)
{
    mOtherMatrix = &(sampler.mMatrix);
    generateLookupTables();
}

// required for GibbsSampler interface
void SparseGibbsSampler::extraInitialization()
{
    // nop - not needed
}

void SparseGibbsSampler::changeMatrix(unsigned row, unsigned col,
float delta)
{
    mMatrix.add(row, col, delta);

    GAPS_ASSERT(mMatrix(row, col) >= 0.f);
}

void SparseGibbsSampler::safelyChangeMatrix(unsigned row,
unsigned col, float delta)
{
    float newVal = gaps::max(mMatrix(row, col) + delta, 0.f);
    mMatrix.add(row, col, newVal - mMatrix(row, col));

    GAPS_ASSERT(mMatrix(row, col) >= 0.f);
}

AlphaParameters SparseGibbsSampler::alphaParameters(unsigned row, unsigned col)
{
    const SparseVector &D(mDMatrix.getCol(row));
    const HybridVector &V(mOtherMatrix->getCol(col));
    const std::vector<uint64_t> &bitflags_D(D.getBitFlags());
    const std::vector<uint64_t> &bitflags_V(V.getBitFlags());
    const std::vector<float> &data(D.getData());

    float s = mZ1[col];
    float s_mu = -1.f * gaps::dot(mMatrix.getRow(row), mZ2.getCol(col));

    unsigned sparseIndex = 0;
    unsigned sz = bitflags_D.size();
    for (unsigned i = 0; i < sz; ++i)
    {
        uint64_t d_flags = bitflags_D[i];
        uint64_t common = d_flags & bitflags_V[i];
        while (common)
        {
            // find common non-zero index, clear out skipped indices of data
            unsigned index = GET_FIRST_SET_BIT(common);
            sparseIndex += COUNT_LOWER_BITS(d_flags, index);
            d_flags = CLEAR_LOWER_BITS(d_flags, index);
            common &= d_flags;

            // get the needed data
            unsigned v_ndx = 64 * i + index;
            float v_val = V[v_ndx];
            float d_val = data[sparseIndex++];

            // compute terms for s and s_mu
            float term1 = v_val / d_val;
            float term2 = v_val - term1 / d_val;
            s += term1 * term1 - v_val * v_val;
            s_mu += term1 + term2 * gaps::dot(mMatrix.getRow(row),
                mOtherMatrix->getRow(v_ndx));
        }
        sparseIndex += COUNT_BITS(d_flags); // skip over any remaining indices
    }
    return AlphaParameters(s, s_mu) * mBeta;
}

AlphaParameters SparseGibbsSampler::alphaParametersWithChange(unsigned row,
unsigned col, float ch)
{
    const SparseVector &D(mDMatrix.getCol(row));
    const HybridVector &V(mOtherMatrix->getCol(col));
    const std::vector<uint64_t> &bitflags_D(D.getBitFlags());
    const std::vector<uint64_t> &bitflags_V(V.getBitFlags());
    const std::vector<float> &data(D.getData());

    float s = mZ1[col];
    float s_mu = -1.f * gaps::dot(mMatrix.getRow(row), mZ2.getCol(col));
    s_mu -= ch * mZ2(col,col);

    unsigned sparseIndex = 0;
    unsigned sz = bitflags_D.size();
    for (unsigned i = 0; i < sz; ++i)
    {
        uint64_t d_flags = bitflags_D[i];
        uint64_t common = d_flags & bitflags_V[i];
        while (common)
        {
            // find common non-zero index, clear out skipped indices of data
            unsigned index = GET_FIRST_SET_BIT(common);
            sparseIndex += COUNT_LOWER_BITS(d_flags, index);
            d_flags = CLEAR_LOWER_BITS(d_flags, index);
            common &= d_flags;

            // get the needed data
            unsigned v_ndx = 64 * i + index;
            float v_val = V[v_ndx];
            float d_val = data[sparseIndex++];

            // compute terms for s and s_mu
            float term1 = v_val / d_val;
            float term2 = v_val - term1 / d_val;
            s += term1 * term1 - v_val * v_val;
            s_mu += term1 + term2 * gaps::dot(mMatrix.getRow(row),
                mOtherMatrix->getRow(v_ndx));
            s_mu += term2 * mOtherMatrix->operator()(v_ndx, col) * ch;
        }
        sparseIndex += COUNT_BITS(d_flags);
    }
    return AlphaParameters(s, s_mu) * mBeta;
}

AlphaParameters SparseGibbsSampler::alphaParameters(unsigned r1, unsigned c1,
unsigned r2, unsigned c2)
{
    if (r1 == r2)
    {
        const SparseVector &D(mDMatrix.getCol(r1));
        const HybridVector &V1(mOtherMatrix->getCol(c1));
        const HybridVector &V2(mOtherMatrix->getCol(c2));
        const std::vector<uint64_t> &bitflags_D(D.getBitFlags());
        const std::vector<uint64_t> &bitflags_V1(V1.getBitFlags());
        const std::vector<uint64_t> &bitflags_V2(V2.getBitFlags());
        const std::vector<float> &data(D.getData());

        float s = mZ1[c1] - 2.f * mZ2(c1,c2) + mZ1[c2];
        float s_mu = -1.f * gaps::dot_diff(mMatrix.getRow(r1), mZ2.getCol(c1),
            mZ2.getCol(c2));

        unsigned sparseIndex = 0;
        unsigned sz = bitflags_D.size();
        for (unsigned i = 0; i < sz; ++i)
        {
            uint64_t d_flags = bitflags_D[i];
            uint64_t common = d_flags & (bitflags_V1[i] | bitflags_V2[i]);
            while (common)
            {
                // find common non-zero index, clear out skipped indices of data
                unsigned index = GET_FIRST_SET_BIT(common);
                sparseIndex += COUNT_LOWER_BITS(d_flags, index);
                d_flags = CLEAR_LOWER_BITS(d_flags, index);
                common &= d_flags;

                // get the needed data
                unsigned v_ndx = 64 * i + index;
                float v1_val = V1[v_ndx];
                float v2_val = V2[v_ndx];
                float d_val = data[sparseIndex++];

                float d_recip = 1.f / d_val;
                float term1 = 1.f - d_recip * d_recip;
                float v_diff = v1_val - v2_val;
                float ap = gaps::dot(mMatrix.getRow(r1), mOtherMatrix->getRow(v_ndx));

                s -= v_diff * v_diff * term1;
                s_mu += v_diff * (ap * term1 + d_recip);
            }
            sparseIndex += COUNT_BITS(d_flags);
        }
        return AlphaParameters(s, s_mu) * mBeta;
    }
    return alphaParameters(r1, c1) + alphaParameters(r2, c2);
}

void SparseGibbsSampler::generateLookupTables()
{
    for (unsigned i = 0; i < mNumPatterns; ++i)
    {
        mZ1[i] = 0.f;
        for (unsigned k = 0; k < mOtherMatrix->nRow(); ++k)
        {
            mZ1[i] += GAPS_SQ(mOtherMatrix->operator()(k,i));
        }
        for (unsigned j = i; j < mNumPatterns; ++j)
        {
            float d = gaps::dot(mOtherMatrix->getCol(i), mOtherMatrix->getCol(j));
            mZ2(i,j) = d;
            mZ2(j,i) = d;
        }
    }
}

Archive& operator<<(Archive &ar, const SparseGibbsSampler &s)
{
    ar << s.mMatrix << s.mDomain << s.mAlpha << s.mLambda << s.mMaxGibbsMass
        << s.mAnnealingTemp << s.mNumPatterns << s.mNumBins << s.mBinLength
        << s.mBeta;
    return ar;
}

Archive& operator>>(Archive &ar, SparseGibbsSampler &s)
{
    ar >> s.mMatrix >> s.mDomain >> s.mAlpha >> s.mLambda >> s.mMaxGibbsMass
        >> s.mAnnealingTemp >> s.mNumPatterns >> s.mNumBins >> s.mBinLength
        >> s.mBeta;
    return ar;
}

#ifdef GAPS_DEBUG
bool SparseGibbsSampler::internallyConsistent() const
{
    return true;
}
#endif
<commit_msg>fix sparse chisq calculation<commit_after>#include "SparseGibbsSampler.h"
#include "../data_structures/SparseIterator.h"
#include "../math/VectorMath.h"

#include <bitset>

#define GAPS_SQ(x) ((x) * (x))

#define COUNT_LOWER_BITS(u, pos) __builtin_popcountll((u) & ((1ull << (pos)) - 1ull))
#define CLEAR_LOWER_BITS(u, pos) (((pos) == 63) ? 0 : (u) & ~((1ull << ((pos) + 1ull)) - 1ull))
#define COUNT_BITS(u) __builtin_popcountll(u)
#define GET_FIRST_SET_BIT(u) (__builtin_ffsll(u) - 1)

/////////// SparseGibbsSampler Function Definitions //////////////

float SparseGibbsSampler::chiSq() const
{
    float chisq = 0.f;
    for (unsigned j = 0; j < mDMatrix.nCol(); ++j)
    {
        for (unsigned i = 0; i < mDMatrix.nRow(); ++i)
        {
            float dot = gaps::dot(mMatrix.getRow(j), mOtherMatrix->getRow(i));
            chisq += dot * dot;
        }

        SparseIterator<1> it(mDMatrix.getCol(j));
        while (!it.atEnd())
        {
            float dot = gaps::dot(mMatrix.getRow(j), mOtherMatrix->getRow(it.getIndex()));
            float dsq = get<1>(it) * get<1>(it);
            chisq += 1 + dot * (dot - 2 * get<1>(it) - dsq * dot) / dsq;
            it.next();
        }
    }
    return chisq * mBeta;
}

void SparseGibbsSampler::sync(const SparseGibbsSampler &sampler, unsigned nThreads)
{
    mOtherMatrix = &(sampler.mMatrix);
    generateLookupTables();
}

// required for GibbsSampler interface
void SparseGibbsSampler::extraInitialization()
{
    // nop - not needed
}

void SparseGibbsSampler::changeMatrix(unsigned row, unsigned col,
float delta)
{
    mMatrix.add(row, col, delta);

    GAPS_ASSERT(mMatrix(row, col) >= 0.f);
}

void SparseGibbsSampler::safelyChangeMatrix(unsigned row,
unsigned col, float delta)
{
    float newVal = gaps::max(mMatrix(row, col) + delta, 0.f);
    mMatrix.add(row, col, newVal - mMatrix(row, col));

    GAPS_ASSERT(mMatrix(row, col) >= 0.f);
}

AlphaParameters SparseGibbsSampler::alphaParameters(unsigned row, unsigned col)
{
    const SparseVector &D(mDMatrix.getCol(row));
    const HybridVector &V(mOtherMatrix->getCol(col));
    const std::vector<uint64_t> &bitflags_D(D.getBitFlags());
    const std::vector<uint64_t> &bitflags_V(V.getBitFlags());
    const std::vector<float> &data(D.getData());

    float s = mZ1[col];
    float s_mu = -1.f * gaps::dot(mMatrix.getRow(row), mZ2.getCol(col));

    unsigned sparseIndex = 0;
    unsigned sz = bitflags_D.size();
    for (unsigned i = 0; i < sz; ++i)
    {
        uint64_t d_flags = bitflags_D[i];
        uint64_t common = d_flags & bitflags_V[i];
        while (common)
        {
            // find common non-zero index, clear out skipped indices of data
            unsigned index = GET_FIRST_SET_BIT(common);
            sparseIndex += COUNT_LOWER_BITS(d_flags, index);
            d_flags = CLEAR_LOWER_BITS(d_flags, index);
            common &= d_flags;

            // get the needed data
            unsigned v_ndx = 64 * i + index;
            float v_val = V[v_ndx];
            float d_val = data[sparseIndex++];

            // compute terms for s and s_mu
            float term1 = v_val / d_val;
            float term2 = v_val - term1 / d_val;
            s += term1 * term1 - v_val * v_val;
            s_mu += term1 + term2 * gaps::dot(mMatrix.getRow(row),
                mOtherMatrix->getRow(v_ndx));
        }
        sparseIndex += COUNT_BITS(d_flags); // skip over any remaining indices
    }
    return AlphaParameters(s, s_mu) * mBeta;
}

AlphaParameters SparseGibbsSampler::alphaParametersWithChange(unsigned row,
unsigned col, float ch)
{
    const SparseVector &D(mDMatrix.getCol(row));
    const HybridVector &V(mOtherMatrix->getCol(col));
    const std::vector<uint64_t> &bitflags_D(D.getBitFlags());
    const std::vector<uint64_t> &bitflags_V(V.getBitFlags());
    const std::vector<float> &data(D.getData());

    float s = mZ1[col];
    float s_mu = -1.f * gaps::dot(mMatrix.getRow(row), mZ2.getCol(col));
    s_mu -= ch * mZ2(col,col);

    unsigned sparseIndex = 0;
    unsigned sz = bitflags_D.size();
    for (unsigned i = 0; i < sz; ++i)
    {
        uint64_t d_flags = bitflags_D[i];
        uint64_t common = d_flags & bitflags_V[i];
        while (common)
        {
            // find common non-zero index, clear out skipped indices of data
            unsigned index = GET_FIRST_SET_BIT(common);
            sparseIndex += COUNT_LOWER_BITS(d_flags, index);
            d_flags = CLEAR_LOWER_BITS(d_flags, index);
            common &= d_flags;

            // get the needed data
            unsigned v_ndx = 64 * i + index;
            float v_val = V[v_ndx];
            float d_val = data[sparseIndex++];

            // compute terms for s and s_mu
            float term1 = v_val / d_val;
            float term2 = v_val - term1 / d_val;
            s += term1 * term1 - v_val * v_val;
            s_mu += term1 + term2 * gaps::dot(mMatrix.getRow(row),
                mOtherMatrix->getRow(v_ndx));
            s_mu += term2 * mOtherMatrix->operator()(v_ndx, col) * ch;
        }
        sparseIndex += COUNT_BITS(d_flags);
    }
    return AlphaParameters(s, s_mu) * mBeta;
}

AlphaParameters SparseGibbsSampler::alphaParameters(unsigned r1, unsigned c1,
unsigned r2, unsigned c2)
{
    if (r1 == r2)
    {
        const SparseVector &D(mDMatrix.getCol(r1));
        const HybridVector &V1(mOtherMatrix->getCol(c1));
        const HybridVector &V2(mOtherMatrix->getCol(c2));
        const std::vector<uint64_t> &bitflags_D(D.getBitFlags());
        const std::vector<uint64_t> &bitflags_V1(V1.getBitFlags());
        const std::vector<uint64_t> &bitflags_V2(V2.getBitFlags());
        const std::vector<float> &data(D.getData());

        float s = mZ1[c1] - 2.f * mZ2(c1,c2) + mZ1[c2];
        float s_mu = -1.f * gaps::dot_diff(mMatrix.getRow(r1), mZ2.getCol(c1),
            mZ2.getCol(c2));

        unsigned sparseIndex = 0;
        unsigned sz = bitflags_D.size();
        for (unsigned i = 0; i < sz; ++i)
        {
            uint64_t d_flags = bitflags_D[i];
            uint64_t common = d_flags & (bitflags_V1[i] | bitflags_V2[i]);
            while (common)
            {
                // find common non-zero index, clear out skipped indices of data
                unsigned index = GET_FIRST_SET_BIT(common);
                sparseIndex += COUNT_LOWER_BITS(d_flags, index);
                d_flags = CLEAR_LOWER_BITS(d_flags, index);
                common &= d_flags;

                // get the needed data
                unsigned v_ndx = 64 * i + index;
                float v1_val = V1[v_ndx];
                float v2_val = V2[v_ndx];
                float d_val = data[sparseIndex++];

                float d_recip = 1.f / d_val;
                float term1 = 1.f - d_recip * d_recip;
                float v_diff = v1_val - v2_val;
                float ap = gaps::dot(mMatrix.getRow(r1), mOtherMatrix->getRow(v_ndx));

                s -= v_diff * v_diff * term1;
                s_mu += v_diff * (ap * term1 + d_recip);
            }
            sparseIndex += COUNT_BITS(d_flags);
        }
        return AlphaParameters(s, s_mu) * mBeta;
    }
    return alphaParameters(r1, c1) + alphaParameters(r2, c2);
}

void SparseGibbsSampler::generateLookupTables()
{
    for (unsigned i = 0; i < mNumPatterns; ++i)
    {
        mZ1[i] = 0.f;
        for (unsigned k = 0; k < mOtherMatrix->nRow(); ++k)
        {
            mZ1[i] += GAPS_SQ(mOtherMatrix->operator()(k,i));
        }
        for (unsigned j = i; j < mNumPatterns; ++j)
        {
            float d = gaps::dot(mOtherMatrix->getCol(i), mOtherMatrix->getCol(j));
            mZ2(i,j) = d;
            mZ2(j,i) = d;
        }
    }
}

Archive& operator<<(Archive &ar, const SparseGibbsSampler &s)
{
    ar << s.mMatrix << s.mDomain << s.mAlpha << s.mLambda << s.mMaxGibbsMass
        << s.mAnnealingTemp << s.mNumPatterns << s.mNumBins << s.mBinLength
        << s.mBeta;
    return ar;
}

Archive& operator>>(Archive &ar, SparseGibbsSampler &s)
{
    ar >> s.mMatrix >> s.mDomain >> s.mAlpha >> s.mLambda >> s.mMaxGibbsMass
        >> s.mAnnealingTemp >> s.mNumPatterns >> s.mNumBins >> s.mBinLength
        >> s.mBeta;
    return ar;
}

#ifdef GAPS_DEBUG
bool SparseGibbsSampler::internallyConsistent() const
{
    return true;
}
#endif
<|endoftext|>


<commit_before><commit_msg>Linux/fontconfig: support retrieving a default font via CreateTypeface(NULL, NULL, ...). This is needed in order for SkTypeface::UniqueID(NULL) to not crash.<commit_after><|endoftext|>