<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ximpgrp.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:10:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XIMPGROUP_HXX
#define _XIMPGROUP_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif

#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif

#ifndef _XIMPSHAPE_HXX
#include "ximpshap.hxx"
#endif

//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)

class SdXMLGroupShapeContext : public SdXMLShapeContext
{
    // the shape group this group is working on
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxChilds;

protected:
    void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
        { mxShapes = rNew; }

public:
    TYPEINFO();

    SdXMLGroupShapeContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
        com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
        sal_Bool bTemporaryShape);
    virtual ~SdXMLGroupShapeContext();

    virtual SvXMLImportContext *CreateChildContext(
        USHORT nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
    virtual void EndElement();

    const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
        { return mxShapes; }
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
        { return mxShapes; }
};

#endif  //  _XIMPGROUP_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.162); FILE MERGED 2008/04/01 16:09:43 thb 1.7.162.3: #i85898# Stripping all external header guards 2008/04/01 13:04:46 thb 1.7.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:08 rt 1.7.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ximpgrp.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XIMPGROUP_HXX
#define _XIMPGROUP_HXX

#include <xmloff/xmlictxt.hxx>
#include "sdxmlimp_impl.hxx"
#include <xmloff/nmspmap.hxx>
#include <com/sun/star/drawing/XShapes.hpp>
#include <tools/rtti.hxx>
#include "ximpshap.hxx"

//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)

class SdXMLGroupShapeContext : public SdXMLShapeContext
{
    // the shape group this group is working on
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxChilds;

protected:
    void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
        { mxShapes = rNew; }

public:
    TYPEINFO();

    SdXMLGroupShapeContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
        com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
        sal_Bool bTemporaryShape);
    virtual ~SdXMLGroupShapeContext();

    virtual SvXMLImportContext *CreateChildContext(
        USHORT nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
    virtual void EndElement();

    const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
        { return mxShapes; }
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
        { return mxShapes; }
};

#endif  //  _XIMPGROUP_HXX
<|endoftext|>


<commit_before>#ifndef slic3r_Semver_hpp_
#define slic3r_Semver_hpp_

#include <string>
#include <cstring>
#include <ostream>
#include <boost/optional.hpp>
#include <boost/format.hpp>

#include "semver/semver.h"

namespace Slic3r {

class Semver
{
public:
	struct Major { const int i;  Major(int i) : i(i) {} };
	struct Minor { const int i;  Minor(int i) : i(i) {} };
	struct Patch { const int i;  Patch(int i) : i(i) {} };

	Semver() : ver(semver_zero()) {}

	Semver(int major, int minor, int patch,
		boost::optional<std::string> metadata = boost::none,
		boost::optional<std::string> prerelease = boost::none)
	{
		ver.major = major;
		ver.minor = minor;
		ver.patch = patch;
		ver.metadata = metadata ? std::strcpy(ver.metadata, metadata->c_str()) : nullptr;
		ver.prerelease = prerelease ? std::strcpy(ver.prerelease, prerelease->c_str()) : nullptr;
	}

	static boost::optional<Semver> parse(const std::string &str)
	{
		semver_t ver = semver_zero();
		if (::semver_parse(str.c_str(), &ver) == 0) {
			return Semver(ver);
		} else {
			return boost::none;
		}
	}

	static const Semver zero() { return Semver(semver_zero()); }

	static const Semver inf()
	{
		static semver_t ver = { std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), nullptr, nullptr };
		return Semver(ver);
	}

	static const Semver invalid()
	{
		static semver_t ver = { -1, 0, 0, nullptr, nullptr };
		return Semver(ver);
	}

	Semver(Semver &&other) : ver(other.ver) { other.ver = semver_zero(); }
	Semver(const Semver &other) : ver(::semver_copy(&other.ver)) {}

	Semver &operator=(Semver &&other)
	{
		::semver_free(&ver);
		ver = other.ver;
		other.ver = semver_zero();
		return *this;
	}

	Semver &operator=(const Semver &other)
	{
		::semver_free(&ver);
		ver = ::semver_copy(&other.ver);
		return *this;
	}

	~Semver() { ::semver_free(&ver); }

	// const accessors
	int 		major() 	 const { return ver.major; }
	int 		minor() 	 const { return ver.minor; }
	int 		patch() 	 const { return ver.patch; }
	const char*	prerelease() const { return ver.prerelease; }
	const char*	metadata() 	 const { return ver.metadata; }

	// Comparison
	bool operator<(const Semver &b)  const { return ::semver_compare(ver, b.ver) == -1; }
	bool operator<=(const Semver &b) const { return ::semver_compare(ver, b.ver) <= 0; }
	bool operator==(const Semver &b) const { return ::semver_compare(ver, b.ver) == 0; }
	bool operator!=(const Semver &b) const { return ::semver_compare(ver, b.ver) != 0; }
	bool operator>=(const Semver &b) const { return ::semver_compare(ver, b.ver) >= 0; }
	bool operator>(const Semver &b)  const { return ::semver_compare(ver, b.ver) == 1; }
	// We're using '&' instead of the '~' operator here as '~' is unary-only:
	// Satisfies patch if Major and minor are equal.
	bool operator&(const Semver &b) const { return ::semver_satisfies_patch(ver, b.ver); }
	bool operator^(const Semver &b) const { return ::semver_satisfies_caret(ver, b.ver); }
	bool in_range(const Semver &low, const Semver &high) const { return low <= *this && *this <= high; }

	// Conversion
	std::string to_string() const {
		auto res = (boost::format("%1%.%2%.%3%") % ver.major % ver.minor % ver.patch).str();
		if (ver.prerelease != nullptr) { res += '-'; res += ver.prerelease; }
		if (ver.metadata != nullptr)   { res += '+'; res += ver.metadata; }
		return res;
	}

	// Arithmetics
	Semver& operator+=(const Major &b) { ver.major += b.i; return *this; }
	Semver& operator+=(const Minor &b) { ver.minor += b.i; return *this; }
	Semver& operator+=(const Patch &b) { ver.patch += b.i; return *this; }
	Semver& operator-=(const Major &b) { ver.major -= b.i; return *this; }
	Semver& operator-=(const Minor &b) { ver.minor -= b.i; return *this; }
	Semver& operator-=(const Patch &b) { ver.patch -= b.i; return *this; }
	Semver operator+(const Major &b) const { Semver res(*this); return res += b; }
	Semver operator+(const Minor &b) const { Semver res(*this); return res += b; }
	Semver operator+(const Patch &b) const { Semver res(*this); return res += b; }
	Semver operator-(const Major &b) const { Semver res(*this); return res -= b; }
	Semver operator-(const Minor &b) const { Semver res(*this); return res -= b; }
	Semver operator-(const Patch &b) const { Semver res(*this); return res -= b; }

private:
	semver_t ver;

	Semver(semver_t ver) : ver(ver) {}

	static semver_t semver_zero() { return { 0, 0, 0, nullptr, nullptr }; }
};

}
#endif
<commit_msg>Fix: Avoid the infamous `major` & `minor` macros on GCC<commit_after>#ifndef slic3r_Semver_hpp_
#define slic3r_Semver_hpp_

#include <string>
#include <cstring>
#include <ostream>
#include <boost/optional.hpp>
#include <boost/format.hpp>

#include "semver/semver.h"

namespace Slic3r {

class Semver
{
public:
	struct Major { const int i;  Major(int i) : i(i) {} };
	struct Minor { const int i;  Minor(int i) : i(i) {} };
	struct Patch { const int i;  Patch(int i) : i(i) {} };

	Semver() : ver(semver_zero()) {}

	Semver(int major, int minor, int patch,
		boost::optional<std::string> metadata = boost::none,
		boost::optional<std::string> prerelease = boost::none)
	{
		ver.major = major;
		ver.minor = minor;
		ver.patch = patch;
		ver.metadata = metadata ? std::strcpy(ver.metadata, metadata->c_str()) : nullptr;
		ver.prerelease = prerelease ? std::strcpy(ver.prerelease, prerelease->c_str()) : nullptr;
	}

	static boost::optional<Semver> parse(const std::string &str)
	{
		semver_t ver = semver_zero();
		if (::semver_parse(str.c_str(), &ver) == 0) {
			return Semver(ver);
		} else {
			return boost::none;
		}
	}

	static const Semver zero() { return Semver(semver_zero()); }

	static const Semver inf()
	{
		static semver_t ver = { std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), nullptr, nullptr };
		return Semver(ver);
	}

	static const Semver invalid()
	{
		static semver_t ver = { -1, 0, 0, nullptr, nullptr };
		return Semver(ver);
	}

	Semver(Semver &&other) : ver(other.ver) { other.ver = semver_zero(); }
	Semver(const Semver &other) : ver(::semver_copy(&other.ver)) {}

	Semver &operator=(Semver &&other)
	{
		::semver_free(&ver);
		ver = other.ver;
		other.ver = semver_zero();
		return *this;
	}

	Semver &operator=(const Semver &other)
	{
		::semver_free(&ver);
		ver = ::semver_copy(&other.ver);
		return *this;
	}

	~Semver() { ::semver_free(&ver); }

	// const accessors
	int 		maj()        const { return ver.major; }
	int 		min()        const { return ver.minor; }
	int 		patch() 	 const { return ver.patch; }
	const char*	prerelease() const { return ver.prerelease; }
	const char*	metadata() 	 const { return ver.metadata; }

