<commit_before>#include "tinysplinecpp.h"
#include <stdexcept>
#include <cstdio>

/* Suppress some useless MSVC warnings. */
#ifdef _MSC_VER
#pragma warning(push)
/* address of dllimport */
#pragma warning(disable:4232)
/* binding rvalues to non-const references */
#pragma warning(disable:4350)
/* unreferenced inline function */
#pragma warning(disable:4514)
/* function not inlined */
#pragma warning(disable:4710)
/* byte padding */
#pragma warning(disable:4820)
/* meaningless deprecation */
#pragma warning(disable:4996)
/* Spectre mitigation */
#pragma warning(disable:5045)
#endif

/******************************************************************************
*                                                                             *
* DeBoorNet                                                                   *
*                                                                             *
******************************************************************************/
tinyspline::DeBoorNet::DeBoorNet()
{
	net.pImpl = NULL;
}

tinyspline::DeBoorNet::DeBoorNet(const tinyspline::DeBoorNet &other)
{
	tsError err = ts_deboornet_copy(&other.net, &net);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::DeBoorNet::~DeBoorNet()
{
	ts_deboornet_free(&net);
}

tinyspline::DeBoorNet & tinyspline::DeBoorNet::operator=(
	const tinyspline::DeBoorNet &other)
{
	if (&other != this) {
		tsError err = ts_deboornet_copy(&other.net, &net);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::real tinyspline::DeBoorNet::knot() const
{
	return ts_deboornet_knot(&net);
}

size_t tinyspline::DeBoorNet::index() const
{
	return ts_deboornet_index(&net);
}

size_t tinyspline::DeBoorNet::multiplicity() const
{
	return ts_deboornet_multiplicity(&net);
}

size_t tinyspline::DeBoorNet::numInsertions() const
{
	return ts_deboornet_num_insertions(&net);
}

size_t tinyspline::DeBoorNet::dimension() const
{
	return ts_deboornet_dimension(&net);
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::points() const
{
	tsReal *points;
	tsError err = ts_deboornet_points(&net, &points);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_points = ts_deboornet_num_points(&net);
	tinyspline::real *begin = points;
	tinyspline::real *end = begin + num_points * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(points);
	return vec;
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::result() const
{
	tsReal *result;
	tsError err = ts_deboornet_result(&net, &result);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_result = ts_deboornet_num_result(&net);
	tinyspline::real *begin = result;
	tinyspline::real *end = begin + num_result * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(result);
	return vec;
}

tsDeBoorNet * tinyspline::DeBoorNet::data()
{
	return &net;
}

/******************************************************************************
*                                                                             *
* BSpline                                                                     *
*                                                                             *
******************************************************************************/
tinyspline::BSpline::BSpline()
{
	tsReal ctrlp[3] = { 0, 0, 0 };
	tsError err = ts_bspline_new(1, 3, 0, TS_CLAMPED, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	err = ts_bspline_set_control_points(&spline, ctrlp);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::BSpline(const tinyspline::BSpline &other)
{
	tsError err = ts_bspline_copy(&other.spline, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::BSpline(size_t nCtrlp, size_t dim, size_t deg,
	tinyspline::BSpline::type type)
{
	tsError err = ts_bspline_new(nCtrlp, dim, deg, type, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::~BSpline()
{
	ts_bspline_free(&spline);
}

tinyspline::BSpline & tinyspline::BSpline::operator=(
	const tinyspline::BSpline &other)
{
	if (&other != this) {
		tsError err = ts_bspline_copy(&other.spline, &spline);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::DeBoorNet tinyspline::BSpline::operator()(tinyspline::real u) const
{
	return eval(u);
}

size_t tinyspline::BSpline::degree() const
{
	return ts_bspline_degree(&spline);
}

size_t tinyspline::BSpline::order() const
{
	return ts_bspline_order(&spline);
}

size_t tinyspline::BSpline::dimension() const
{
	return ts_bspline_dimension(&spline);
}

std::vector<tinyspline::real> tinyspline::BSpline::controlPoints() const
{
	tsReal *ctrlp;
	tsError err = ts_bspline_control_points(&spline, &ctrlp);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_ctrlp = ts_bspline_num_control_points(&spline);
	tinyspline::real *begin  = ctrlp;
	tinyspline::real *end = begin + num_ctrlp * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(ctrlp);
	return vec;
}

std::vector<tinyspline::real> tinyspline::BSpline::knots() const
{
	tsReal *knots;
	tsError err = ts_bspline_knots(&spline, &knots);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_knots = ts_bspline_num_knots(&spline);
	tinyspline::real *begin = knots;
	tinyspline::real *end = begin + num_knots;
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(knots);
	return vec;
}

tsBSpline * tinyspline::BSpline::data()
{
	return &spline;
}

tinyspline::DeBoorNet tinyspline::BSpline::eval(tinyspline::real u) const
{
	tinyspline::DeBoorNet deBoorNet;
	tsError err = ts_bspline_eval(&spline, u, deBoorNet.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return deBoorNet;
}

std::string tinyspline::BSpline::toJSON()
{
	char *json;
	tsError err = ts_bspline_to_json(&spline, &json);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	std::string string(json);
	free(json);
	return string;
}

void tinyspline::BSpline::fromJSON(std::string json)
{
	tsBSpline s;
	tsError err = ts_bspline_from_json(json.c_str(), &s);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	ts_bspline_free(&spline);
	ts_bspline_move(&s, &spline);
}

void tinyspline::BSpline::save(std::string path)
{
	tsError err = ts_bspline_save_json(&spline, path.c_str());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

void tinyspline::BSpline::load(std::string path)
{
	tsBSpline s;
	tsError err = ts_bspline_load_json(path.c_str(), &s);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	ts_bspline_free(&spline);
	ts_bspline_move(&s, &spline);
}

void tinyspline::BSpline::setControlPoints(
	const std::vector<tinyspline::real> &ctrlp)
{
	size_t expected = ts_bspline_len_control_points(&spline);
	size_t actual = ctrlp.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_control_points(&spline, ctrlp.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

void tinyspline::BSpline::setKnots(const std::vector<tinyspline::real> &knots)
{
	size_t expected = ts_bspline_num_knots(&spline);
	size_t actual = knots.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_knots(&spline, knots.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline tinyspline::BSpline::fillKnots(tsBSplineType type,
	tinyspline::real min, tinyspline::real max) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_fill_knots(
		&spline, type, min, max, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::insertKnot(tinyspline::real u,
	size_t n) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_insert_knot(&spline, u, n, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::resize(int n, int back) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_resize(&spline, n, back, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::split(tinyspline::real u) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_split(&spline, u, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::buckle(tinyspline::real b) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_buckle(&spline, b, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::toBeziers() const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_to_beziers(&spline, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::derive(size_t n) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_derive(&spline, n, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

/******************************************************************************
*                                                                             *
* Utils                                                                       *
*                                                                             *
******************************************************************************/
tinyspline::BSpline tinyspline::Utils::interpolateCubic(
	const std::vector<tinyspline::real> *points, size_t dim)
{
	if (dim == 0)
		throw std::runtime_error(ts_enum_str(TS_DIM_ZERO));
	if (points->size() % dim != 0)
		throw std::runtime_error("#points % dim == 0 failed");
	tinyspline::BSpline bspline;
	tsError err = ts_bspline_interpolate_cubic(
		points->data(), points->size()/dim, dim, bspline.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bspline;
}

bool tinyspline::Utils::fequals(tinyspline::real x, tinyspline::real y)
{
	return ts_fequals(x, y) == 1;
}

std::string tinyspline::Utils::enum_str(tsError err)
{
	return std::string(ts_enum_str(err));
}

tsError tinyspline::Utils::str_enum(std::string str)
{
	return ts_str_enum(str.c_str());
}

#ifdef _MSC_VER
#pragma warning(pop)
#endif
<commit_msg>Include stdlib.h for free(). Fixes build with GCC.<commit_after>#include "tinysplinecpp.h"
#include <stdlib.h>
#include <stdexcept>
#include <cstdio>

/* Suppress some useless MSVC warnings. */
#ifdef _MSC_VER
#pragma warning(push)
/* address of dllimport */
#pragma warning(disable:4232)
/* binding rvalues to non-const references */
#pragma warning(disable:4350)
/* unreferenced inline function */
#pragma warning(disable:4514)
/* function not inlined */
#pragma warning(disable:4710)
/* byte padding */
#pragma warning(disable:4820)
/* meaningless deprecation */
#pragma warning(disable:4996)
/* Spectre mitigation */
#pragma warning(disable:5045)
#endif

/******************************************************************************
*                                                                             *
* DeBoorNet                                                                   *
*                                                                             *
******************************************************************************/
tinyspline::DeBoorNet::DeBoorNet()
{
	net.pImpl = NULL;
}

tinyspline::DeBoorNet::DeBoorNet(const tinyspline::DeBoorNet &other)
{
	tsError err = ts_deboornet_copy(&other.net, &net);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::DeBoorNet::~DeBoorNet()
{
	ts_deboornet_free(&net);
}

tinyspline::DeBoorNet & tinyspline::DeBoorNet::operator=(
	const tinyspline::DeBoorNet &other)
{
	if (&other != this) {
		tsError err = ts_deboornet_copy(&other.net, &net);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::real tinyspline::DeBoorNet::knot() const
{
	return ts_deboornet_knot(&net);
}

size_t tinyspline::DeBoorNet::index() const
{
	return ts_deboornet_index(&net);
}

size_t tinyspline::DeBoorNet::multiplicity() const
{
	return ts_deboornet_multiplicity(&net);
}

size_t tinyspline::DeBoorNet::numInsertions() const
{
	return ts_deboornet_num_insertions(&net);
}

size_t tinyspline::DeBoorNet::dimension() const
{
	return ts_deboornet_dimension(&net);
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::points() const
{
	tsReal *points;
	tsError err = ts_deboornet_points(&net, &points);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_points = ts_deboornet_num_points(&net);
	tinyspline::real *begin = points;
	tinyspline::real *end = begin + num_points * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(points);
	return vec;
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::result() const
{
	tsReal *result;
	tsError err = ts_deboornet_result(&net, &result);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_result = ts_deboornet_num_result(&net);
	tinyspline::real *begin = result;
	tinyspline::real *end = begin + num_result * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(result);
	return vec;
}

tsDeBoorNet * tinyspline::DeBoorNet::data()
{
	return &net;
}

/******************************************************************************
*                                                                             *
* BSpline                                                                     *
*                                                                             *
******************************************************************************/
tinyspline::BSpline::BSpline()
{
	tsReal ctrlp[3] = { 0, 0, 0 };
	tsError err = ts_bspline_new(1, 3, 0, TS_CLAMPED, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	err = ts_bspline_set_control_points(&spline, ctrlp);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::BSpline(const tinyspline::BSpline &other)
{
	tsError err = ts_bspline_copy(&other.spline, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::BSpline(size_t nCtrlp, size_t dim, size_t deg,
	tinyspline::BSpline::type type)
{
	tsError err = ts_bspline_new(nCtrlp, dim, deg, type, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::~BSpline()
{
	ts_bspline_free(&spline);
}

tinyspline::BSpline & tinyspline::BSpline::operator=(
	const tinyspline::BSpline &other)
{
	if (&other != this) {
		tsError err = ts_bspline_copy(&other.spline, &spline);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::DeBoorNet tinyspline::BSpline::operator()(tinyspline::real u) const
{
	return eval(u);
}

size_t tinyspline::BSpline::degree() const
{
	return ts_bspline_degree(&spline);
}

size_t tinyspline::BSpline::order() const
{
	return ts_bspline_order(&spline);
}

size_t tinyspline::BSpline::dimension() const
{
	return ts_bspline_dimension(&spline);
}

std::vector<tinyspline::real> tinyspline::BSpline::controlPoints() const
{
	tsReal *ctrlp;
	tsError err = ts_bspline_control_points(&spline, &ctrlp);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_ctrlp = ts_bspline_num_control_points(&spline);
	tinyspline::real *begin  = ctrlp;
	tinyspline::real *end = begin + num_ctrlp * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(ctrlp);
	return vec;
}

std::vector<tinyspline::real> tinyspline::BSpline::knots() const
{
	tsReal *knots;
	tsError err = ts_bspline_knots(&spline, &knots);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	size_t num_knots = ts_bspline_num_knots(&spline);
	tinyspline::real *begin = knots;
	tinyspline::real *end = begin + num_knots;
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	free(knots);
	return vec;
}

tsBSpline * tinyspline::BSpline::data()
{
	return &spline;
}

tinyspline::DeBoorNet tinyspline::BSpline::eval(tinyspline::real u) const
{
	tinyspline::DeBoorNet deBoorNet;
	tsError err = ts_bspline_eval(&spline, u, deBoorNet.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return deBoorNet;
}

std::string tinyspline::BSpline::toJSON()
{
	char *json;
	tsError err = ts_bspline_to_json(&spline, &json);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	std::string string(json);
	free(json);
	return string;
}

void tinyspline::BSpline::fromJSON(std::string json)
{
	tsBSpline s;
	tsError err = ts_bspline_from_json(json.c_str(), &s);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	ts_bspline_free(&spline);
	ts_bspline_move(&s, &spline);
}

void tinyspline::BSpline::save(std::string path)
{
	tsError err = ts_bspline_save_json(&spline, path.c_str());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

void tinyspline::BSpline::load(std::string path)
{
	tsBSpline s;
	tsError err = ts_bspline_load_json(path.c_str(), &s);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	ts_bspline_free(&spline);
	ts_bspline_move(&s, &spline);
}

void tinyspline::BSpline::setControlPoints(
	const std::vector<tinyspline::real> &ctrlp)
{
	size_t expected = ts_bspline_len_control_points(&spline);
	size_t actual = ctrlp.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_control_points(&spline, ctrlp.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

void tinyspline::BSpline::setKnots(const std::vector<tinyspline::real> &knots)
{
	size_t expected = ts_bspline_num_knots(&spline);
	size_t actual = knots.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_knots(&spline, knots.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline tinyspline::BSpline::fillKnots(tsBSplineType type,
	tinyspline::real min, tinyspline::real max) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_fill_knots(
		&spline, type, min, max, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::insertKnot(tinyspline::real u,
	size_t n) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_insert_knot(&spline, u, n, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::resize(int n, int back) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_resize(&spline, n, back, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::split(tinyspline::real u) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_split(&spline, u, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::buckle(tinyspline::real b) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_buckle(&spline, b, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::toBeziers() const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_to_beziers(&spline, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::derive(size_t n) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_derive(&spline, n, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

/******************************************************************************
*                                                                             *
* Utils                                                                       *
*                                                                             *
******************************************************************************/
tinyspline::BSpline tinyspline::Utils::interpolateCubic(
	const std::vector<tinyspline::real> *points, size_t dim)
{
	if (dim == 0)
		throw std::runtime_error(ts_enum_str(TS_DIM_ZERO));
	if (points->size() % dim != 0)
		throw std::runtime_error("#points % dim == 0 failed");
	tinyspline::BSpline bspline;
	tsError err = ts_bspline_interpolate_cubic(
		points->data(), points->size()/dim, dim, bspline.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bspline;
}

bool tinyspline::Utils::fequals(tinyspline::real x, tinyspline::real y)
{
	return ts_fequals(x, y) == 1;
}

std::string tinyspline::Utils::enum_str(tsError err)
{
	return std::string(ts_enum_str(err));
}

tsError tinyspline::Utils::str_enum(std::string str)
{
	return ts_str_enum(str.c_str());
}

#ifdef _MSC_VER
#pragma warning(pop)
#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2009 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <topologyreader.h>
#include "version.h"

using namespace std;

void help_text(void)
{
    votca::csg::HelpTextHeader("csg_dump");
    cout << "Print atoms that are read from topology file to help"
        " debugging atom naming.\n\n";
}

int main(int argc, char** argv)
{
    // initialize the readers/writers,
    // this will be combined in an initialize function later
//    TrajectoryReader::RegisterPlugins();
    TopologyReader::RegisterPlugins();

    // lets read in some program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    desc.add_options()
    ("help", "produce this help message")
    //("version", "show version info")
    ("top", boost::program_options::value<string>(), "atomistic topology file");

    // now read in the command line
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    // does the user want help?
    if (vm.count("help")) {
        help_text();
        cout << desc << endl;
        return 0;
    }

    if(!vm.count("top")) {
        cout << "no topology specified\n";
        return 0;
    }

    // try to run the cg process, go through the frames, etc...
    try {
        Topology top;
        TopologyReader *reader;
        reader = TopReaderFactory().Create(vm["top"].as<string>());
        if(reader == NULL)
            throw std::runtime_error("input format not supported: " + vm["top"].as<string>());

        reader->ReadTopology(vm["top"].as<string>(), top);
        cout << "I have " << top.BeadCount() << " beads in " << top.MoleculeCount() << " molecules" << endl;

        MoleculeContainer::iterator mol;
        for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
            cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName()
              << " beads: " << (*mol)->BeadCount() << endl;
            for(int i=0; i<(*mol)->BeadCount(); ++i) {
                cout << (*mol)->getBeadId(i) << " " <<
                    (*mol)->getBeadName(i) << " " << (*mol)->getBead(i)->getType()->getName() << endl;
            }
        }
    }
    // did an error occour?
    catch(std::exception &error) {
        cerr << "An error occoured!" << endl << error.what() << endl;
    }
    return 0;
}

<commit_msg>fixed typo<commit_after>/*
 * Copyright 2009 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <topologyreader.h>
#include "version.h"

using namespace std;

void help_text(void)
{
    votca::csg::HelpTextHeader("csg_dump");
    cout << "Print atoms that are read from topology file to help"
        " debugging atom naming.\n\n";
}

int main(int argc, char** argv)
{
    // initialize the readers/writers,
    // this will be combined in an initialize function later
//    TrajectoryReader::RegisterPlugins();
    TopologyReader::RegisterPlugins();

    // lets read in some program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    desc.add_options()
    ("help", "produce this help message")
    //("version", "show version info")
    ("top", boost::program_options::value<string>(), "atomistic topology file");

    // now read in the command line
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    // does the user want help?
    if (vm.count("help")) {
        help_text();
        cout << desc << endl;
        return 0;
    }

    if(!vm.count("top")) {
        cout << "no topology specified\n";
        return 0;
    }

    // try to run the cg process, go through the frames, etc...
    try {
        Topology top;
        TopologyReader *reader;
        reader = TopReaderFactory().Create(vm["top"].as<string>());
        if(reader == NULL)
            throw std::runtime_error("input format not supported: " + vm["top"].as<string>());

        reader->ReadTopology(vm["top"].as<string>(), top);
        cout << "I have " << top.BeadCount() << " beads in " << top.MoleculeCount() << " molecules" << endl;

        MoleculeContainer::iterator mol;
        for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
            cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName()
              << " beads: " << (*mol)->BeadCount() << endl;
            for(int i=0; i<(*mol)->BeadCount(); ++i) {
                cout << (*mol)->getBeadId(i) << " " <<
                    (*mol)->getBeadName(i) << " " << (*mol)->getBead(i)->getType()->getName() << endl;
            }
        }
    }
    // did an error occour?
    catch(std::exception &error) {
        cerr << "An error occured!" << endl << error.what() << endl;
    }
    return 0;
}

<|endoftext|>


<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include "extracted-path.hh"

#include <hpp/util/debug.hh>

#include <hpp/core/time-parameterization.hh>

namespace hpp {
  namespace core {
    namespace timeParameterization {
      class HPP_CORE_LOCAL Shift :
        public TimeParameterization
      {
        public:
          typedef boost::shared_ptr<Shift> Ptr_t;

          static TimeParameterizationPtr_t createWithCheck (TimeParameterizationPtr_t tp, value_type t, value_type s)
          {
            if (t == 0 && s == 0) return tp;
            else return create (tp, t, s);
          }

          static Ptr_t create (TimeParameterizationPtr_t tp, value_type t, value_type s)
          {
            Ptr_t shift = HPP_DYNAMIC_PTR_CAST(Shift, tp);
            if (shift)
              return Ptr_t(new Shift (shift->tp_, shift->t_ + t, shift->s_ + s));
            else
              return Ptr_t(new Shift (tp, t, s));
          }

          Shift (TimeParameterizationPtr_t tp, value_type t, value_type s)
          : tp_ (tp), t_ (t), s_ (s) {}

          value_type value (const value_type& t) const
          {
            return tp_->value (t + t_) + s_;
          }
          value_type derivative (const value_type& t) const
          {
            return tp_->derivative (t + t_);
          }
          value_type impl_derivativeBound (const value_type& l, const value_type& u) const
          {
            return tp_->derivativeBound(l + t_, u + t_);
          }

          TimeParameterizationPtr_t copy () const
          {
            return create (tp_->copy(), t_, s_);
          }

          TimeParameterizationPtr_t tp_;
          value_type t_;
          value_type s_;
      };
    }

    // Constructor with constraints
    Path::Path (const interval_t& interval, size_type outputSize,
		size_type outputDerivativeSize,
		const ConstraintSetPtr_t& constraints) :
      paramRange_ (interval), timeRange_ (interval), outputSize_ (outputSize),
      outputDerivativeSize_ (outputDerivativeSize), constraints_ ()
    {
      if (constraints) {
	constraints_ = HPP_STATIC_PTR_CAST (ConstraintSet,
					    constraints->copy ());
      }
    }

    // Constructor without constraints
    Path::Path (const interval_t& interval, size_type outputSize,
		size_type outputDerivativeSize) :
      paramRange_ (interval), timeRange_ (interval), outputSize_ (outputSize),
      outputDerivativeSize_ (outputDerivativeSize), constraints_ ()
    {
    }

    // Copy constructor
    Path::Path (const Path& path) :
      paramRange_ (path.paramRange_), timeRange_ (path.timeRange_),
      outputSize_ (path.outputSize_),
      outputDerivativeSize_ (path.outputDerivativeSize_), constraints_ (),
      timeParam_ ()
    {
      if (path.constraints_) {
	constraints_ = HPP_STATIC_PTR_CAST (ConstraintSet,
					    path.constraints_->copy ());
      }
      if (path.timeParam_)
        timeParam_ = path.timeParam_->copy();
    }

    Path::Path (const Path& path, const ConstraintSetPtr_t& constraints) :
      paramRange_ (path.paramRange_), timeRange_ (path.timeRange_),
      outputSize_ (path.outputSize_),
      outputDerivativeSize_ (path.outputDerivativeSize_),
      constraints_ (constraints), timeParam_ ()
    {
      assert (!path.constraints_);
      if (path.timeParam_)
        timeParam_ = path.timeParam_->copy();
    }

    // Initialization after creation
    void Path::init (const PathWkPtr_t& self)
    {
      weak_ = self;
    }

    PathPtr_t Path::extract (const interval_t& subInterval) const
        throw (projection_error)
    {
      PathPtr_t res;
      if (timeParam_) {
        interval_t paramInterval (
            timeParam_->value(subInterval.first),
            timeParam_->value(subInterval.second));
        res = this->impl_extract (paramInterval);
        // TODO Child class that reimplement impl_extract may return
        // a path whose paramRange has been shifted to 0. We must then shift
        // the time parameterization.
        value_type shift_t, shift_s;
        interval_t timeInterval;
        if (subInterval.first > subInterval.second) {
          shift_t = 0;
          shift_s = res->paramRange().first - paramInterval.second;

          if (shift_s != 0) {
            shift_t = subInterval.second;
            timeInterval.first = 0;
            timeInterval.second = subInterval.first - subInterval.second;
          } else {
            shift_t = 0;
            timeInterval = interval_t (subInterval.second, subInterval.first);
          }
        } else {
          shift_t = 0;
          shift_s = res->paramRange().first - paramInterval.first;
          if (shift_s != 0) {
            shift_t = subInterval.first;
            timeInterval.first = 0;
            timeInterval.second = subInterval.second - subInterval.first;
          } else {
            assert (res->paramRange() == paramInterval);
            shift_t = 0;
            timeInterval = subInterval;
          }
        }
        timeParameterization::Shift::createWithCheck (timeParam_,
            shift_t, shift_s);
#ifndef NDEBUG
        interval_t pr = res->paramRange();
#endif // NDEBUG
        res->timeParameterization(timeParam_->copy(), timeInterval);
        assert (pr == res->paramRange());
      } else {
        res = this->impl_extract (subInterval);
      }
      return res;
    }

    PathPtr_t Path::impl_extract (const interval_t& paramInterval) const
        throw (projection_error)
    {
      if (paramInterval == paramRange_)
	return this->copy ();
      return ExtractedPath::create (weak_.lock (), paramInterval);
    }

    PathPtr_t Path::reverse () const
    {
      interval_t interval;
      interval.first = this->timeRange_.second;
      interval.second = this->timeRange_.first;
      return this->extract (interval);
    }

    void Path::checkPath () const
    {
      if (constraints()) {
        if (!constraints()->isSatisfied (initial())) {
          hppDout (error, *constraints());
          hppDout (error, initial().transpose ());
          throw projection_error ("Initial configuration of path does not satisfy "
              "the constraints");
        }
        if (constraints() && !constraints()->isSatisfied (end())) {
          hppDout (error, *constraints());
          hppDout (error, end().transpose ());
          throw projection_error ("End configuration of path does not satisfy "
              "the constraints");
        }
      }
    }

    std::ostream& Path::print (std::ostream& os) const
    {
      os << "time in [ " << timeRange().first << ", "
        << timeRange().second << " ]";
      if (timeParam_)
        os << ", param in [ " << paramRange().first << ", "
          << paramRange().second << " ]";
      os << std::endl;
      return os;
    }
  } //   namespace core
} // namespace hpp
<commit_msg>Make error message more explicit.<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include "extracted-path.hh"

#include <hpp/util/debug.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/core/time-parameterization.hh>

namespace hpp {
  namespace core {
    namespace timeParameterization {
      class HPP_CORE_LOCAL Shift :
        public TimeParameterization
      {
        public:
          typedef boost::shared_ptr<Shift> Ptr_t;

          static TimeParameterizationPtr_t createWithCheck (TimeParameterizationPtr_t tp, value_type t, value_type s)
          {
            if (t == 0 && s == 0) return tp;
            else return create (tp, t, s);
          }

          static Ptr_t create (TimeParameterizationPtr_t tp, value_type t, value_type s)
          {
            Ptr_t shift = HPP_DYNAMIC_PTR_CAST(Shift, tp);
            if (shift)
              return Ptr_t(new Shift (shift->tp_, shift->t_ + t, shift->s_ + s));
            else
              return Ptr_t(new Shift (tp, t, s));
          }

          Shift (TimeParameterizationPtr_t tp, value_type t, value_type s)
          : tp_ (tp), t_ (t), s_ (s) {}

          value_type value (const value_type& t) const
          {
            return tp_->value (t + t_) + s_;
          }
          value_type derivative (const value_type& t) const
          {
            return tp_->derivative (t + t_);
          }
          value_type impl_derivativeBound (const value_type& l, const value_type& u) const
          {
            return tp_->derivativeBound(l + t_, u + t_);
          }

          TimeParameterizationPtr_t copy () const
          {
            return create (tp_->copy(), t_, s_);
          }

          TimeParameterizationPtr_t tp_;
          value_type t_;
          value_type s_;
      };
    }

    // Constructor with constraints
    Path::Path (const interval_t& interval, size_type outputSize,
		size_type outputDerivativeSize,
		const ConstraintSetPtr_t& constraints) :
      paramRange_ (interval), timeRange_ (interval), outputSize_ (outputSize),
      outputDerivativeSize_ (outputDerivativeSize), constraints_ ()
    {
      if (constraints) {
	constraints_ = HPP_STATIC_PTR_CAST (ConstraintSet,
					    constraints->copy ());
      }
    }

    // Constructor without constraints
    Path::Path (const interval_t& interval, size_type outputSize,
		size_type outputDerivativeSize) :
      paramRange_ (interval), timeRange_ (interval), outputSize_ (outputSize),
      outputDerivativeSize_ (outputDerivativeSize), constraints_ ()
    {
    }

    // Copy constructor
    Path::Path (const Path& path) :
      paramRange_ (path.paramRange_), timeRange_ (path.timeRange_),
      outputSize_ (path.outputSize_),
      outputDerivativeSize_ (path.outputDerivativeSize_), constraints_ (),
      timeParam_ ()
    {
      if (path.constraints_) {
	constraints_ = HPP_STATIC_PTR_CAST (ConstraintSet,
					    path.constraints_->copy ());
      }
      if (path.timeParam_)
        timeParam_ = path.timeParam_->copy();
    }

    Path::Path (const Path& path, const ConstraintSetPtr_t& constraints) :
      paramRange_ (path.paramRange_), timeRange_ (path.timeRange_),
      outputSize_ (path.outputSize_),
      outputDerivativeSize_ (path.outputDerivativeSize_),
      constraints_ (constraints), timeParam_ ()
    {
      assert (!path.constraints_);
      if (path.timeParam_)
        timeParam_ = path.timeParam_->copy();
    }

    // Initialization after creation
    void Path::init (const PathWkPtr_t& self)
    {
      weak_ = self;
    }

    PathPtr_t Path::extract (const interval_t& subInterval) const
        throw (projection_error)
    {
      PathPtr_t res;
      if (timeParam_) {
        interval_t paramInterval (
            timeParam_->value(subInterval.first),
            timeParam_->value(subInterval.second));
        res = this->impl_extract (paramInterval);
        // TODO Child class that reimplement impl_extract may return
        // a path whose paramRange has been shifted to 0. We must then shift
        // the time parameterization.
        value_type shift_t, shift_s;
        interval_t timeInterval;
        if (subInterval.first > subInterval.second) {
          shift_t = 0;
          shift_s = res->paramRange().first - paramInterval.second;

          if (shift_s != 0) {
            shift_t = subInterval.second;
            timeInterval.first = 0;
            timeInterval.second = subInterval.first - subInterval.second;
          } else {
            shift_t = 0;
            timeInterval = interval_t (subInterval.second, subInterval.first);
          }
        } else {
          shift_t = 0;
          shift_s = res->paramRange().first - paramInterval.first;
          if (shift_s != 0) {
            shift_t = subInterval.first;
            timeInterval.first = 0;
            timeInterval.second = subInterval.second - subInterval.first;
          } else {
            assert (res->paramRange() == paramInterval);
            shift_t = 0;
            timeInterval = subInterval;
          }
        }
        timeParameterization::Shift::createWithCheck (timeParam_,
            shift_t, shift_s);
#ifndef NDEBUG
        interval_t pr = res->paramRange();
#endif // NDEBUG
        res->timeParameterization(timeParam_->copy(), timeInterval);
        assert (pr == res->paramRange());
      } else {
        res = this->impl_extract (subInterval);
      }
      return res;
    }

    PathPtr_t Path::impl_extract (const interval_t& paramInterval) const
        throw (projection_error)
    {
      if (paramInterval == paramRange_)
	return this->copy ();
      return ExtractedPath::create (weak_.lock (), paramInterval);
    }

    PathPtr_t Path::reverse () const
    {
      interval_t interval;
      interval.first = this->timeRange_.second;
      interval.second = this->timeRange_.first;
      return this->extract (interval);
    }

    void Path::checkPath () const
    {
      using pinocchio::displayConfig;
      if (constraints()) {
        if (!constraints()->isSatisfied (initial())) {
          std::stringstream oss;
          hppDout (error, *constraints());
          hppDout (error, initial().transpose ());
          oss << "Initial configuration of path does not satisfy the path "
            "constraints: q=" << displayConfig (initial ()) << "; error=";
          vector_t error;
          constraints ()->isSatisfied (initial (), error);
          oss << displayConfig (error) << ".";
          throw projection_error (oss.str ().c_str ());
        }
        if (constraints() && !constraints()->isSatisfied (end())) {
          std::stringstream oss;
          hppDout (error, *constraints());
          hppDout (error, end().transpose ());
          oss << "End configuration of path does not satisfy the path "
            "constraints: q=" << displayConfig (initial ()) << "; error=";
          vector_t error;
          constraints ()->isSatisfied (end (), error);
          oss << displayConfig (error) << ".";
          throw projection_error (oss.str ().c_str ());
        }
      }
    }

    std::ostream& Path::print (std::ostream& os) const
    {
      os << "time in [ " << timeRange().first << ", "
        << timeRange().second << " ]";
      if (timeParam_)
        os << ", param in [ " << paramRange().first << ", "
          << paramRange().second << " ]";
      os << std::endl;
      return os;
    }
  } //   namespace core
} // namespace hpp
<|endoftext|>


<commit_before>
#include "pca.h"
#include <stdio.h>
#include <dataanalysis.h>

using namespace alglib;

void projectData(real_2d_array inMatrix, real_2d_array v, unsigned int rows,
    unsigned int cols, real_2d_array outMatrix)
{
  ae_int_t m = rows;
  ae_int_t n = cols;
  ae_int_t k = cols;
  double alpha = 0.0;
  ae_int_t ia = 0;
  ae_int_t ja = 0;
  ae_int_t optypea = 0;
  ae_int_t ib = 0;
  ae_int_t jb = 0;
  ae_int_t optypeb = 0;
  double beta = 0.0;
  ae_int_t ic = 0;
  ae_int_t jc = 0;

  rmatrixgemm(m, n, k, alpha, inMatrix, ia, ja, optypea, v, ib, jb, optypeb, beta,
      outMatrix, ic, jc);
}

void pca(float* d_inMatrix, unsigned int inRows, unsigned int inCols,
    float* d_outMatrix)
{
  real_2d_array inMatrix;
  double* inMatrixDouble = (double*) calloc(inRows * inCols, sizeof(double));

  for (size_t i = 0; i < inRows * inCols; i++)
  {
    unsigned int row_i = floor(i / inCols);
    unsigned int col_i = i - (row_i * inCols);

    // Begin transpose
    unsigned int tmp = row_i;
    row_i = col_i;
    col_i = tmp;
    // End transpose

    unsigned int index = row_i * inRows + col_i;

    inMatrixDouble[index] = d_inMatrix[i];
    printf("Index %u\n", index);
  }
  inMatrix.setcontent(inCols, inRows, inMatrixDouble);

  ae_int_t info;
  real_1d_array s2;
  real_2d_array v;
  pcabuildbasis(inMatrix, inCols, inRows, info, s2, v);

  printf("V\n");
  for (size_t i = 0; i < inRows; i++)
  {
    for (size_t j = 0; j < inRows; j++)
    {
      printf("%lu,%lu: %f\n", i, j, v[i][j]);
    }
  }

  real_2d_array outMatrix;
  outMatrix.setlength(inCols, inRows);
  projectData(inMatrix, v, inCols, inRows, outMatrix);

  for (size_t i = 0; i < inRows; i++)
  {
    for (size_t j = 0; j < inCols; j++)
    {
      d_outMatrix[j + i * inCols] = outMatrix[j][i];
    }
  }
}

void pcaUpdateMean(float* d_inMatrix, unsigned int inRows, unsigned int inCols)
{

}

void pcaCalculateYMatrix(float* d_inMatrix, unsigned int inRows, unsigned int
    inCols, float* d_Y)
{

}

void pcaSVD(float* d_Y, unsigned int inRows, unsigned int inCols, float* d_PC)
{

}

void pcaCalculateSignals(float* d_PC, float* d_inMatrix, unsigned int inRows,
    unsigned int inCols, float* d_Signals)
{

}

<commit_msg>Removed bug from sequential pca.<commit_after>
#include "pca.h"
#include <stdio.h>
#include <dataanalysis.h>

using namespace alglib;

void projectData(real_2d_array inMatrix, real_2d_array v, unsigned int rows,
    unsigned int cols, real_2d_array& outMatrix)
{
  ae_int_t m = rows;
  ae_int_t n = cols;
  ae_int_t k = cols;
  double alpha = 1.0;
  ae_int_t ia = 0;
  ae_int_t ja = 0;
  ae_int_t optypea = 0;
  ae_int_t ib = 0;
  ae_int_t jb = 0;
  ae_int_t optypeb = 0;
  double beta = 0.0;
  ae_int_t ic = 0;
  ae_int_t jc = 0;

  rmatrixgemm(m, n, k, alpha, inMatrix, ia, ja, optypea, v, ib, jb, optypeb, beta,
      outMatrix, ic, jc);
}

void pca(float* d_inMatrix, unsigned int inRows, unsigned int inCols,
    float* d_outMatrix)
{
  pcaUpdateMean(d_inMatrix, inRows, inCols);

  real_2d_array inMatrix;
  double* inMatrixDouble = (double*) calloc(inRows * inCols, sizeof(double));

  for (size_t i = 0; i < inRows * inCols; i++)
  {
    unsigned int row_i = floor(i / inCols);
    unsigned int col_i = i - (row_i * inCols);

    // Begin transpose
    unsigned int tmp = row_i;
    row_i = col_i;
    col_i = tmp;
    // End transpose

    unsigned int index = row_i * inRows + col_i;

    inMatrixDouble[index] = d_inMatrix[i];
  }
  inMatrix.setcontent(inCols, inRows, inMatrixDouble);

  ae_int_t info;
  real_1d_array s2;
  real_2d_array v;
  pcabuildbasis(inMatrix, inCols, inRows, info, s2, v);

  printf("V\n");
  for (size_t i = 0; i < inRows; i++)
  {
    for (size_t j = 0; j < inRows; j++)
    {
      printf("%lu,%lu: %f\n", i, j, v[i][j]);
    }
  }

  real_2d_array outMatrix;
  outMatrix.setlength(inCols, inRows);
  projectData(inMatrix, v, inCols, inRows, outMatrix);

  for (size_t i = 0; i < inRows; i++)
  {
    for (size_t j = 0; j < inCols; j++)
    {
      d_outMatrix[j + i * inCols] = outMatrix[j][i];
    }
  }
}

void pcaUpdateMean(float* d_inMatrix, unsigned int inRows, unsigned int inCols)
{
  float* averages = (float*) calloc(inRows, sizeof(float));
  for (size_t i = 0; i < inRows; i++)
  {
    for (size_t j = 0; j < inCols; j++)
    {
      averages[i] += d_inMatrix[j + i * inCols];
    }
    averages[i] /= inCols;
  }

  for (size_t i = 0; i < inRows; i++)
  {
    for (size_t j = 0; j < inCols; j++)
    {
      d_inMatrix[j + i * inCols] -= averages[i];
    }
  }
  free(averages);
}

void pcaCalculateYMatrix(float* d_inMatrix, unsigned int inRows, unsigned int
    inCols, float* d_Y)
{

}

void pcaSVD(float* d_Y, unsigned int inRows, unsigned int inCols, float* d_PC)
{

}

void pcaCalculateSignals(float* d_PC, float* d_inMatrix, unsigned int inRows,
    unsigned int inCols, float* d_Signals)
{

}

<|endoftext|>


<commit_before>///
/// @file  phi.cpp
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include "pi_bsearch.h"
#include "imath.h"

#include <primesieve/soe/PrimeSieve.h>
#include <stdint.h>
#include <vector>
#include <limits>
#include <cstddef>

#ifdef _OPENMP
  #include <omp.h>
  #include "to_omp_threads.h"
#endif

/// Keep the cache size below CACHE_BYTES_LIMIT per thread
#define CACHE_BYTES_LIMIT (16 << 20)

/// Cache phi(x, a) results if a <= CACHE_A_LIMIT
#define CACHE_A_LIMIT 500

/// Avoid slow 64-bit division if possible
#define FAST_DIV(x, y) ((x <= std::numeric_limits<uint32_t>::max()) \
    ? static_cast<uint32_t>(x) / (y) : (x) / (y))

namespace primecount {

/// This class is used to calculate phi(x, a) using the recursive
/// formula: phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1).
/// This implementation is based on an algorithm from Tomas Oliveira e
/// Silva [1]. I have added a cache to my implementation in which
/// results of phi(x, a) are stored if x < 2^16 and a <= 500.
/// The cache speeds up the calculations by at least 3 orders of
/// magnitude near 10^15.
///
/// [1] Tomas Oliveira e Silva, "Computing pi(x): the combinatorial method",
///     Revista do DETUA, vol. 4, no. 6, pp. 759-768, March 2006
///
class PhiCache {
public:
  PhiCache(const std::vector<int32_t>& primes) :
    primes_(primes), bytes_(0)
  {
    std::size_t maxSize = CACHE_A_LIMIT + 1;
    cache_.resize(std::min(primes.size(), maxSize));
  }

  template<int64_t SIGN> int64_t phi(int64_t x, int64_t a)
  {
    int64_t sum = x * SIGN;
    if (a > 0)
    {
      int64_t iters = pi_bsearch(primes_.begin(), primes_.begin() + a, isqrt(x));
      sum += (a - iters) * -SIGN;

      for (int64_t a2 = 0; a2 < iters; a2++)
      {
        // x2 = x / primes_[a2]
        int64_t x2 = FAST_DIV(x, primes_[a2]);
        int64_t phiResult;

        if (validIndexes(a2, x2) && cache_[a2][x2] != 0)
          phiResult = cache_[a2][x2] * -SIGN;
        else
        {
          // phi(x2, a2) not cached, calculate recursively
          phiResult = phi<-SIGN>(x2, a2);
          if (validIndexes(a2, x2))
            cache_[a2][x2] = static_cast<uint16_t>(phiResult * -SIGN);
        }
        sum += phiResult;
      }
    }
    return sum;
  }
private:
  /// Cache for phi(x, a) results
  std::vector<std::vector<uint16_t> > cache_;
  const std::vector<int32_t>& primes_;
  int64_t bytes_;

  bool validIndexes(int64_t a2, int64_t x2)
  {
    if (a2 > CACHE_A_LIMIT || x2 > std::numeric_limits<uint16_t>::max())
      return false;
    // resize cache if necessary
    if (x2 >= static_cast<int64_t>(cache_[a2].size()))
    {
      if (bytes_ > CACHE_BYTES_LIMIT)
        return false;
      bytes_ += (x2 + 1 - cache_[a2].size()) * 2;
      cache_[a2].resize(x2 + 1, 0);
    }
    return true;
  }
};

/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
/// @pre prime[a] <= sqrt(x)
///
int64_t phi(int64_t x, int64_t a, int threads)
{
  if (x < 1) return 0;
  if (a < 1) return x;

  std::vector<int32_t> primes;
  PrimeSieve ps;
  ps.generate_N_Primes(a, &primes);

  int iters = pi_bsearch(primes.begin(), primes.begin() + a, isqrt(x));
  PhiCache cache(primes);
  int64_t sum = x - a + iters;

#ifdef _OPENMP
  threads = to_omp_threads(threads);
  #pragma omp parallel for firstprivate(cache) reduction(+: sum) \
      num_threads(threads) schedule(dynamic, 16)
#endif
  for (int64_t a2 = 0; a2 < iters; a2++)
    sum += cache.phi<-1>(x / primes[a2], a2);

  return sum;
}

} // namespace primecount
<commit_msg>Refactoring<commit_after>///
/// @file  phi.cpp
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include "pi_bsearch.h"
#include "imath.h"

#include <primesieve/soe/PrimeSieve.h>
#include <stdint.h>
#include <vector>
#include <limits>
#include <cstddef>

#ifdef _OPENMP
  #include <omp.h>
  #include "to_omp_threads.h"
#endif

/// Keep the cache size below CACHE_BYTES_LIMIT per thread
#define CACHE_BYTES_LIMIT (16 << 20)

/// Cache phi(x, a) results if a <= CACHE_A_LIMIT
#define CACHE_A_LIMIT 500

/// Avoid slow 64-bit division if possible
#define FAST_DIV(x, y) ((x <= std::numeric_limits<uint32_t>::max()) \
    ? static_cast<uint32_t>(x) / (y) : (x) / (y))

namespace primecount {

/// This class is used to calculate phi(x, a) using the recursive
/// formula: phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1).
/// This implementation is based on an algorithm from Tomas Oliveira e
/// Silva [1]. I have added a cache to my implementation in which
/// results of phi(x, a) are stored if x < 2^16 and a <= 500.
/// The cache speeds up the calculations by at least 3 orders of
/// magnitude near 10^15.
///
/// [1] Tomas Oliveira e Silva, "Computing pi(x): the combinatorial method",
///     Revista do DETUA, vol. 4, no. 6, pp. 759-768, March 2006
///
class PhiCache {
public:
  PhiCache(const std::vector<int32_t>& primes) :
    primes_(primes), bytes_(0)
  {
    std::size_t maxSize = CACHE_A_LIMIT + 1;
    cache_.resize(std::min(primes.size(), maxSize));
  }

  template<int64_t SIGN> int64_t phi(int64_t x, int64_t a)
  {
    int64_t sum = x * SIGN;
    if (a > 0)
    {
      int64_t iters = pi_bsearch(primes_.begin(), primes_.begin() + a, isqrt(x));
      sum += (a - iters) * -SIGN;

      for (int64_t a2 = 0; a2 < iters; a2++)
      {
        // x2 = x / primes_[a2]
        int64_t x2 = FAST_DIV(x, primes_[a2]);
        int64_t phiResult;

        if (validate(a2, x2) && cache_[a2][x2] != 0)
          phiResult = cache_[a2][x2] * -SIGN;
        else
        {
          // phi(x2, a2) not cached, calculate recursively
          phiResult = phi<-SIGN>(x2, a2);
          if (validate(a2, x2))
            cache_[a2][x2] = static_cast<uint16_t>(phiResult * -SIGN);
        }
        sum += phiResult;
      }
    }
    return sum;
  }
private:
  /// Cache for phi(x, a) results
  std::vector<std::vector<uint16_t> > cache_;
  const std::vector<int32_t>& primes_;
  int64_t bytes_;

  bool validate(int64_t a2, int64_t x2)
  {
    if (a2 > CACHE_A_LIMIT || x2 > std::numeric_limits<uint16_t>::max())
      return false;
    // resize and initialize cache if necessary
    if (x2 >= static_cast<int64_t>(cache_[a2].size()))
    {
      if (bytes_ > CACHE_BYTES_LIMIT)
        return false;
      bytes_ += (x2 + 1 - cache_[a2].size()) * 2;
      cache_[a2].resize(x2 + 1, 0);
    }
    return true;
  }
};

/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
/// @pre prime[a] <= sqrt(x)
///
int64_t phi(int64_t x, int64_t a, int threads)
{
  if (x < 1) return 0;
  if (a < 1) return x;

  std::vector<int32_t> primes;
  PrimeSieve ps;
  ps.generate_N_Primes(a, &primes);

  int iters = pi_bsearch(primes.begin(), primes.begin() + a, isqrt(x));
  PhiCache cache(primes);
  int64_t sum = x - a + iters;

#ifdef _OPENMP
  threads = to_omp_threads(threads);
  #pragma omp parallel for firstprivate(cache) reduction(+: sum) \
      num_threads(threads) schedule(dynamic, 16)
#endif
  for (int64_t a2 = 0; a2 < iters; a2++)
    sum += cache.phi<-1>(x / primes[a2], a2);

  return sum;
}

} // namespace primecount
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "helpwindow.h"
#include "utils.h"

#include "ui_mainwindow.h"

#ifdef Q_WS_WIN
    #include <windows.h>
#endif

#include <QApplication>
#include <QCloseEvent>
#include <QDebug>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDir>
#include <QHelpEngine>
#include <QLibraryInfo>
#include <QMessageBox>
#include <QSettings>
#include <QTemporaryFile>
#include <QTranslator>
#include <QUrl>

#define OPENCOR_HOMEPAGE "http://opencor.sourceforge.net/"
#define OPENCOR_HELP_HOMEPAGE "qthelp://world.opencor/doc/index.html"

#define SETTINGS_INSTITUTION "World"
#define SETTINGS_GENERAL_LOCALE "General_Locale"
#define SETTINGS_GENERAL_GEOMETRY "General_Geometry"
#define SETTINGS_GENERAL_STATE "General_State"
#define SETTINGS_HELPWINDOW_ZOOMLEVEL "HelpWindow_ZoomLevel"

#define ENGLISH_LOCALE "en"
#define FRENCH_LOCALE  "fr"

MainWindow::MainWindow(bool *pRestart, QWidget *pParent) :
    QMainWindow(pParent),
    mUi(new Ui::MainWindow),
    mRestart(pRestart)
{
    // Set up the GUI

    mUi->setupUi(this);

    // Set the name of the main window to that of the application

    setWindowTitle(qApp->applicationName());

    // Some basic signals/events for some actions

    connect(mUi->actionExit, SIGNAL(triggered(bool)),
            this, SLOT(close()));
    connect(mUi->actionResetAll, SIGNAL(triggered(bool)),
            this, SLOT(resetAll()));

    // Signals/events for showing/hiding the various toolbars

    connect(mUi->actionHelpToolbar, SIGNAL(triggered(bool)),
            mUi->helpToolbar, SLOT(setVisible(bool)));
    connect(mUi->helpToolbar->toggleViewAction(), SIGNAL(toggled(bool)),
            mUi->actionHelpToolbar, SLOT(setChecked(bool)));

    // Extract the help files

    QTemporaryFile tempDir;

    tempDir.open();    // Note: this is required to get a 'valid' temporary
    tempDir.close();   //       directory name...

    mTempDirName = tempDir.fileName().append("."+qApp->applicationName());

    QDir().mkdir(mTempDirName);

    QString applicationBaseName(QFileInfo(qApp->applicationFilePath()).baseName());

    mQchFileName = mTempDirName+QDir::separator()+applicationBaseName+".qch";
    mQhcFileName = mTempDirName+QDir::separator()+applicationBaseName+".qhc";

    saveResourceAs(":qchFile", mQchFileName);
    saveResourceAs(":qhcFile", mQhcFileName);

    // Set up the help engine

    mHelpEngine = new QHelpEngine(mQhcFileName);

    mHelpEngine->setupData();

    // Help window

    mHelpWindow = new HelpWindow(mHelpEngine, QUrl(OPENCOR_HELP_HOMEPAGE));

    connect(mUi->actionHelp, SIGNAL(triggered(bool)),
            mHelpWindow, SLOT(setVisible(bool)));
    connect(mHelpWindow, SIGNAL(visibilityChanged(bool)),
            mUi->actionHelp, SLOT(setChecked(bool)));

    // Default user settings (useful the very first time we start OpenCOR or
    // after a reset all)

    defaultSettings();

    // Retrieve our default settings

    loadSettings();

    // Update the GUI, which may have changed (e.g. hidden toolbar) as a result
    // of loading OpenCOR's settings

    updateGUI();

    // Bring ourselves to the foreground (this is required when we come here as
    // a result of a reset all on Mac OS X)

#ifdef Q_WS_MAC
    raise();
#endif
}

MainWindow::~MainWindow()
{
    // Delete some internal objects

    delete mHelpEngine;
    delete mUi;

    // Delete the help files

    QFile(mQchFileName).remove();
    QFile(mQhcFileName).remove();

    QDir().rmdir(mTempDirName);
}

void MainWindow::closeEvent(QCloseEvent *pEvent)
{
    // Keep track of our default settings, but only if we don't want to restart
    // OpenCOR (i.e. as a result of a reset all)
    // Note: it must be done here, as opposed to the destructor, otherwise some
    //       settings (e.g. docked windows) won't be properly saved

    if (!*mRestart)
        saveSettings();

    pEvent->accept();
}

void MainWindow::singleAppMsgRcvd(const QString&)
{
    // We have just received a message from another instance of OpenCOR, so
    // bring ourselves to the foreground
    // Note: one would normally use activateWindow(), but depending on the
    //       operating system it may or not bring OpenCOR to the foreground,
    //       so... instead we do what follows, depending on the operating
    //       system...

#ifdef Q_WS_WIN
    // Retrieve OpenCOR's window Id

    WId mwWinId = winId();

    // Restore OpenCOR, should it be minimized

    if (IsIconic(mwWinId))
        SendMessage(mwWinId, WM_SYSCOMMAND, SC_RESTORE, 0);

    // Bring OpenCOR to the foreground

    DWORD foregroundThreadPId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
    DWORD mwThreadPId         = GetWindowThreadProcessId(mwWinId, NULL);

    if (foregroundThreadPId != mwThreadPId)
    {
        // OpenCOR's thread process Id is not that of the foreground window, so
        // attach the foreground thread to OpenCOR's, set OpenCOR to the
        // foreground, and detach the foreground thread from OpenCOR's

        AttachThreadInput(foregroundThreadPId, mwThreadPId, true);

        SetForegroundWindow(mwWinId);

        AttachThreadInput(foregroundThreadPId, mwThreadPId, false);
    }
    else
        // OpenCOR's thread process Id is that of the foreground window, so
        // just set OpenCOR to the foreground

        SetForegroundWindow(mwWinId);

    // Note: under Windows, to use activateWindow() will only highlight the
    //       application in the taskbar, since under Windows no application
    //       should be allowed to bring itself to the foreground when another
    //       application is already in the foreground. Fair enough, but it
    //       happens that, here, the user wants OpenCOR to be brought to the
    //       foreground, hence the above code to get the effect we are after...
#else
    // Do what one should normally do and which works fine under Mac OS X

    activateWindow();

    #ifdef Q_WS_X11
        raise();
        // Note: under Linux, to use activateWindow() may or not give the
        //       expected result. The above code is supposed to make sure that
        //       OpenCOR gets brought to the foreground, but that itsn't the
        //       case under Ubuntu at least (it works when you want to open a
        //       second instance of OpenCOR, but not thereafter!)...
    #endif
#endif

    // Now, we must handle the arguments that were passed to us

    // TODO: handle the arguments passed to the 'official' instance of OpenCOR
}

void MainWindow::resetAll()
{
    // Clear all the user settings and asked for OpenCOR to be restarted
    // (indeed, a restart will ensure that all the docked windows are properly
    // reset with regards to their dimensions)

    QSettings(SETTINGS_INSTITUTION, qApp->applicationName()).clear();

    *mRestart = true;

    close();
}

void MainWindow::defaultSettings()
{
    // Default language to be used by OpenCOR

    setLocale(ENGLISH_LOCALE);

    // Default size and position of the main window

    double spaceRatio = 1.0/13.0;
    QRect desktopGeometry = qApp->desktop()->availableGeometry();
    int horizSpace = spaceRatio*desktopGeometry.width();
    int vertSpace  = spaceRatio*desktopGeometry.height();

    setGeometry(desktopGeometry.left()+horizSpace, desktopGeometry.top()+vertSpace, desktopGeometry.width()-2*horizSpace, desktopGeometry.height()-2*vertSpace);

    // Default size and position of the help window

    mHelpWindow->setVisible(false);   // So we can set things up without having
                                      // the screen flashing

    addDockWidget(Qt::RightDockWidgetArea, mHelpWindow);

    mHelpWindow->defaultSettings();

    mHelpWindow->setVisible(true);

    // Default visibility and location of the various toolbars

    addToolBar(Qt::TopToolBarArea, mUi->helpToolbar);

    mUi->helpToolbar->setVisible(true);
}

void MainWindow::loadSettings()
{
    QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());

    // Retrieve the language to be used by OpenCOR

    setLocale(settings.value(SETTINGS_GENERAL_LOCALE, ENGLISH_LOCALE).toString());

    // Retrieve the geometry of the main window

    restoreGeometry(settings.value(SETTINGS_GENERAL_GEOMETRY).toByteArray());

    // Retrieve the state of the main window

    restoreState(settings.value(SETTINGS_GENERAL_STATE).toByteArray());

    // Retrieve the zoom level for the help widget

    mHelpWindow->setZoomLevel(settings.value(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->defaultZoomLevel()).toInt());
}

void MainWindow::saveSettings()
{
    QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());

    // Keep track of the language to be used by OpenCOR

    settings.setValue(SETTINGS_GENERAL_LOCALE, mLocale);

    // Keep track of the geometry of the main window

    settings.setValue(SETTINGS_GENERAL_GEOMETRY, saveGeometry());

    // Keep track of the state of the main window

    settings.setValue(SETTINGS_GENERAL_STATE, saveState());

    // Keep track of the text size multiplier for the help widget

    settings.setValue(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->zoomLevel());
}

void MainWindow::setLocale(const QString& pLocale)
{
    if (pLocale != mLocale)
    {
        mLocale = pLocale;

        // Specify the language to be used by OpenCOR

        qApp->removeTranslator(&mQtTranslator);
        mQtTranslator.load("qt_"+mLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
        qApp->installTranslator(&mQtTranslator);

        qApp->removeTranslator(&mAppTranslator);
        mAppTranslator.load(":app_"+mLocale);
        qApp->installTranslator(&mAppTranslator);

        // Translate the whole GUI (including any 'child' window), should the
        // language have changed

        mUi->retranslateUi(this);

        mHelpWindow->retranslateUi();
    }

    // Update the checked menu item
    // Note: it has to be done every single time, since selecting a menu item
    //       will automatically toggle its checked status, so...

    mUi->actionEnglish->setChecked(mLocale == ENGLISH_LOCALE);
    mUi->actionFrench->setChecked(mLocale == FRENCH_LOCALE);
}

void MainWindow::on_actionEnglish_triggered()
{
    // Select English as the language used by OpenCOR

    setLocale(ENGLISH_LOCALE);
}

void MainWindow::on_actionFrench_triggered()
{
    // Select French as the language used by OpenCOR

    setLocale(FRENCH_LOCALE);
}

void MainWindow::updateGUI()
{
    // Update the checked status of the toolbars menu items

    mUi->actionHelpToolbar->setChecked(mUi->helpToolbar->isVisible());
}

void MainWindow::on_actionHomePage_triggered()
{
    // Look up the OpenCOR home page

    QDesktopServices::openUrl(QUrl(OPENCOR_HOMEPAGE));
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, qApp->applicationName(),
                       QString("")+
                       ""+
                           "
"+qApp->applicationName()+" "+qApp->applicationVersion()+"
"+
                           "
"+getOsName()+"
"+
                       ""+
                       "
"+
                       ""+qApp->applicationName()+" "+tr("is a cross-platform CellML-based modelling environment which can be used to organise, edit, simulate and analyse CellML files."));
}
<commit_msg>Addressed a small issue related to the restart of OpenCOR following a reset all.<commit_after>#include "mainwindow.h"
#include "helpwindow.h"
#include "utils.h"

#include "ui_mainwindow.h"

#ifdef Q_WS_WIN
    #include <windows.h>
#endif

#include <QApplication>
#include <QCloseEvent>
#include <QDebug>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDir>
#include <QHelpEngine>
#include <QLibraryInfo>
#include <QMessageBox>
#include <QSettings>
#include <QTemporaryFile>
#include <QTranslator>
#include <QUrl>

#define OPENCOR_HOMEPAGE "http://opencor.sourceforge.net/"
#define OPENCOR_HELP_HOMEPAGE "qthelp://world.opencor/doc/index.html"

#define SETTINGS_INSTITUTION "World"
#define SETTINGS_GENERAL_LOCALE "General_Locale"
#define SETTINGS_GENERAL_GEOMETRY "General_Geometry"
#define SETTINGS_GENERAL_STATE "General_State"
#define SETTINGS_HELPWINDOW_ZOOMLEVEL "HelpWindow_ZoomLevel"

#define ENGLISH_LOCALE "en"
#define FRENCH_LOCALE  "fr"

MainWindow::MainWindow(bool *pRestart, QWidget *pParent) :
    QMainWindow(pParent),
    mUi(new Ui::MainWindow),
    mRestart(pRestart)
{
    // Set up the GUI

    mUi->setupUi(this);

    // Set the name of the main window to that of the application

    setWindowTitle(qApp->applicationName());

    // Some basic signals/events for some actions

    connect(mUi->actionExit, SIGNAL(triggered(bool)),
            this, SLOT(close()));
    connect(mUi->actionResetAll, SIGNAL(triggered(bool)),
            this, SLOT(resetAll()));

    // Signals/events for showing/hiding the various toolbars

    connect(mUi->actionHelpToolbar, SIGNAL(triggered(bool)),
            mUi->helpToolbar, SLOT(setVisible(bool)));
    connect(mUi->helpToolbar->toggleViewAction(), SIGNAL(toggled(bool)),
            mUi->actionHelpToolbar, SLOT(setChecked(bool)));

    // Extract the help files

    QTemporaryFile tempDir;

    tempDir.open();    // Note: this is required to get a 'valid' temporary
    tempDir.close();   //       directory name...

    mTempDirName = tempDir.fileName().append("."+qApp->applicationName());

    QDir().mkdir(mTempDirName);

    QString applicationBaseName(QFileInfo(qApp->applicationFilePath()).baseName());

    mQchFileName = mTempDirName+QDir::separator()+applicationBaseName+".qch";
    mQhcFileName = mTempDirName+QDir::separator()+applicationBaseName+".qhc";

    saveResourceAs(":qchFile", mQchFileName);
    saveResourceAs(":qhcFile", mQhcFileName);

    // Set up the help engine

    mHelpEngine = new QHelpEngine(mQhcFileName);

    mHelpEngine->setupData();

    // Help window

    mHelpWindow = new HelpWindow(mHelpEngine, QUrl(OPENCOR_HELP_HOMEPAGE));

    connect(mUi->actionHelp, SIGNAL(triggered(bool)),
            mHelpWindow, SLOT(setVisible(bool)));
    connect(mHelpWindow, SIGNAL(visibilityChanged(bool)),
            mUi->actionHelp, SLOT(setChecked(bool)));

    // Default user settings (useful the very first time we start OpenCOR or
    // after a reset all)

    defaultSettings();

    // Retrieve our default settings

    loadSettings();

    // Update the GUI, which may have changed (e.g. hidden toolbar) as a result
    // of loading OpenCOR's settings

    updateGUI();

    // Bring ourselves to the foreground. Indeed, when restarting OpenCOR as a
    // result of a result all, OpenCOR will on Mac OS X be behind the other
    // applications. This behaviour has, on occasions, also been observed on
    // Windows, so... rather than making the following Mac OS X, we may as well
    // make it cross-platform, since it doesn't have any adverse effect on any
    // of the operating system on which we use OpenCOR.

    raise();
}

MainWindow::~MainWindow()
{
    // Delete some internal objects

    delete mHelpEngine;
    delete mUi;

    // Delete the help files

    QFile(mQchFileName).remove();
    QFile(mQhcFileName).remove();

    QDir().rmdir(mTempDirName);
}

void MainWindow::closeEvent(QCloseEvent *pEvent)
{
    // Keep track of our default settings, but only if we don't want to restart
    // OpenCOR (i.e. as a result of a reset all)
    // Note: it must be done here, as opposed to the destructor, otherwise some
    //       settings (e.g. docked windows) won't be properly saved

    if (!*mRestart)
        saveSettings();

    pEvent->accept();
}

void MainWindow::singleAppMsgRcvd(const QString&)
{
    // We have just received a message from another instance of OpenCOR, so
    // bring ourselves to the foreground
    // Note: one would normally use activateWindow(), but depending on the
    //       operating system it may or not bring OpenCOR to the foreground,
    //       so... instead we do what follows, depending on the operating
    //       system...

#ifdef Q_WS_WIN
    // Retrieve OpenCOR's window Id

    WId mwWinId = winId();

    // Restore OpenCOR, should it be minimized

    if (IsIconic(mwWinId))
        SendMessage(mwWinId, WM_SYSCOMMAND, SC_RESTORE, 0);

    // Bring OpenCOR to the foreground

    DWORD foregroundThreadPId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
    DWORD mwThreadPId         = GetWindowThreadProcessId(mwWinId, NULL);

    if (foregroundThreadPId != mwThreadPId)
    {
        // OpenCOR's thread process Id is not that of the foreground window, so
        // attach the foreground thread to OpenCOR's, set OpenCOR to the
        // foreground, and detach the foreground thread from OpenCOR's

        AttachThreadInput(foregroundThreadPId, mwThreadPId, true);

        SetForegroundWindow(mwWinId);

        AttachThreadInput(foregroundThreadPId, mwThreadPId, false);
    }
    else
        // OpenCOR's thread process Id is that of the foreground window, so
        // just set OpenCOR to the foreground

        SetForegroundWindow(mwWinId);

    // Note: under Windows, to use activateWindow() will only highlight the
    //       application in the taskbar, since under Windows no application
    //       should be allowed to bring itself to the foreground when another
    //       application is already in the foreground. Fair enough, but it
    //       happens that, here, the user wants OpenCOR to be brought to the
    //       foreground, hence the above code to get the effect we are after...
#else
    // Do what one should normally do and which works fine under Mac OS X

    activateWindow();

    #ifdef Q_WS_X11
        raise();
        // Note: under Linux, to use activateWindow() may or not give the
        //       expected result. The above code is supposed to make sure that
        //       OpenCOR gets brought to the foreground, but that itsn't the
        //       case under Ubuntu at least (it works when you want to open a
        //       second instance of OpenCOR, but not thereafter!)...
    #endif
#endif

    // Now, we must handle the arguments that were passed to us

    // TODO: handle the arguments passed to the 'official' instance of OpenCOR
}

void MainWindow::resetAll()
{
    // Clear all the user settings and asked for OpenCOR to be restarted
    // (indeed, a restart will ensure that all the docked windows are properly
    // reset with regards to their dimensions)

    QSettings(SETTINGS_INSTITUTION, qApp->applicationName()).clear();

    *mRestart = true;

    close();
}

void MainWindow::defaultSettings()
{
    // Default language to be used by OpenCOR

    setLocale(ENGLISH_LOCALE);

    // Default size and position of the main window

    double spaceRatio = 1.0/13.0;
    QRect desktopGeometry = qApp->desktop()->availableGeometry();
    int horizSpace = spaceRatio*desktopGeometry.width();
    int vertSpace  = spaceRatio*desktopGeometry.height();

    setGeometry(desktopGeometry.left()+horizSpace, desktopGeometry.top()+vertSpace, desktopGeometry.width()-2*horizSpace, desktopGeometry.height()-2*vertSpace);

    // Default size and position of the help window

    mHelpWindow->setVisible(false);   // So we can set things up without having
                                      // the screen flashing

    addDockWidget(Qt::RightDockWidgetArea, mHelpWindow);

    mHelpWindow->defaultSettings();

    mHelpWindow->setVisible(true);

    // Default visibility and location of the various toolbars

    addToolBar(Qt::TopToolBarArea, mUi->helpToolbar);

    mUi->helpToolbar->setVisible(true);
}

void MainWindow::loadSettings()
{
    QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());

    // Retrieve the language to be used by OpenCOR

    setLocale(settings.value(SETTINGS_GENERAL_LOCALE, ENGLISH_LOCALE).toString());

    // Retrieve the geometry of the main window

    restoreGeometry(settings.value(SETTINGS_GENERAL_GEOMETRY).toByteArray());

    // Retrieve the state of the main window

    restoreState(settings.value(SETTINGS_GENERAL_STATE).toByteArray());

    // Retrieve the zoom level for the help widget

    mHelpWindow->setZoomLevel(settings.value(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->defaultZoomLevel()).toInt());
}

void MainWindow::saveSettings()
{
    QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());

    // Keep track of the language to be used by OpenCOR

    settings.setValue(SETTINGS_GENERAL_LOCALE, mLocale);

    // Keep track of the geometry of the main window

    settings.setValue(SETTINGS_GENERAL_GEOMETRY, saveGeometry());

    // Keep track of the state of the main window

    settings.setValue(SETTINGS_GENERAL_STATE, saveState());

    // Keep track of the text size multiplier for the help widget

    settings.setValue(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->zoomLevel());
}

void MainWindow::setLocale(const QString& pLocale)
{
    if (pLocale != mLocale)
    {
        mLocale = pLocale;

        // Specify the language to be used by OpenCOR

        qApp->removeTranslator(&mQtTranslator);
        mQtTranslator.load("qt_"+mLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
        qApp->installTranslator(&mQtTranslator);

        qApp->removeTranslator(&mAppTranslator);
        mAppTranslator.load(":app_"+mLocale);
        qApp->installTranslator(&mAppTranslator);

        // Translate the whole GUI (including any 'child' window), should the
        // language have changed

        mUi->retranslateUi(this);

        mHelpWindow->retranslateUi();
    }

    // Update the checked menu item
    // Note: it has to be done every single time, since selecting a menu item
    //       will automatically toggle its checked status, so...

    mUi->actionEnglish->setChecked(mLocale == ENGLISH_LOCALE);
    mUi->actionFrench->setChecked(mLocale == FRENCH_LOCALE);
}

void MainWindow::on_actionEnglish_triggered()
{
    // Select English as the language used by OpenCOR

    setLocale(ENGLISH_LOCALE);
}

void MainWindow::on_actionFrench_triggered()
{
    // Select French as the language used by OpenCOR

    setLocale(FRENCH_LOCALE);
}

void MainWindow::updateGUI()
{
    // Update the checked status of the toolbars menu items

    mUi->actionHelpToolbar->setChecked(mUi->helpToolbar->isVisible());
}

void MainWindow::on_actionHomePage_triggered()
{
    // Look up the OpenCOR home page

    QDesktopServices::openUrl(QUrl(OPENCOR_HOMEPAGE));
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, qApp->applicationName(),
                       QString("")+
                       ""+
                           "
"+qApp->applicationName()+" "+qApp->applicationVersion()+"
"+
                           "
"+getOsName()+"
"+
                       ""+
                       "
"+
                       ""+qApp->applicationName()+" "+tr("is a cross-platform CellML-based modelling environment which can be used to organise, edit, simulate and analyse CellML files."));
}
<|endoftext|>


<commit_before>#include "uiFilterFrame.h"

uiFilterFrame::uiFilterFrame(const Glib::RefPtr<Gtk::Builder>& refGlade)
	: m_refGlade(refGlade),
	  m_adjMinFiles(5, 1, 20, 1, 3, 0)
{
	/*
	 * Load the VBox
	 */
	m_refGlade->get_widget("VBoxFilter", mp_VBoxFilter);

	/*
	 * Spin button to select minimum number of files.
	 */
	m_refGlade->get_widget("sbMinFiles", mp_sbMinFiles);
	mp_sbMinFiles->set_adjustment(m_adjMinFiles);
	m_adjMinFiles.signal_value_changed().connect(
			sigc::mem_fun(*this, &uiFilterFrame::on_adjMinFiles_changed)
	);

	/*
	 * ComboBox to select the X-Variable
	 */
	m_XVar.append_text("All");
	m_XVar.append_text("Freq");
	m_XVar.append_text("Dur");
	m_XVar.append_text("Onset");
	m_XVar.append_text("Atten");
	m_XVar.set_active(0);
	m_XVar.signal_changed().connect(
		sigc::mem_fun(*this, &uiFilterFrame::on_XVar_changed)
	);
	mp_VBoxFilter->pack_start(m_XVar, false, false, 0);

	/*
	 * Tag filter
	 */
	Gtk::Label *tagLabel = Gtk::manage(new Gtk::Label("Tag Filter"));
	mp_VBoxFilter->pack_start(*tagLabel, false, false, 0);
	mp_VBoxFilter->pack_start(m_tag, false, false, 0);
	Glib::RefPtr<Gtk::EntryCompletion> mrp_tagCompletion = Gtk::EntryCompletion::create();
	m_tag.set_completion(mrp_tagCompletion);
	mrp_CompletionModel = Gtk::ListStore::create(m_tagColumns);
	mrp_tagCompletion->set_model(mrp_CompletionModel);
	mrp_tagCompletion->set_text_column(m_tagColumns.m_col_name);

	m_tag.signal_changed().connect(
			sigc::mem_fun(*this, &uiFilterFrame::on_tag_changed)
	);

	m_timer.start();
	Glib::signal_timeout().connect(sigc::mem_fun(*this, &uiFilterFrame::check_change_queue), 5);

	/*
	 * Hidden file checkbox
	 */
	mp_cbHidden = Gtk::manage(new Gtk::CheckButton("Show hidden files"));
	mp_VBoxFilter->pack_start(*mp_cbHidden, false, false, 0);
	mp_cbHidden->signal_toggled().connect(
		sigc::mem_fun(*this, &uiFilterFrame::on_hidden_toggled)
			);
}

uiFilterFrame::~uiFilterFrame()
{
	delete mp_sbMinFiles;
	delete mp_VBoxFilter;
}

/*
 * Changed Signal
 */
uiFilterFrame::type_signal_changed uiFilterFrame::signal_changed()
{
	return m_signal_changed;
}

void uiFilterFrame::on_hidden_toggled()
{
	m_signal_changed.emit();
}

bool uiFilterFrame::showHidden()
{
	return mp_cbHidden->get_active();
}

void uiFilterFrame::showHidden(bool set)
{
	mp_cbHidden->set_active(set);
}

void uiFilterFrame::on_XVar_changed()
{
		m_signal_changed.emit();
}

void uiFilterFrame::on_adjMinFiles_changed()
{
	m_signal_changed.emit();
}

void uiFilterFrame::on_tag_changed()
{
	if (m_timer.elapsed() >= 1)
	{
		m_signal_changed.emit();
		m_timer.reset();
	} else {
		queue_change_signal = true;
	}
}

bool uiFilterFrame::check_change_queue()
{
	if (queue_change_signal) {
		m_signal_changed.emit();
		queue_change_signal = false;
	}
	return true;
}

void uiFilterFrame::updateTagCompletion(std::vector<Glib::ustring> tags)
{
	Gtk::TreeModel::Row row;
	mrp_CompletionModel->clear();

	for (unsigned int i = 0; i < tags.size(); i++)
	{
		row = *(mrp_CompletionModel->append());
		row[m_tagColumns.m_col_name] = tags[i];
	}
}

Glib::ustring uiFilterFrame::tag()
{
	return m_tag.get_text();
}

/*
 * Return the currently selected minimum number of files
 */
int uiFilterFrame::minFiles()
{
	return (int)m_adjMinFiles.get_value();
}
void uiFilterFrame::minFiles(int set)
{
	m_adjMinFiles.set_value(set);
}

int uiFilterFrame::XVar()
{
	return m_XVar.get_active_row_number();
}
<commit_msg>Ensure hidden files are hidden by default.<commit_after>#include "uiFilterFrame.h"

uiFilterFrame::uiFilterFrame(const Glib::RefPtr<Gtk::Builder>& refGlade)
	: m_refGlade(refGlade),
	  m_adjMinFiles(5, 1, 20, 1, 3, 0)
{
	/*
	 * Load the VBox
	 */
	m_refGlade->get_widget("VBoxFilter", mp_VBoxFilter);

	/*
	 * Spin button to select minimum number of files.
	 */
	m_refGlade->get_widget("sbMinFiles", mp_sbMinFiles);
	mp_sbMinFiles->set_adjustment(m_adjMinFiles);
	m_adjMinFiles.signal_value_changed().connect(
			sigc::mem_fun(*this, &uiFilterFrame::on_adjMinFiles_changed)
	);

	/*
	 * ComboBox to select the X-Variable
	 */
	m_XVar.append_text("All");
	m_XVar.append_text("Freq");
	m_XVar.append_text("Dur");
	m_XVar.append_text("Onset");
	m_XVar.append_text("Atten");
	m_XVar.set_active(0);
	m_XVar.signal_changed().connect(
		sigc::mem_fun(*this, &uiFilterFrame::on_XVar_changed)
	);
	mp_VBoxFilter->pack_start(m_XVar, false, false, 0);

	/*
	 * Tag filter
	 */
	Gtk::Label *tagLabel = Gtk::manage(new Gtk::Label("Tag Filter"));
	mp_VBoxFilter->pack_start(*tagLabel, false, false, 0);
	mp_VBoxFilter->pack_start(m_tag, false, false, 0);
	Glib::RefPtr<Gtk::EntryCompletion> mrp_tagCompletion = Gtk::EntryCompletion::create();
	m_tag.set_completion(mrp_tagCompletion);
	mrp_CompletionModel = Gtk::ListStore::create(m_tagColumns);
	mrp_tagCompletion->set_model(mrp_CompletionModel);
	mrp_tagCompletion->set_text_column(m_tagColumns.m_col_name);

	m_tag.signal_changed().connect(
			sigc::mem_fun(*this, &uiFilterFrame::on_tag_changed)
	);

	m_timer.start();
	Glib::signal_timeout().connect(sigc::mem_fun(*this, &uiFilterFrame::check_change_queue), 5);

	/*
	 * Hidden file checkbox
	 */
	mp_cbHidden = Gtk::manage(new Gtk::CheckButton("Show hidden files"));
	mp_cbHidden->set_active(false);
	mp_VBoxFilter->pack_start(*mp_cbHidden, false, false, 0);
	mp_cbHidden->signal_toggled().connect(
		sigc::mem_fun(*this, &uiFilterFrame::on_hidden_toggled)
			);
}

uiFilterFrame::~uiFilterFrame()
{
	delete mp_sbMinFiles;
	delete mp_VBoxFilter;
}

/*
 * Changed Signal
 */
uiFilterFrame::type_signal_changed uiFilterFrame::signal_changed()
{
	return m_signal_changed;
}

void uiFilterFrame::on_hidden_toggled()
{
	m_signal_changed.emit();
}

bool uiFilterFrame::showHidden()
{
	return mp_cbHidden->get_active();
}

void uiFilterFrame::showHidden(bool set)
{
	mp_cbHidden->set_active(set);
}

void uiFilterFrame::on_XVar_changed()
{
		m_signal_changed.emit();
}

void uiFilterFrame::on_adjMinFiles_changed()
{
	m_signal_changed.emit();
}

void uiFilterFrame::on_tag_changed()
{
	if (m_timer.elapsed() >= 1)
	{
		m_signal_changed.emit();
		m_timer.reset();
	} else {
		queue_change_signal = true;
	}
}

bool uiFilterFrame::check_change_queue()
{
	if (queue_change_signal) {
		m_signal_changed.emit();
		queue_change_signal = false;
	}
	return true;
}

void uiFilterFrame::updateTagCompletion(std::vector<Glib::ustring> tags)
{
	Gtk::TreeModel::Row row;
	mrp_CompletionModel->clear();

	for (unsigned int i = 0; i < tags.size(); i++)
	{
		row = *(mrp_CompletionModel->append());
		row[m_tagColumns.m_col_name] = tags[i];
	}
}

Glib::ustring uiFilterFrame::tag()
{
	return m_tag.get_text();
}

/*
 * Return the currently selected minimum number of files
 */
int uiFilterFrame::minFiles()
{
	return (int)m_adjMinFiles.get_value();
}
void uiFilterFrame::minFiles(int set)
{
	m_adjMinFiles.set_value(set);
}

int uiFilterFrame::XVar()
{
	return m_XVar.get_active_row_number();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImager.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to Matt Turek who developed this class.

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/

#include "vtkImager.h"
#include "vtkImageWindow.h"

// Description:
// Create an imager with viewport (0, 0, 1, 1)
vtkImager::vtkImager()
{
  vtkDebugMacro(<< "vtkImager::vtkImager");

  this->Viewport[0] = 0.0; // min x
  this->Viewport[1] = 1.0; // max x
  this->Viewport[2] = 0.0; // min y
  this->Viewport[3] = 1.0; // max y

}

void vtkImager::Render()
{
  vtkActor2D* tempActor;

  vtkDebugMacro (<< "vtkImager::Render");

  if (this->StartRenderMethod)
    {
    (*this->StartRenderMethod)(this->StartRenderMethodArg);
    }

  int numActors = this->Actors2D->GetNumberOfItems();
  if (numActors == 0)
    {
    vtkDebugMacro (<< "vtkImager::Render - No actors in collection");
    return;
    }

  vtkDebugMacro(<<"vtkImager::Render - " << numActors << " actors in collection");
  vtkDebugMacro(<<"vtkImager::Render - Sorting actor collection.");

  this->Actors2D->Sort();

  for ( this->Actors2D->InitTraversal();
	(tempActor = this->Actors2D->GetNextItem());)
    {
    // Make sure that the actor is visible before rendering
    if (tempActor->GetVisibility() == 1)
      {
      tempActor->Render(this);
      }
    }

  if (this->EndRenderMethod)
    {
    (*this->EndRenderMethod)(this->EndRenderMethodArg);
    }

  return;

}

<commit_msg>FIX: previous mistake is bounds<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImager.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to Matt Turek who developed this class.

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/

#include "vtkImager.h"
#include "vtkImageWindow.h"

// Description:
// Create an imager with viewport (0, 0, 1, 1)
vtkImager::vtkImager()
{
  vtkDebugMacro(<< "vtkImager::vtkImager");

  this->Viewport[0] = 0.0; // min x
  this->Viewport[1] = 0.0; // min y
  this->Viewport[2] = 1.0; // max x
  this->Viewport[3] = 1.0; // max y

}

void vtkImager::Render()
{
  vtkActor2D* tempActor;

  vtkDebugMacro (<< "vtkImager::Render");

  if (this->StartRenderMethod)
    {
    (*this->StartRenderMethod)(this->StartRenderMethodArg);
    }

  int numActors = this->Actors2D->GetNumberOfItems();
  if (numActors == 0)
    {
    vtkDebugMacro (<< "vtkImager::Render - No actors in collection");
    return;
    }

  vtkDebugMacro(<<"vtkImager::Render - " << numActors << " actors in collection");
  vtkDebugMacro(<<"vtkImager::Render - Sorting actor collection.");

  this->Actors2D->Sort();

  for ( this->Actors2D->InitTraversal();
	(tempActor = this->Actors2D->GetNextItem());)
    {
    // Make sure that the actor is visible before rendering
    if (tempActor->GetVisibility() == 1)
      {
      tempActor->Render(this);
      }
    }

  if (this->EndRenderMethod)
    {
    (*this->EndRenderMethod)(this->EndRenderMethodArg);
    }

  return;

}

<|endoftext|>