	// Comparison
	bool operator<(const Semver &b)  const { return ::semver_compare(ver, b.ver) == -1; }
	bool operator<=(const Semver &b) const { return ::semver_compare(ver, b.ver) <= 0; }
	bool operator==(const Semver &b) const { return ::semver_compare(ver, b.ver) == 0; }
	bool operator!=(const Semver &b) const { return ::semver_compare(ver, b.ver) != 0; }
	bool operator>=(const Semver &b) const { return ::semver_compare(ver, b.ver) >= 0; }
	bool operator>(const Semver &b)  const { return ::semver_compare(ver, b.ver) == 1; }
	// We're using '&' instead of the '~' operator here as '~' is unary-only:
	// Satisfies patch if Major and minor are equal.
	bool operator&(const Semver &b) const { return ::semver_satisfies_patch(ver, b.ver); }
	bool operator^(const Semver &b) const { return ::semver_satisfies_caret(ver, b.ver); }
	bool in_range(const Semver &low, const Semver &high) const { return low <= *this && *this <= high; }

	// Conversion
	std::string to_string() const {
		auto res = (boost::format("%1%.%2%.%3%") % ver.major % ver.minor % ver.patch).str();
		if (ver.prerelease != nullptr) { res += '-'; res += ver.prerelease; }
		if (ver.metadata != nullptr)   { res += '+'; res += ver.metadata; }
		return res;
	}

	// Arithmetics
	Semver& operator+=(const Major &b) { ver.major += b.i; return *this; }
	Semver& operator+=(const Minor &b) { ver.minor += b.i; return *this; }
	Semver& operator+=(const Patch &b) { ver.patch += b.i; return *this; }
	Semver& operator-=(const Major &b) { ver.major -= b.i; return *this; }
	Semver& operator-=(const Minor &b) { ver.minor -= b.i; return *this; }
	Semver& operator-=(const Patch &b) { ver.patch -= b.i; return *this; }
	Semver operator+(const Major &b) const { Semver res(*this); return res += b; }
	Semver operator+(const Minor &b) const { Semver res(*this); return res += b; }
	Semver operator+(const Patch &b) const { Semver res(*this); return res += b; }
	Semver operator-(const Major &b) const { Semver res(*this); return res -= b; }
	Semver operator-(const Minor &b) const { Semver res(*this); return res -= b; }
	Semver operator-(const Patch &b) const { Semver res(*this); return res -= b; }

private:
	semver_t ver;

	Semver(semver_t ver) : ver(ver) {}

	static semver_t semver_zero() { return { 0, 0, 0, nullptr, nullptr }; }
};

}
#endif
<|endoftext|>


<commit_before>// 2-SAT - O(V+E)

int n, vis[2*N], ord[2*N], ordn, cnt, cmp[2*N], val[N];
vector<int> adj[2*N], adjt[2*N];

// for a variable u with idx i
// u is 2*i and !u is 2*i+1
// (a v b) == !a -> b ^ !b -> a

int v(int x) { return 2*x; }
int nv(int x) { return 2*x+1; }

// add clause (a v b)
void add(int a, int b){
  adj[a^1].push_back(b);
  adj[b^1].push_back(a);
  adjt[b].push_back(a^1);
  adjt[a].push_back(b^1);
}

void dfs(int x){
  vis[x] = 1;
  for(auto v : adj[x]) if(!vis[v]) dfs(v);
  ord[ordn++] = x;
}

void dfst(int x){
  cmp[x] = cnt, vis[x] = 0;
  for(auto v : adj[x]) if(vis[v]) dfst(v);
}

bool run2sat(){
  for(int i = 1; i <= n; i++) {
    if(!vis[v(i)]) dfs(v(i));
    if(!vis[nv(i)]) dfs(nv(i));
  }
  for(int i = ordn-1; i >= 0; i--)
    if(vis[ord[i]]) cnt++, dfst(ord[i]);
  for(int i = 1; i <= n; i ++){
    if(cmp[v(i)] == cmp[nv(i)]) return false;
    val[i] = cmp[v(i)] > cmp[nv(i)];
  }
  return true;
}
<commit_msg>Update 2-sat-navarro.cpp<commit_after>// 2-SAT - O(V+E)

int n, vis[2*N], ord[2*N], ordn, cnt, cmp[2*N], val[N];
vector<int> adj[2*N], adjt[2*N];

// for a variable u with idx i
// u is 2*i and !u is 2*i+1
// (a v b) == !a -> b ^ !b -> a

int v(int x) { return 2*x; }
int nv(int x) { return 2*x+1; }

// add clause (a v b)
void add(int a, int b){
  adj[a^1].push_back(b);
  adj[b^1].push_back(a);
  adjt[b].push_back(a^1);
  adjt[a].push_back(b^1);
}

void dfs(int x){
  vis[x] = 1;
  for(auto v : adj[x]) if(!vis[v]) dfs(v);
  ord[ordn++] = x;
}

void dfst(int x){
  cmp[x] = cnt, vis[x] = 0;
  for(auto v : adjt[x]) if(vis[v]) dfst(v);
}

bool run2sat(){
  for(int i = 1; i <= n; i++) {
    if(!vis[v(i)]) dfs(v(i));
    if(!vis[nv(i)]) dfs(nv(i));
  }
  for(int i = ordn-1; i >= 0; i--)
    if(vis[ord[i]]) cnt++, dfst(ord[i]);
  for(int i = 1; i <= n; i ++){
    if(cmp[v(i)] == cmp[nv(i)]) return false;
    val[i] = cmp[v(i)] > cmp[nv(i)];
  }
  return true;
}
<|endoftext|>


<commit_before>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "ascii_grid_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstdio>   // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string, std::stoi
#include <vector>   // std::vector

namespace loaders
{
    bool load_ascii_grid(
            std::string ascii_grid_file_name,
            std::vector<glm::vec3>& out_vertices,
            std::vector<glm::vec2>& out_UVs,
            std::vector<glm::vec3>& out_normals,
            std::string triangulation_type)
    {
        // Beginning of `L4133D.asc`.
        //
        // ncols        3000
        // nrows        3000
        // xllcorner    386000.000000000000
        // yllcorner    6672000.000000000000
        // cellsize     2.000000000000
        // NODATA_value  -9999.000
        // 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832

        std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n";

        // Open the file
        const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str();
        std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb");
        if (!file)
        {
            std::cerr << ascii_grid_file_name << " could not be opened.\n";
            return false;
        }

        // Find out file size.
        if (std::fseek(file, 0, SEEK_END) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        uint64_t file_size = std::ftell(file);

        // Move file pointer to the beginning of file.
        if (fseek(file, 0, SEEK_SET) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        // Reserve enough memory.
        char* point_data = new char[file_size];

        if (point_data == nullptr)
        {
            std::cerr << "Reserving memory for point data failed.\n";
            std::fclose(file);
            return false;
        }

        char* point_data_pointer = point_data;

        // Read the point data from the file into the buffer.
        std::fread(point_data, 1, file_size, file);

        // Everything is in memory now, the file can be closed
        std::fclose(file);

        // All possible block identifier strings.
        std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_width = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "ncols");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_height = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "nrows");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float xllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "xllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float yllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "yllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float cellsize = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "cellsize");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value");

        uint32_t image_width_in_use = 3000; // should be 3000.
        uint32_t image_height_in_use = 2000;

        float* vertex_data;
        vertex_data = new float[image_width_in_use * image_height_in_use];

        if (vertex_data == nullptr)
        {
            std::cerr << "Reserving memory for vertex data failed.\n";
            delete point_data;
            return false;
        }

        float* vertex_pointer;
        vertex_pointer = vertex_data;

        // start processing image_data.

        for (uint32_t z = 0; z < image_height_in_use; z++)
        {
            for (uint32_t x = 0; x < image_width_in_use; x++)
            {
                while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
                {
                    point_data_pointer++;
                }
                *vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr);
            }
        }

        delete point_data;

        std::cout << "Triangulating ascii grid data.\n";

        TriangulateQuadsStruct triangulate_quads_struct;
        // triangulate_quads_struct.image_width = image_width;
        triangulate_quads_struct.image_width = image_width_in_use;
        triangulate_quads_struct.image_height = image_height_in_use;
        triangulate_quads_struct.triangulation_type = triangulation_type;
        triangulate_quads_struct.sphere_radius = NAN;
        triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.

        bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        delete vertex_data;
        return true;
    }
}
<commit_msg>Bugfix: Read `cellsize` correctly.<commit_after>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "ascii_grid_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstdio>   // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string, std::stoi
#include <vector>   // std::vector

namespace loaders
{
    bool load_ascii_grid(
            std::string ascii_grid_file_name,
            std::vector<glm::vec3>& out_vertices,
            std::vector<glm::vec2>& out_UVs,
            std::vector<glm::vec3>& out_normals,
            std::string triangulation_type)
    {
        // Beginning of `L4133D.asc`.
        //
        // ncols        3000
        // nrows        3000
        // xllcorner    386000.000000000000
        // yllcorner    6672000.000000000000
        // cellsize     2.000000000000
        // NODATA_value  -9999.000
        // 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832

        std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n";

        // Open the file
        const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str();
        std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb");
        if (!file)
        {
            std::cerr << ascii_grid_file_name << " could not be opened.\n";
            return false;
        }

        // Find out file size.
        if (std::fseek(file, 0, SEEK_END) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        uint64_t file_size = std::ftell(file);

        // Move file pointer to the beginning of file.
        if (fseek(file, 0, SEEK_SET) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        // Reserve enough memory.
        char* point_data = new char[file_size];

        if (point_data == nullptr)
        {
            std::cerr << "Reserving memory for point data failed.\n";
            std::fclose(file);
            return false;
        }

        char* point_data_pointer = point_data;

        // Read the point data from the file into the buffer.
        std::fread(point_data, 1, file_size, file);

        // Everything is in memory now, the file can be closed
        std::fclose(file);

        // All possible block identifier strings.
        std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_width = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "ncols");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_height = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "nrows");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float xllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "xllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float yllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "yllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float cellsize = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "cellsize");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value");

        uint32_t image_width_in_use = 3000; // should be 3000.
        uint32_t image_height_in_use = 2000;

        float* vertex_data;
        vertex_data = new float[image_width_in_use * image_height_in_use];

        if (vertex_data == nullptr)
        {
            std::cerr << "Reserving memory for vertex data failed.\n";
            delete point_data;
            return false;
        }

        float* vertex_pointer;
        vertex_pointer = vertex_data;

        // start processing image_data.

        for (uint32_t z = 0; z < image_height_in_use; z++)
        {
            for (uint32_t x = 0; x < image_width_in_use; x++)
            {
                while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
                {
                    point_data_pointer++;
                }
                *vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr);
            }
        }

        delete point_data;

        std::cout << "Triangulating ascii grid data.\n";

        TriangulateQuadsStruct triangulate_quads_struct;
        // triangulate_quads_struct.image_width = image_width;
        triangulate_quads_struct.image_width = image_width_in_use;
        triangulate_quads_struct.image_height = image_height_in_use;
        triangulate_quads_struct.triangulation_type = triangulation_type;
        triangulate_quads_struct.sphere_radius = NAN;
        triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.

        bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        delete vertex_data;
        return true;
    }
}
<|endoftext|>


<commit_before><commit_msg>Replaced `#include` line with a forward declaration.<commit_after><|endoftext|>


<commit_before>#include "DynamixelConsole.h"

const DynamixelCommand DynamixelConsole::sCommand[] =
	{{"ping", &DynamixelConsole::ping},
	{"read", &DynamixelConsole::read},
	{"write", &DynamixelConsole::write},
	{"reset", &DynamixelConsole::reset}};

DynamixelConsole::DynamixelConsole(DynamixelInterface &aInterface, Stream &aConsole):
	mInterface(aInterface), mConsole(aConsole)
{
	mLinePtr=&(mLineBuffer[0]);
	mLineBuffer[sLineBufferSize]=0;
}

void DynamixelConsole::loop()
{
	//empty input buffer
	while(mConsole.available())
		mConsole.read();

	//write new command prompt
	mConsole.write(">");

	// read one command line
	char c;
	while((c=mConsole.read())!='\n' && c!='\r')
	{
		if(c>=32 && c<=126 && (mLinePtr-&(mLineBuffer[0]))<sLineBufferSize)
		{
			mConsole.write(c);
			*mLinePtr=c;
			++mLinePtr;
		}
		else if(c==8 && mLinePtr>(&(mLineBuffer[0])))
		{
			mConsole.write(c);
			--mLinePtr;
		}
	}
	//new line
	mConsole.write("\n\r");
	// run command
	run();
	// reset buffer
	mLinePtr=&(mLineBuffer[0]);
}

void DynamixelConsole::run()
{
	char *argv[16];
	int argc=parseCmd(argv);

	const int commandNumber=sizeof(sCommand)/sizeof(DynamixelCommand);
	for(int i=0; i<commandNumber; ++i)
	{
		if(strcmp(argv[0],sCommand[i].mName)==0)
		{
			DynamixelStatus status=(this->*(sCommand[i].mCallback))(argc, argv);
			printStatus(status);
			break;
		}
	}
}

int DynamixelConsole::parseCmd(char **argv)
{
	int argc=0;
	char *ptr=&mLineBuffer[0];
	while(argc<15)
	{
		while(*ptr==' ' && ptr<mLinePtr)
		{
			++ptr;
		}
		if(ptr>=mLinePtr)
		{
			break;
		}
		argv[argc]=ptr;
		while(*ptr!=' ' && ptr<mLinePtr)
		{
			++ptr;
		}
		*ptr='\0';
		++ptr;
		++argc;
	}
	argv[argc]=0;
	return argc;
}

void DynamixelConsole::printStatus(DynamixelStatus aStatus)
{
	if(aStatus==DYN_STATUS_INTERNAL_ERROR)
	{
		mConsole.print("Invalid command parameters\n\r");
		return;
	}
	mConsole.print("Status : ");
	if(aStatus==DYN_STATUS_OK)
	{
		mConsole.print("ok");
	}
	else if(aStatus&DYN_STATUS_COM_ERROR)
	{
		mConsole.print("communication error");
		if(aStatus&DYN_STATUS_TIMEOUT)
		{
			mConsole.print(", timeout");
		}
		else if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
		{
			mConsole.print(", invalid response checksum");
		}
	}
	else
	{
		mConsole.print("communication ok");

		if(aStatus&DYN_STATUS_INPUT_VOLTAGE_ERROR)
		{
			mConsole.print(", invalid input voltage");
		}
		if(aStatus&DYN_STATUS_ANGLE_LIMIT_ERROR)
		{
			mConsole.print(", angle limit error");
		}
		if(aStatus&DYN_STATUS_OVERHEATING_ERROR)
		{
			mConsole.print(", overheating");
		}
		if(aStatus&DYN_STATUS_RANGE_ERROR)
		{
			mConsole.print(", out of range value");
		}
		if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
		{
			mConsole.print(", invalid command checksum");
		}
		if(aStatus&DYN_STATUS_OVERLOAD_ERROR)
		{
			mConsole.print(", overload");
		}
		if(aStatus&DYN_STATUS_INSTRUCTION_ERROR)
		{
			mConsole.print(", invalid instruction");
		}
	}
	mConsole.print("\n\r");
}

void DynamixelConsole::printData(const uint8_t *data, uint8_t length)
{
	for(uint8_t i=0; i<length; ++i)
	{
		mConsole.print(data[i]);
		mConsole.print(" ");
	}
	mConsole.print("\n\r");
}

DynamixelStatus DynamixelConsole::ping(int argc, char **argv)
{
	int id=0;
	if(argc<2)
	{
		mConsole.print("Usage : ping <id>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id<1 || id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	return mInterface.ping(id);
}

DynamixelStatus DynamixelConsole::read(int argc, char **argv)
{
	int id=0, addr=0, length=1;
	if(argc<3)
	{
		mConsole.print("Usage : read <id> <address> <length=1>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id<1 || id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	addr=atoi(argv[2]);
	if(argc>3)
	{
		length=atoi(argv[3]);
	}
	if(length>255)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	uint8_t *ptr=new uint8_t[length];
	DynamixelStatus result=mInterface.read(id, addr, length, ptr);
	printData(ptr,length);
	delete ptr;
	return result;
}

DynamixelStatus DynamixelConsole::write(int argc, char **argv)
{
	int id=0, addr=0, length=0;
	if(argc<4)
	{
		mConsole.print("Usage : write <id> <address> <data_1> ... <data_N>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id<1 || id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	addr=atoi(argv[2]);
	length=argc-3;
	if(length>255)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}

	uint8_t *ptr=new uint8_t[length];
	for(uint8_t i=0; i<length; ++i)
	{
		ptr[i]=atoi(argv[i+3]);
	}
	DynamixelStatus result=mInterface.write(id, addr, length, ptr);
	delete ptr;
	return result;
}

DynamixelStatus DynamixelConsole::reset(int argc, char **argv)
{
	int id=0;
	if(argc<2)
	{
		mConsole.print("Usage : reset <id>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id<1 || id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	DynamixelStatus result=mInterface.reset(id);
	return result;
}

<commit_msg>zero is a valid id<commit_after>#include "DynamixelConsole.h"

const DynamixelCommand DynamixelConsole::sCommand[] =
	{{"ping", &DynamixelConsole::ping},
	{"read", &DynamixelConsole::read},
	{"write", &DynamixelConsole::write},
	{"reset", &DynamixelConsole::reset}};

DynamixelConsole::DynamixelConsole(DynamixelInterface &aInterface, Stream &aConsole):
	mInterface(aInterface), mConsole(aConsole)
{
	mLinePtr=&(mLineBuffer[0]);
	mLineBuffer[sLineBufferSize]=0;
}

void DynamixelConsole::loop()
{
	//empty input buffer
	while(mConsole.available())
		mConsole.read();

	//write new command prompt
	mConsole.write(">");

	// read one command line
	char c;
	while((c=mConsole.read())!='\n' && c!='\r')
	{
		if(c>=32 && c<=126 && (mLinePtr-&(mLineBuffer[0]))<sLineBufferSize)
		{
			mConsole.write(c);
			*mLinePtr=c;
			++mLinePtr;
		}
		else if(c==8 && mLinePtr>(&(mLineBuffer[0])))
		{
			mConsole.write(c);
			--mLinePtr;
		}
	}
	//new line
	mConsole.write("\n\r");
	// run command
	run();
	// reset buffer
	mLinePtr=&(mLineBuffer[0]);
}

void DynamixelConsole::run()
{
	char *argv[16];
	int argc=parseCmd(argv);

	const int commandNumber=sizeof(sCommand)/sizeof(DynamixelCommand);
	for(int i=0; i<commandNumber; ++i)
	{
		if(strcmp(argv[0],sCommand[i].mName)==0)
		{
			DynamixelStatus status=(this->*(sCommand[i].mCallback))(argc, argv);
			printStatus(status);
			break;
		}
	}
}

int DynamixelConsole::parseCmd(char **argv)
{
	int argc=0;
	char *ptr=&mLineBuffer[0];
	while(argc<15)
	{
		while(*ptr==' ' && ptr<mLinePtr)
		{
			++ptr;
		}
		if(ptr>=mLinePtr)
		{
			break;
		}
		argv[argc]=ptr;
		while(*ptr!=' ' && ptr<mLinePtr)
		{
			++ptr;
		}
		*ptr='\0';
		++ptr;
		++argc;
	}
	argv[argc]=0;
	return argc;
}

void DynamixelConsole::printStatus(DynamixelStatus aStatus)
{
	if(aStatus==DYN_STATUS_INTERNAL_ERROR)
	{
		mConsole.print("Invalid command parameters\n\r");
		return;
	}
	mConsole.print("Status : ");
	if(aStatus==DYN_STATUS_OK)
	{
		mConsole.print("ok");
	}
	else if(aStatus&DYN_STATUS_COM_ERROR)
	{
		mConsole.print("communication error");
		if(aStatus&DYN_STATUS_TIMEOUT)
		{
			mConsole.print(", timeout");
		}
		else if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
		{
			mConsole.print(", invalid response checksum");
		}
	}
	else
	{
		mConsole.print("communication ok");

		if(aStatus&DYN_STATUS_INPUT_VOLTAGE_ERROR)
		{
			mConsole.print(", invalid input voltage");
		}
		if(aStatus&DYN_STATUS_ANGLE_LIMIT_ERROR)
		{
			mConsole.print(", angle limit error");
		}
		if(aStatus&DYN_STATUS_OVERHEATING_ERROR)
		{
			mConsole.print(", overheating");
		}
		if(aStatus&DYN_STATUS_RANGE_ERROR)
		{
			mConsole.print(", out of range value");
		}
		if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
		{
			mConsole.print(", invalid command checksum");
		}
		if(aStatus&DYN_STATUS_OVERLOAD_ERROR)
		{
			mConsole.print(", overload");
		}
		if(aStatus&DYN_STATUS_INSTRUCTION_ERROR)
		{
			mConsole.print(", invalid instruction");
		}
	}
	mConsole.print("\n\r");
}

void DynamixelConsole::printData(const uint8_t *data, uint8_t length)
{
	for(uint8_t i=0; i<length; ++i)
	{
		mConsole.print(data[i]);
		mConsole.print(" ");
	}
	mConsole.print("\n\r");
}

DynamixelStatus DynamixelConsole::ping(int argc, char **argv)
{
	int id=0;
	if(argc<2)
	{
		mConsole.print("Usage : ping <id>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	return mInterface.ping(id);
}

DynamixelStatus DynamixelConsole::read(int argc, char **argv)
{
	int id=0, addr=0, length=1;
	if(argc<3)
	{
		mConsole.print("Usage : read <id> <address> <length=1>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	addr=atoi(argv[2]);
	if(argc>3)
	{
		length=atoi(argv[3]);
	}
	if(length>255)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	uint8_t *ptr=new uint8_t[length];
	DynamixelStatus result=mInterface.read(id, addr, length, ptr);
	printData(ptr,length);
	delete ptr;
	return result;
}

DynamixelStatus DynamixelConsole::write(int argc, char **argv)
{
	int id=0, addr=0, length=0;
	if(argc<4)
	{
		mConsole.print("Usage : write <id> <address> <data_1> ... <data_N>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	addr=atoi(argv[2]);
	length=argc-3;
	if(length>255)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}

	uint8_t *ptr=new uint8_t[length];
	for(uint8_t i=0; i<length; ++i)
	{
		ptr[i]=atoi(argv[i+3]);
	}
	DynamixelStatus result=mInterface.write(id, addr, length, ptr);
	delete ptr;
	return result;
}

DynamixelStatus DynamixelConsole::reset(int argc, char **argv)
{
	int id=0;
	if(argc<2)
	{
		mConsole.print("Usage : reset <id>\n\r");
		return DYN_STATUS_INTERNAL_ERROR;
	}
	id=atoi(argv[1]);
	if(id>254)
	{
		return DYN_STATUS_INTERNAL_ERROR;
	}
	DynamixelStatus result=mInterface.reset(id);
	return result;
}

<|endoftext|>


<commit_before>
#include <iostream>
#include <cmath>

#include "timer.h"
#include "matrix.h"

#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif

#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif

template <typename TMatrixType1, typename TMatrixType2>
bool CheckEqual(TMatrixType1 const& Matrix1, TMatrixType2 const& Matrix2) {
    for (int i = 0; i < Matrix1.size1(); i++)
        for (int j = 0; j < Matrix1.size2(); j++)
            if (Matrix1(i, j) != Matrix2(i, j))
                return false;

    return true;
}

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
    TMatrixType mA;
    TMatrixType mB;
    TMatrixType mC;

    void initialize(TMatrixType& TheMatrix, double Value) {
        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = Value;
    }

    void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
        AMatrix::Matrix<double, 3, 3> block;

        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                block(i, j) = 0.00;

        block(0, 0) = std::cos(AngleInRadian);
        block(0, 1) = -std::sin(AngleInRadian);
        block(1, 0) = std::sin(AngleInRadian);
        block(1, 1) = std::cos(AngleInRadian);
        block(2, 2) = 1.00;

        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++) {
                auto block_i = i % 3;
                auto block_j = j % 3;
                TheMatrix(i, j) = block(block_i, block_j);
            }
    }

   public:
    ComparisonColumn() {
        initialize(mA, 0.00);
        initialize(mB, 0.00);
        initialize(mC, 0.00);
    }

    TMatrixType& GetMatrixC() { return mC; }

    Timer::duration_type MeasureSumTime() {
        int repeat_number = 10000000;
        initialize(mA, 0.01);
        initialize(mB, 0.20);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC = mA + mB;
            mB = mC;
        }

        return timer.elapsed().count();
    }

    Timer::duration_type MeasureMultTime() {
        int repeat_number = 10000000;
        initialize_rotation(mA, -0.0001);
        initialize_rotation(mB, 0.0001);
        TMatrixType D;
        initialize(D, 1.00);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC = D * mA;
            D = mC * mB;
        }

        return timer.elapsed().count();
    }
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    Timer::duration_type MeasureProdTime() {
        int repeat_number = 10000000;
        initialize_rotation(mA, -0.0001);
        initialize_rotation(mB, 0.0001);
        TMatrixType D;
        initialize(D, 1.00);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC = boost::numeric::ublas::prod(D, mA);
            D = boost::numeric::ublas::prod(mC, mB);
        }

        return timer.elapsed().count();
    }
#endif
};

void CompareSumTime() {
    ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
    std::cout << "C = A + B\t\t" << a_matrix_column.MeasureSumTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
    std::cout << "\t\t" << eigen_column.MeasureSumTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
        std::cout << "(Failed!)";

#endif
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
        ublas_column;
    std::cout << "\t\t" << ublas_column.MeasureSumTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
        std::cout << "(Failed!)";

#endif
    std::cout << std::endl;
}

void CompareMultTime() {
    ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
    std::cout << "C = A * B\t\t" << a_matrix_column.MeasureMultTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
    std::cout << "\t\t" << eigen_column.MeasureMultTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
        std::cout << "(Failed!)";
#endif
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
        ublas_column;
    std::cout << "\t\t" << ublas_column.MeasureProdTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
        std::cout << "(Failed!)";

#endif
    std::cout << std::endl;
    // std::cout << "AMatrix C = " << a_matrix_column.GetMatrixC() << std::endl;
    // std::cout << "Eigen C = " << eigen_column.GetMatrixC() << std::endl;
}

int main() {
    std::cout << "operation\t\tAMatrix\t\tEigen\t\tUblas\t\tAtlas" << std::endl;
    CompareSumTime();
    CompareMultTime();
    return 0;
}
<commit_msg>Correcting macro check errors<commit_after>
#include <iostream>
#include <cmath>

#include "timer.h"
#include "matrix.h"

#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif

#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif

template <typename TMatrixType1, typename TMatrixType2>
bool CheckEqual(TMatrixType1 const& Matrix1, TMatrixType2 const& Matrix2) {
    for (int i = 0; i < Matrix1.size1(); i++)
        for (int j = 0; j < Matrix1.size2(); j++)
            if (Matrix1(i, j) != Matrix2(i, j))
                return false;

    return true;
}

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
    TMatrixType mA;
    TMatrixType mB;
    TMatrixType mC;

    void initialize(TMatrixType& TheMatrix, double Value) {
        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = Value;
    }

    void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
        AMatrix::Matrix<double, 3, 3> block;

        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                block(i, j) = 0.00;

        block(0, 0) = std::cos(AngleInRadian);
        block(0, 1) = -std::sin(AngleInRadian);
        block(1, 0) = std::sin(AngleInRadian);
        block(1, 1) = std::cos(AngleInRadian);
        block(2, 2) = 1.00;

        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++) {
                auto block_i = i % 3;
                auto block_j = j % 3;
                TheMatrix(i, j) = block(block_i, block_j);
            }
    }

   public:
    ComparisonColumn() {
        initialize(mA, 0.00);
        initialize(mB, 0.00);
        initialize(mC, 0.00);
    }

    TMatrixType& GetMatrixC() { return mC; }

    Timer::duration_type MeasureSumTime() {
        int repeat_number = 10000000;
        initialize(mA, 0.01);
        initialize(mB, 0.20);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC = mA + mB;
            mB = mC;
        }

        return timer.elapsed().count();
    }

    Timer::duration_type MeasureMultTime() {
        int repeat_number = 10000000;
        initialize_rotation(mA, -0.0001);
        initialize_rotation(mB, 0.0001);
        TMatrixType D;
        initialize(D, 1.00);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC = D * mA;
            D = mC * mB;
        }

        return timer.elapsed().count();
    }
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
    Timer::duration_type MeasureProdTime() {
        int repeat_number = 10000000;
        initialize_rotation(mA, -0.0001);
        initialize_rotation(mB, 0.0001);
        TMatrixType D;
        initialize(D, 1.00);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC = boost::numeric::ublas::prod(D, mA);
            D = boost::numeric::ublas::prod(mC, mB);
        }

        return timer.elapsed().count();
    }
#endif
};

void CompareSumTime() {
    ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
    std::cout << "C = A + B\t\t" << a_matrix_column.MeasureSumTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
    std::cout << "\t\t" << eigen_column.MeasureSumTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
        std::cout << "(Failed!)";

#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
    ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
        ublas_column;
    std::cout << "\t\t" << ublas_column.MeasureSumTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
        std::cout << "(Failed!)";

#endif
    std::cout << std::endl;
}

void CompareMultTime() {
    ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
    std::cout << "C = A * B\t\t" << a_matrix_column.MeasureMultTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
    std::cout << "\t\t" << eigen_column.MeasureMultTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
        std::cout << "(Failed!)";
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
    ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
        ublas_column;
    std::cout << "\t\t" << ublas_column.MeasureProdTime();
    if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
        std::cout << "(Failed!)";

#endif
    std::cout << std::endl;
    // std::cout << "AMatrix C = " << a_matrix_column.GetMatrixC() << std::endl;
    // std::cout << "Eigen C = " << eigen_column.GetMatrixC() << std::endl;
}

int main() {
    std::cout << "operation\t\tAMatrix\t\tEigen\t\tUblas\t\tAtlas" << std::endl;
    CompareSumTime();
    CompareMultTime();
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>

#include "timer.h"
#include "matrix.h"

#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif

#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif

template <typename TMatrixType1, typename TMatrixType2>
bool CheckEqual(TMatrixType1 const& Matrix1, TMatrixType2 const& Matrix2) {
    for (int i = 0; i < Matrix1.size1(); i++)
        for (int j = 0; j < Matrix1.size2(); j++)
            if (Matrix1(i, j) != Matrix2(i, j))
                return false;

    return true;
}

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
    std::string mColumnName;

   protected:
    TMatrixType mA;
    TMatrixType mB;
    TMatrixType mC;

    void initialize(TMatrixType& TheMatrix, double Value) {
        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = Value;
    }

    void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
        AMatrix::Matrix<double, 3, 3> block;

        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                block(i, j) = 0.00;

        block(0, 0) = std::cos(AngleInRadian);
        block(0, 1) = -std::sin(AngleInRadian);
        block(1, 0) = std::sin(AngleInRadian);
        block(1, 1) = std::cos(AngleInRadian);
        block(2, 2) = 1.00;

        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++) {
                auto block_i = i % 3;
                auto block_j = j % 3;
                TheMatrix(i, j) = block(block_i, block_j);
            }
    }

   public:
    ComparisonColumn() = delete;

    ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
        initialize(mA, 0.00);
        initialize(mB, 0.00);
        initialize(mC, 0.00);
    }
    std::string const& GetColumnName() { return mColumnName; }
    TMatrixType& GetMatrixC() { return mC; }

    void MeasureSumTime() {
        int repeat_number = 10000000;
        initialize(mA, 0.01);
        initialize(mB, 0.20);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC.noalias() = mA + mB;
            mB.noalias() = mC;
        }
        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

    void MeasureMultTime() {
        int repeat_number = 10000000;
        initialize_rotation(mA, -0.0001);
        initialize_rotation(mB, 0.0001);
        TMatrixType D;
        initialize(D, 1.00);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mC.noalias() = mA * TMatrixType(D * mA);
            D.noalias() = mB * TMatrixType(mC * mB);
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

#if defined(AMATRIX_COMPARE_WITH_UBLAS)

#endif
};

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class UblasComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    using BsaeType =
        ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;

    UblasComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
              ColumnName) {}

    void MeasureSumTime() {
        int repeat_number = 10000000;
        BsaeType::initialize(BsaeType::mA, 0.01);
        BsaeType::initialize(BsaeType::mB, 0.20);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            boost::numeric::ublas::noalias(BsaeType::mC) =
                BsaeType::mA + BsaeType::mB;
            boost::numeric::ublas::noalias(BsaeType::mB) = BsaeType::mC;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
    void MeasureMultTime() {
        using namespace boost::numeric::ublas;
        int repeat_number = 10000000;
        BsaeType::initialize_rotation(BsaeType::mA, -0.0001);
        BsaeType::initialize_rotation(BsaeType::mB, 0.0001);
        TMatrixType D;
        BsaeType::initialize(D, 1.00);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            noalias(BsaeType::mC) = prod(BsaeType::mA, TMatrixType(prod(D, BsaeType::mA)));
            noalias(D) = prod(BsaeType::mB, TMatrixType(prod(BsaeType::mC, BsaeType::mB)));
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
};

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class EmptyComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    EmptyComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
    void MeasureSumTime() {}
    void MeasureMultTime() {}
};

template <int NumberOfRows, int NumberOfColumns>
class BenchmarkMatrix {
    ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mEigenColumn;
#elif
    EmptyComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
    UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
                              NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mUblasColumn;
#elif
    EmptyComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
                              NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mUblasColumn;
#endif
   public:
    BenchmarkMatrix()
        : mAMatrixColumn("AMatrix"),
          mEigenColumn("Eigen"),
          mUblasColumn("Ublas") {
        std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
                  << "]";
        std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
        std::cout << "\t\t" << mEigenColumn.GetColumnName();
        std::cout << "\t\t" << mUblasColumn.GetColumnName();
        std::cout << std::endl;
    }

    void Run() {
        std::cout << "C = A + B";
        mAMatrixColumn.MeasureSumTime();
        mEigenColumn.MeasureSumTime();
        mUblasColumn.MeasureSumTime();
        std::cout << std::endl;

        std::cout << "C = A * B";
        mAMatrixColumn.MeasureMultTime();
        mEigenColumn.MeasureMultTime();
        mUblasColumn.MeasureMultTime();
        std::cout << std::endl;

        std::cout << std::endl;
    }
};

int main() {
    BenchmarkMatrix<3, 3> benchmark_3_3;
    benchmark_3_3.Run();

    BenchmarkMatrix<4, 4> benchmark_4_4;
    benchmark_4_4.Run();

    BenchmarkMatrix<6, 6> benchmark_6_6;
    benchmark_6_6.Run();

    return 0;
}
<commit_msg>Fixing mulitiplication benchmarks<commit_after>#include <iostream>
#include <cmath>

#include "timer.h"
#include "matrix.h"

#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif

#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
    std::string mColumnName;

   protected:
    TMatrixType mA;
    TMatrixType mB;
    TMatrixType mResult;

    void initialize(TMatrixType& TheMatrix) {
        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = j + 1;
    }

    void initializeInverse(TMatrixType& TheMatrix) {
        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = 1.00 / (i + 1);
    }

    void initialize(TMatrixType& TheMatrix, double Value) {
        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = Value;
    }

    void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
        AMatrix::Matrix<double, 3, 3> block;

        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                block(i, j) = 0.00;

        block(0, 0) = std::cos(AngleInRadian);
        block(0, 1) = -std::sin(AngleInRadian);
        block(1, 0) = std::sin(AngleInRadian);
        block(1, 1) = std::cos(AngleInRadian);
        block(2, 2) = 1.00;

        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++) {
                auto block_i = i % 3;
                auto block_j = j % 3;
                TheMatrix(i, j) = block(block_i, block_j);
            }
    }

   public:
    ComparisonColumn() = delete;

    ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
        initialize(mA, 0.00);
        initialize(mB, 0.00);
        initialize(mResult, 0.00);
    }
    std::string const& GetColumnName() { return mColumnName; }
    TMatrixType& GetResult() { return mResult; }

    template <typename TMatrixType2>
    bool CheckResult(TMatrixType2 const& Reference) {
        for (int i = 0; i < NumberOfRows; i++)
            for (int j = 0; j < NumberOfColumns; j++)
                if (mResult(i, j) != Reference(i, j))
                    return false;

        return true;
    }

    void MeasureSumTime() {
        int repeat_number = 10000000;
        initialize(mA, 0.01);
        initialize(mB, 0.20);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mResult.noalias() = mA + mB;
            mB.noalias() = mResult;
        }
        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

    void MeasureMultTime() {
        int repeat_number = 10000000;
        initialize(mA);
        initializeInverse(mB);
        TMatrixType D;
        initializeInverse(D);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mResult.noalias() = D * mA;
            D.noalias() = mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

    void MeasureABAMultTime() {
        int repeat_number = 10000000;
        initialize(mA);
        initializeInverse(mB);
        TMatrixType D;
        initializeInverse(D);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            mResult.noalias() = mA * TMatrixType(D * mA);
            D.noalias() = mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

#if defined(AMATRIX_COMPARE_WITH_UBLAS)

#endif
};

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class UblasComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    using BaseType =
        ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;

    UblasComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
              ColumnName) {}

    void MeasureSumTime() {
        int repeat_number = 10000000;
        BaseType::initialize(BaseType::mA, 0.01);
        BaseType::initialize(BaseType::mB, 0.20);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            boost::numeric::ublas::noalias(BaseType::mResult) =
                BaseType::mA + BaseType::mB;
            boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
    void MeasureMultTime() {
        using namespace boost::numeric::ublas;
        int repeat_number = 10000000;
        BaseType::initialize(BaseType::mA);
        BaseType::initializeInverse(BaseType::mB);
        TMatrixType D;
        BaseType::initializeInverse(D);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            noalias(BaseType::mResult) = prod(D, BaseType::mA);
            noalias(D) = BaseType::mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
    void MeasureABAMultTime() {
        using namespace boost::numeric::ublas;
        int repeat_number = 10000000;
        BaseType::initialize(BaseType::mA);
        BaseType::initializeInverse(BaseType::mB);
        TMatrixType D;
        BaseType::initializeInverse(D);
        Timer timer;
        for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
            noalias(BaseType::mResult) =
                prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
            noalias(D) = BaseType::mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
};

template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class EmptyComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    EmptyComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
    void MeasureSumTime() {}
    void MeasureABAMultTime() {}

    template <typename TMatrixType2>
    bool CheckResult(TMatrixType2 const& Reference) {
        return true;
    }
};

template <int NumberOfRows, int NumberOfColumns>
class BenchmarkMatrix {
    ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mEigenColumn;
#elif
    EmptyComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
    UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
                              NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mUblasColumn;
#elif
    EmptyComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
                              NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mUblasColumn;
#endif
   public:
    BenchmarkMatrix()
        : mAMatrixColumn("AMatrix"),
          mEigenColumn("Eigen"),
          mUblasColumn("Ublas") {
        std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
                  << "]";
        std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
        std::cout << "\t\t" << mEigenColumn.GetColumnName();
        std::cout << "\t\t" << mUblasColumn.GetColumnName();
        std::cout << std::endl;
    }

    void Run() {
        std::cout << "C = A + B";
        mAMatrixColumn.MeasureSumTime();
        mEigenColumn.MeasureSumTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureSumTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        std::cout << "C = A * B";
        mAMatrixColumn.MeasureMultTime();
        mEigenColumn.MeasureMultTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureMultTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        std::cout << "C = A * B * A";
        mAMatrixColumn.MeasureABAMultTime();
        mEigenColumn.MeasureABAMultTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureABAMultTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        // std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
        // std::cout << "Eigen   : " << mEigenColumn.GetResult() << std::endl;

        std::cout << std::endl;
    }
};

int main() {
    BenchmarkMatrix<3, 3> benchmark_3_3;
    benchmark_3_3.Run();

    BenchmarkMatrix<4, 4> benchmark_4_4;
    benchmark_4_4.Run();

    BenchmarkMatrix<6, 6> benchmark_6_6;
    benchmark_6_6.Run();

    BenchmarkMatrix<12, 12> benchmark_12_12;
    benchmark_12_12.Run();

    BenchmarkMatrix<16, 16> benchmark_16_16;
    benchmark_16_16.Run();

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>

#include "timer.h"
#include "matrix.h"

#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif

#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif

template <typename TMatrixType, std::size_t NumberOfRows,
    std::size_t NumberOfColumns>
class ComparisonColumn {
   protected:
    static constexpr std::size_t mRepeat =
        static_cast<std::size_t>(1e8 / (NumberOfRows * NumberOfColumns));
    TMatrixType mA;
    TMatrixType mB;
    TMatrixType mResult;
    std::string mColumnName;

    void initialize(TMatrixType& TheMatrix) {
        for (std::size_t i = 0; i < NumberOfRows; i++)
            for (std::size_t j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = j + 1.00;
    }

    void initializeInverse(TMatrixType& TheMatrix) {
        for (std::size_t i = 0; i < NumberOfRows; i++)
            for (std::size_t j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = 1.00 / (i + 1);
    }

   public:
    ComparisonColumn() = delete;

    ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
        initialize(mA);
        initialize(mB);
        initialize(mResult);
    }
    std::string const& GetColumnName() { return mColumnName; }
    TMatrixType& GetResult() { return mResult; }

    template <typename TMatrixType2>
    bool CheckResult(TMatrixType2 const& Reference) {
        for (std::size_t i = 0; i < NumberOfRows; i++)
            for (std::size_t j = 0; j < NumberOfColumns; j++)
                if (mResult(i, j) != Reference(i, j))
                    return false;

        return true;
    }

    void MeasureSumTime() {
        initialize(mA);
        initialize(mB);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
            mResult.noalias() = mA + mB;
            mB.noalias() = mResult;
        }
        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

    void MeasureMultTime() {
        initialize(mA);
        initializeInverse(mB);
        TMatrixType D;
        initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
            mResult.noalias() = D * mA;
            D.noalias() = mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

    void MeasureABAMultTime() {
        initialize(mA);
        initializeInverse(mB);
        TMatrixType D;
        initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
            mResult.noalias() = mA * TMatrixType(D * mA);
            D.noalias() = mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
};

template <typename TMatrixType, std::size_t NumberOfRows,
    std::size_t NumberOfColumns>
class UblasComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    using BaseType =
        ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;

    UblasComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
              ColumnName) {}

    void MeasureSumTime() {
        BaseType::initialize(BaseType::mA);
        BaseType::initialize(BaseType::mB);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
             i_repeat++) {
            boost::numeric::ublas::noalias(BaseType::mResult) =
                BaseType::mA + BaseType::mB;
            boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
    void MeasureMultTime() {
        using namespace boost::numeric::ublas;
        BaseType::initialize(BaseType::mA);
        BaseType::initializeInverse(BaseType::mB);
        TMatrixType D;
        BaseType::initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
             i_repeat++) {
            noalias(BaseType::mResult) = prod(D, BaseType::mA);
            noalias(D) = BaseType::mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
    void MeasureABAMultTime() {
        using namespace boost::numeric::ublas;
        BaseType::initialize(BaseType::mA);
        BaseType::initializeInverse(BaseType::mB);
        TMatrixType D;
        BaseType::initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
             i_repeat++) {
            noalias(BaseType::mResult) =
                prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
            noalias(D) = BaseType::mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
};

template <typename TMatrixType, std::size_t NumberOfRows,
    std::size_t NumberOfColumns>
class EmptyComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    EmptyComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
    void MeasureSumTime() { std::cout << "\t\t"; }
    void MeasureMultTime() { std::cout << "\t\t"; }
    void MeasureABAMultTime() { std::cout << "\t\t"; }

    template <typename TMatrixType2>
    bool CheckResult(TMatrixType2 const& Reference) {
        return true;
    }
};

template <std::size_t NumberOfRows, std::size_t NumberOfColumns>
class BenchmarkMatrix {
    ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mEigenColumn;
#else
    EmptyComparisonColumn<
        AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
        NumberOfColumns>
        mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
    UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
                              NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mUblasColumn;
#else
    EmptyComparisonColumn<
        AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
        NumberOfColumns>
        mUblasColumn;
#endif
   public:
    BenchmarkMatrix()
        : mAMatrixColumn("AMatrix"),
          mEigenColumn("Eigen"),
          mUblasColumn("Ublas") {
        std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
                  << "]";
        std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
        std::cout << "\t\t" << mEigenColumn.GetColumnName();
        std::cout << "\t\t" << mUblasColumn.GetColumnName();
        std::cout << std::endl;
    }

    ~BenchmarkMatrix() = default;
    void Run() {
        std::cout << "C = A + B";
        mAMatrixColumn.MeasureSumTime();
        mEigenColumn.MeasureSumTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureSumTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        std::cout << "C = A * B";
        mAMatrixColumn.MeasureMultTime();
        mEigenColumn.MeasureMultTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureMultTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        std::cout << "C = A * B * A";
        mAMatrixColumn.MeasureABAMultTime();
        mEigenColumn.MeasureABAMultTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureABAMultTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        // std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
        // std::cout << "Eigen   : " << mEigenColumn.GetResult() << std::endl;

        std::cout << std::endl;
    }
};

int main() {
    BenchmarkMatrix<3, 3> benchmark_3_3;
    benchmark_3_3.Run();

    BenchmarkMatrix<4, 4> benchmark_4_4;
    benchmark_4_4.Run();

    BenchmarkMatrix<6, 6> benchmark_6_6;
    benchmark_6_6.Run();

    BenchmarkMatrix<12, 12> benchmark_12_12;
    benchmark_12_12.Run();

    BenchmarkMatrix<16, 16> benchmark_16_16;
    benchmark_16_16.Run();

    return 0;
}
<commit_msg>Adding A^T * B * A benchmarks<commit_after>#include <iostream>
#include <cmath>

#include "timer.h"
#include "matrix.h"

#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif

#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif

template <typename TMatrixType, std::size_t NumberOfRows,
    std::size_t NumberOfColumns>
class ComparisonColumn {
   protected:
    static constexpr std::size_t mRepeat =
        static_cast<std::size_t>(1e8 / (NumberOfRows * NumberOfColumns));
    TMatrixType mA;
    TMatrixType mB;
    TMatrixType mResult;
    std::string mColumnName;

    void initialize(TMatrixType& TheMatrix) {
        for (std::size_t i = 0; i < NumberOfRows; i++)
            for (std::size_t j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = j + 1.00;
    }

    void initializeInverse(TMatrixType& TheMatrix) {
        for (std::size_t i = 0; i < NumberOfRows; i++)
            for (std::size_t j = 0; j < NumberOfColumns; j++)
                TheMatrix(i, j) = 1.00 / (i + 1);
    }

   public:
    ComparisonColumn() = delete;

    ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
        initialize(mA);
        initialize(mB);
        initialize(mResult);
    }
    std::string const& GetColumnName() { return mColumnName; }
    TMatrixType& GetResult() { return mResult; }

    template <typename TMatrixType2>
    bool CheckResult(TMatrixType2 const& Reference) {
        for (std::size_t i = 0; i < NumberOfRows; i++)
            for (std::size_t j = 0; j < NumberOfColumns; j++)
                if (mResult(i, j) != Reference(i, j))
                    return false;

        return true;
    }

    void MeasureSumTime() {
        initialize(mA);
        initialize(mB);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
            mResult.noalias() = mA + mB;
            mB.noalias() = mResult;
        }
        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

    void MeasureMultTime() {
        initialize(mA);
        initializeInverse(mB);
        TMatrixType D;
        initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
            mResult.noalias() = D * mA;
            D.noalias() = mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
   void MeasureABAMultTime() {
        initialize(mA);
        initializeInverse(mB);
        TMatrixType D;
        initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
            mResult.noalias() = mA * TMatrixType(D * mA);
            D.noalias() = mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }

    void MeasureATransposeBAMultTime() {
        initialize(mA);
        initializeInverse(mB);
        TMatrixType D;
        initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
            mResult.noalias() = mA.transpose() * TMatrixType(D * mA);
            D.noalias() = mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
};

template <typename TMatrixType, std::size_t NumberOfRows,
    std::size_t NumberOfColumns>
class UblasComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    using BaseType =
        ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;

    UblasComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
              ColumnName) {}

    void MeasureSumTime() {
        BaseType::initialize(BaseType::mA);
        BaseType::initialize(BaseType::mB);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
             i_repeat++) {
            boost::numeric::ublas::noalias(BaseType::mResult) =
                BaseType::mA + BaseType::mB;
            boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
    void MeasureMultTime() {
        using namespace boost::numeric::ublas;
        BaseType::initialize(BaseType::mA);
        BaseType::initializeInverse(BaseType::mB);
        TMatrixType D;
        BaseType::initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
             i_repeat++) {
            noalias(BaseType::mResult) = prod(D, BaseType::mA);
            noalias(D) = BaseType::mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
    void MeasureABAMultTime() {
        using namespace boost::numeric::ublas;
        BaseType::initialize(BaseType::mA);
        BaseType::initializeInverse(BaseType::mB);
        TMatrixType D;
        BaseType::initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
             i_repeat++) {
            noalias(BaseType::mResult) =
                prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
            noalias(D) = BaseType::mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
   void MeasureATransposeBAMultTime() {
        using namespace boost::numeric::ublas;
        BaseType::initialize(BaseType::mA);
        BaseType::initializeInverse(BaseType::mB);
        TMatrixType D;
        BaseType::initializeInverse(D);
        Timer timer;
        for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
             i_repeat++) {
            noalias(BaseType::mResult) =
                prod(trans(BaseType::mA), TMatrixType(prod(D, BaseType::mA)));
            noalias(D) = BaseType::mB;
        }

        auto elapsed = timer.elapsed().count();
        std::cout << "\t\t" << elapsed;
    }
};

template <typename TMatrixType, std::size_t NumberOfRows,
    std::size_t NumberOfColumns>
class EmptyComparisonColumn
    : public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
   public:
    EmptyComparisonColumn(std::string ColumnName)
        : ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
    void MeasureSumTime() { std::cout << "\t\t"; }
    void MeasureMultTime() { std::cout << "\t\t"; }
    void MeasureABAMultTime() { std::cout << "\t\t"; }
    void MeasureATransposeBAMultTime() { std::cout << "\t\t"; }

    template <typename TMatrixType2>
    bool CheckResult(TMatrixType2 const& Reference) {
        return true;
    }
};

template <std::size_t NumberOfRows, std::size_t NumberOfColumns>
class BenchmarkMatrix {
    ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
    ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mEigenColumn;
#else
    EmptyComparisonColumn<
        AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
        NumberOfColumns>
        mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
    UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
                              NumberOfRows, NumberOfColumns>,
        NumberOfRows, NumberOfColumns>
        mUblasColumn;
#else
    EmptyComparisonColumn<
        AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
        NumberOfColumns>
        mUblasColumn;
#endif
   public:
    BenchmarkMatrix()
        : mAMatrixColumn("AMatrix"),
          mEigenColumn("Eigen"),
          mUblasColumn("Ublas") {
        std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
                  << "]";
        std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
        std::cout << "\t\t" << mEigenColumn.GetColumnName();
        std::cout << "\t\t" << mUblasColumn.GetColumnName();
        std::cout << std::endl;
    }

    ~BenchmarkMatrix() = default;
    void Run() {
        std::cout << "C = A + B";
        mAMatrixColumn.MeasureSumTime();
        mEigenColumn.MeasureSumTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureSumTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        std::cout << "C = A * B";
        mAMatrixColumn.MeasureMultTime();
        mEigenColumn.MeasureMultTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureMultTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        std::cout << "C = A * B * A";
        mAMatrixColumn.MeasureABAMultTime();
        mEigenColumn.MeasureABAMultTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureABAMultTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        std::cout << "C = A^T * B * A";
        mAMatrixColumn.MeasureATransposeBAMultTime();
        mEigenColumn.MeasureATransposeBAMultTime();
        if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        mUblasColumn.MeasureATransposeBAMultTime();
        if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
            std::cout << "(Failed!)";
        std::cout << std::endl;

        // std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
        // std::cout << "Eigen   : " << mEigenColumn.GetResult() << std::endl;

        std::cout << std::endl;
    }
};

int main() {
    BenchmarkMatrix<3, 3> benchmark_3_3;
    benchmark_3_3.Run();

    BenchmarkMatrix<4, 4> benchmark_4_4;
    benchmark_4_4.Run();

    BenchmarkMatrix<6, 6> benchmark_6_6;
    benchmark_6_6.Run();

    BenchmarkMatrix<12, 12> benchmark_12_12;
    benchmark_12_12.Run();

    BenchmarkMatrix<16, 16> benchmark_16_16;
    benchmark_16_16.Run();

    return 0;
}
<|endoftext|>


<commit_before>#include <stdexcept>
#include "FractalGenerator.h"
#include "math_utils.h"

/*
 * Public member functions
 */

FractalGenerator::FractalGenerator(fractalId id, v8::Isolate *isolate,
		void (*doneCallback)(v8::Isolate *isolate,
				v8::Local<v8::Object> nodeBuffer, bool halted,
				void *doneCallbackData), v8::Local<v8::Object> buf,
		void *doneCallbackData, int width, int height, double fractalWidth,
		double fractalHeight, double fracgtalX, double fractalY, int iterations) :
		id(id), doneCallback(doneCallback), doneCallbackData(doneCallbackData), width(
				width), height(height), fractalWidth(fractalWidth), fractalHeight(
				fractalHeight), fractalX(fractalX), fractalY(fractalY), iterations(
				iterations) {
	if (node::Buffer::Length(buf) < (width * height * 4)) {
		throw new std::invalid_argument(
				"node::Buffer::Length(buf) < (width * height * 4)");
	}

	nodeBuffer = new v8::Global<v8::Object>;
	nodeBuffer->Reset(isolate, buf);
	buffer = node::Buffer::Data(buf);

	doneAsync = new uv_async_t;
	// TODO switch to std::bind because c++ 11
	doneAsync->data = this;
	uv_loop_t *loop = uv_default_loop();
	uv_async_init(loop, doneAsync, doneAsyncCallback);
}

FractalGenerator::~FractalGenerator() {
	nodeBuffer->Reset();
	delete nodeBuffer;
	delete doneAsync;
}

void FractalGenerator::start() {
	thread = new std::thread(&FractalGenerator::threadFunction, this);
}

void FractalGenerator::halt() {
	halting.store(true);
}

int FractalGenerator::getProgress() {
	return progress.load();
}

bool FractalGenerator::isGenerating() {
	return generating.load();
}

/*
 * Private member functions
 */

void FractalGenerator::doneAsyncCallback(uv_async_t *handle) {
	// TODO switch to std::bind because c++ 11
	FractalGenerator *self = ((FractalGenerator *) handle->data);
	v8::Isolate *isolate = v8::Isolate::GetCurrent();
	v8::HandleScope scope(isolate);
	(*self->doneCallback)(isolate, self->nodeBuffer->Get(isolate),
			self->halting.load(), self->doneCallbackData);
	self->nodeBuffer->Reset();
}

void FractalGenerator::threadFunction() {
	// build fractal here and call uv_async_send when done

	generating.store(true);
	progress.store(0);

	// does this make things faster or is this redundant with g++ optimization?
	float fx, fy, a, b, aa, bb, twoab;
	int x, y, i, n;
	RGBData color;

	for (y = 0; y < height; y++) {
		for (x = 0; x < width; x++) {
			if (halting.load()) {
				generating.store(false);
				uv_async_send(doneAsync);
				return;
			}

			// get buffer index
			i = x + y * width;

			// pixel value generation
			fx = x * fractalWidth / width + fractalX;
			fy = y * fractalHeight / height + fractalY;

			// z = (a + bi)
			a = fx;
			b = fy;

			for (n = 0; n < iterations; n++) {
				// z = z * z
				aa = a * a;
				bb = b * b;
				twoab = 2.0f * a * b;

				a = aa - bb + fx;
				b = twoab + fy;

				// if old sqrt(a * a + b * b) > 4
				// z is outside a circle with radius 4 in the complex plane
				if (aa + bb > 16) {
					break;
				}
			}

			// pixel coloring
			if (n < iterations) {
				// magic numbers
				color = fromHSB(mod2(n * 3.3f, 0, 256.0f) / 256.0f, 1.0f,
						mod2(n * 16.0f, 0, 256.0f) / 256.0f);
				buffer[i] = color.r;
				buffer[i + 1] = color.g;
				buffer[i + 2] = color.b;
				buffer[i + 3] = 0xFF;
			} else {
				buffer[i] = 0x00;
				buffer[i + 1] = 0x00;
				buffer[i + 2] = 0x00;
				buffer[i + 3] = 0xFF;
			}

			progress++;
		}
	}

	// set status
	generating.store(false);

	// send callback
	uv_async_send(doneAsync);
}
<commit_msg>std::bind doesn't work with c function pointers<commit_after>#include <stdexcept>
#include "FractalGenerator.h"
#include "math_utils.h"

/*
 * Public member functions
 */

FractalGenerator::FractalGenerator(fractalId id, v8::Isolate *isolate,
		void (*doneCallback)(v8::Isolate *isolate,
				v8::Local<v8::Object> nodeBuffer, bool halted,
				void *doneCallbackData), v8::Local<v8::Object> buf,
		void *doneCallbackData, int width, int height, double fractalWidth,
		double fractalHeight, double fracgtalX, double fractalY, int iterations) :
		id(id), doneCallback(doneCallback), doneCallbackData(doneCallbackData), width(
				width), height(height), fractalWidth(fractalWidth), fractalHeight(
				fractalHeight), fractalX(fractalX), fractalY(fractalY), iterations(
				iterations) {
	if (node::Buffer::Length(buf) < (width * height * 4)) {
		throw new std::invalid_argument(
				"node::Buffer::Length(buf) < (width * height * 4)");
	}

	nodeBuffer = new v8::Global<v8::Object>;
	nodeBuffer->Reset(isolate, buf);
	buffer = node::Buffer::Data(buf);

	doneAsync = new uv_async_t;
	doneAsync->data = this;
	uv_loop_t *loop = uv_default_loop();
	uv_async_init(loop, doneAsync, doneAsyncCallback);
}

FractalGenerator::~FractalGenerator() {
	nodeBuffer->Reset();
	delete nodeBuffer;
	delete doneAsync;
}

void FractalGenerator::start() {
	thread = new std::thread(&FractalGenerator::threadFunction, this);
}

void FractalGenerator::halt() {
	halting.store(true);
}

int FractalGenerator::getProgress() {
	return progress.load();
}

bool FractalGenerator::isGenerating() {
	return generating.load();
}

/*
 * Private member functions
 */

void FractalGenerator::doneAsyncCallback(uv_async_t *handle) {
	FractalGenerator *self = ((FractalGenerator *) handle->data);
	v8::Isolate *isolate = v8::Isolate::GetCurrent();
	v8::HandleScope scope(isolate);
	(*self->doneCallback)(isolate, self->nodeBuffer->Get(isolate),
			self->halting.load(), self->doneCallbackData);
	self->nodeBuffer->Reset();
}

void FractalGenerator::threadFunction() {
	// build fractal here and call uv_async_send when done

	generating.store(true);
	progress.store(0);

	// does this make things faster or is this redundant with g++ optimization?
	float fx, fy, a, b, aa, bb, twoab;
	int x, y, i, n;
	RGBData color;

	for (y = 0; y < height; y++) {
		for (x = 0; x < width; x++) {
			if (halting.load()) {
				generating.store(false);
				uv_async_send(doneAsync);
				return;
			}

			// get buffer index
			i = x + y * width;

			// pixel value generation
			fx = x * fractalWidth / width + fractalX;
			fy = y * fractalHeight / height + fractalY;

			// z = (a + bi)
			a = fx;
			b = fy;

			for (n = 0; n < iterations; n++) {
				// z = z * z
				aa = a * a;
				bb = b * b;
				twoab = 2.0f * a * b;

				a = aa - bb + fx;
				b = twoab + fy;

				// if old sqrt(a * a + b * b) > 4
				// z is outside a circle with radius 4 in the complex plane
				if (aa + bb > 16) {
					break;
				}
			}

			// pixel coloring
			if (n < iterations) {
				// magic numbers
				color = fromHSB(mod2(n * 3.3f, 0, 256.0f) / 256.0f, 1.0f,
						mod2(n * 16.0f, 0, 256.0f) / 256.0f);
				buffer[i] = color.r;
				buffer[i + 1] = color.g;
				buffer[i + 2] = color.b;
				buffer[i + 3] = 0xFF;
			} else {
				buffer[i] = 0x00;
				buffer[i + 1] = 0x00;
				buffer[i + 2] = 0x00;
				buffer[i + 3] = 0xFF;
			}

			progress++;
		}
	}

	// set status
	generating.store(false);

	// send callback
	uv_async_send(doneAsync);
}
<|endoftext|>


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

#include "chrome/browser/host_zoom_map.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"

HostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {
  const DictionaryValue* host_zoom_dictionary =
      profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);
  // Careful: The returned value could be NULL if the pref has never been set.
  if (host_zoom_dictionary != NULL) {
    for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());
         i != host_zoom_dictionary->end_keys(); ++i) {
      std::wstring wide_host(*i);
      int zoom_level = 0;
      bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(
          wide_host, &zoom_level);
      DCHECK(success);
      host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;
    }
  }
}

// static
void HostZoomMap::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);
}

int HostZoomMap::GetZoomLevel(const std::string& host) const {
  AutoLock auto_lock(lock_);
  HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));
  return (i == host_zoom_levels_.end()) ? 0 : i->second;
}

void HostZoomMap::SetZoomLevel(const std::string& host, int level) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  if (host.empty())
    return;

  {
    AutoLock auto_lock(lock_);
    if (level == 0)
      host_zoom_levels_.erase(host);
    else
      host_zoom_levels_[host] = level;
  }

  DictionaryValue* host_zoom_dictionary =
      profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);
  std::wstring wide_host(UTF8ToWide(host));
  if (level == 0) {
    host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);
  } else {
    host_zoom_dictionary->SetWithoutPathExpansion(wide_host,
        Value::CreateIntegerValue(level));
  }
}

void HostZoomMap::ResetToDefaults() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  host_zoom_levels_.clear();
  profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);
}

HostZoomMap::~HostZoomMap() {
}
<commit_msg>One more place I forgot to lock.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/host_zoom_map.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"

HostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {
  const DictionaryValue* host_zoom_dictionary =
      profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);
  // Careful: The returned value could be NULL if the pref has never been set.
  if (host_zoom_dictionary != NULL) {
    for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());
         i != host_zoom_dictionary->end_keys(); ++i) {
      std::wstring wide_host(*i);
      int zoom_level = 0;
      bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(
          wide_host, &zoom_level);
      DCHECK(success);
      host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;
    }
  }
}

// static
void HostZoomMap::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);
}

int HostZoomMap::GetZoomLevel(const std::string& host) const {
  AutoLock auto_lock(lock_);
  HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));
  return (i == host_zoom_levels_.end()) ? 0 : i->second;
}

void HostZoomMap::SetZoomLevel(const std::string& host, int level) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  if (host.empty())
    return;

  {
    AutoLock auto_lock(lock_);
    if (level == 0)
      host_zoom_levels_.erase(host);
    else
      host_zoom_levels_[host] = level;
  }

  DictionaryValue* host_zoom_dictionary =
      profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);
  std::wstring wide_host(UTF8ToWide(host));
  if (level == 0) {
    host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);
  } else {
    host_zoom_dictionary->SetWithoutPathExpansion(wide_host,
        Value::CreateIntegerValue(level));
  }
}

void HostZoomMap::ResetToDefaults() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  {
    AutoLock auto_lock(lock_);
    host_zoom_levels_.clear();
  }

  profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);
}

HostZoomMap::~HostZoomMap() {
}
<|endoftext|>