<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Daniel Melanz, Radu Serban
// =============================================================================
//
// Front and Rear HMMWV suspension subsystems (solid axle).
//
// These concrete suspension subsystems are defined with respect to right-handed
// frames with X pointing towards the front, Y to the left, and Z up (as imposed
// by the base class ChSolidAxle) and origins at the midpoint between the wheel
// centers.
//
// All point locations are provided for the left half of the supspension.
//
// =============================================================================

#include "HMMWV_SolidAxle.h"

using namespace chrono;

namespace hmmwv {

// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------

static double scaleCon = 35.815 / 750;

static const double in2m = 0.0254;

const double     HMMWV_SolidAxleFront::m_ULMass = 12.0/2.2;
const double     HMMWV_SolidAxleFront::m_LLMass = 36.0/2.2;
const double     HMMWV_SolidAxleFront::m_knuckleMass = 60.0/2.2;
const double     HMMWV_SolidAxleFront::m_spindleMass = 35.0/2.2;
const double     HMMWV_SolidAxleFront::m_axleTubeMass = 35.0/2.2;

const double     HMMWV_SolidAxleFront::m_spindleRadius = 0.15;
const double     HMMWV_SolidAxleFront::m_spindleWidth = 0.06;
const double     HMMWV_SolidAxleFront::m_ULRadius = 0.02;
const double     HMMWV_SolidAxleFront::m_LLRadius = 0.02;
const double     HMMWV_SolidAxleFront::m_axleTubeRadius = 0.03;
const double     HMMWV_SolidAxleFront::m_knuckleRadius = 0.01;

const ChVector<> HMMWV_SolidAxleFront::m_axleTubeCOM(0, 0, 0);

const ChVector<> HMMWV_SolidAxleFront::m_axleTubeInertia(2, 4, 2);
const ChVector<> HMMWV_SolidAxleFront::m_spindleInertia(2, 4, 2);
const ChVector<> HMMWV_SolidAxleFront::m_ULInertia(2, 2, 2);
const ChVector<> HMMWV_SolidAxleFront::m_LLInertia(3, 3, 3);
const ChVector<> HMMWV_SolidAxleFront::m_knuckleInertia(5, 5, 5);

const double     HMMWV_SolidAxleFront::m_axleInertia = 0.4;

const double     HMMWV_SolidAxleFront::m_springCoefficient  = 267062.0;
const double     HMMWV_SolidAxleFront::m_dampingCoefficient = 22459.0;
const double     HMMWV_SolidAxleFront::m_springRestLength   = in2m * 13.36;

// -----------------------------------------------------------------------------

const double     HMMWV_SolidAxleRear::m_ULMass = 12.0/2.2;
const double     HMMWV_SolidAxleRear::m_LLMass = 36.0/2.2;
const double     HMMWV_SolidAxleRear::m_knuckleMass = 60.0/2.2;
const double     HMMWV_SolidAxleRear::m_spindleMass = 35.0/2.2;
const double     HMMWV_SolidAxleRear::m_axleTubeMass = 35.0/2.2;

const double     HMMWV_SolidAxleRear::m_spindleRadius = 0.15;
const double     HMMWV_SolidAxleRear::m_spindleWidth = 0.06;
const double     HMMWV_SolidAxleRear::m_ULRadius = 0.02;
const double     HMMWV_SolidAxleRear::m_LLRadius = 0.02;
const double     HMMWV_SolidAxleRear::m_axleTubeRadius = 0.03;
const double     HMMWV_SolidAxleRear::m_knuckleRadius = 0.01;

const ChVector<> HMMWV_SolidAxleRear::m_axleTubeCOM(0, 0, 0);

const ChVector<> HMMWV_SolidAxleRear::m_axleTubeInertia(2, 4, 2);
const ChVector<> HMMWV_SolidAxleRear::m_spindleInertia(2, 4, 2);
const ChVector<> HMMWV_SolidAxleRear::m_ULInertia(2, 2, 2);
const ChVector<> HMMWV_SolidAxleRear::m_LLInertia(3, 3, 3);
const ChVector<> HMMWV_SolidAxleRear::m_knuckleInertia(5, 5, 5);

const double     HMMWV_SolidAxleRear::m_axleInertia = 0.4;

const double     HMMWV_SolidAxleRear::m_springCoefficient  = 267062.0;
const double     HMMWV_SolidAxleRear::m_dampingCoefficient = 22459.0;
const double     HMMWV_SolidAxleRear::m_springRestLength   = in2m * 13.36;

// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
HMMWV_SolidAxleFront::HMMWV_SolidAxleFront(const std::string& name,
                                           bool               driven)
: ChSolidAxle(name, driven)
{
}

HMMWV_SolidAxleRear::HMMWV_SolidAxleRear(const std::string& name,
                                         bool               driven)
: ChSolidAxle(name, driven)
{
}

// -----------------------------------------------------------------------------
// Implementations of the getLocation() virtual methods.
// -----------------------------------------------------------------------------

const ChVector<> HMMWV_SolidAxleFront::getLocation(PointId which)
{
  switch (which) {
  case SHOCK_A:    return in2m * scaleCon * ChVector<>(-65, 575, -25);
  case SHOCK_C:    return in2m * scaleCon * ChVector<>(-80, 560, 300);
  case KNUCKLE_L:  return in2m * scaleCon * ChVector<>(5, 700, -50);
  case KNUCKLE_U:  return in2m * scaleCon * ChVector<>(-15, 675, 75);
  case LL_A:       return in2m * scaleCon * ChVector<>(10, 600, -75);
  case LL_C:       return in2m * scaleCon * ChVector<>(450, 350, -45);
  case UL_A:       return in2m * scaleCon * ChVector<>(-55, 475, 150);
  case UL_C:       return in2m * scaleCon * ChVector<>(355, 500, 150);
  case SPRING_A:   return in2m * scaleCon * ChVector<>(-65, 575, -25);
  case SPRING_C:   return in2m * scaleCon * ChVector<>(-80, 560, 300);
  case TIEROD_C:   return in2m * scaleCon * ChVector<>(-75, 325, -65);
  case TIEROD_K:   return in2m * scaleCon * ChVector<>(-75, 680, -65);
  case SPINDLE:    return in2m * scaleCon * ChVector<>(0, 750, 0);
  case KNUCKLE_CM: return in2m * scaleCon * ChVector<>(5, 700, -50);
  case LL_CM:      return in2m * scaleCon * ChVector<>(10, 600, -75);
  case UL_CM:      return in2m * scaleCon * ChVector<>(-55, 475, 150);
  default:         return ChVector<>(0, 0, 0);
  }
}

const ChVector<> HMMWV_SolidAxleRear::getLocation(PointId which)
{
  switch (which) {
  case SHOCK_A:    return in2m * scaleCon * ChVector<>(-65, 575, -25);
  case SHOCK_C:    return in2m * scaleCon * ChVector<>(-80, 560, 300);
  case KNUCKLE_L:  return in2m * scaleCon * ChVector<>(5, 700, -50);
  case KNUCKLE_U:  return in2m * scaleCon * ChVector<>(-15, 675, 75);
  case LL_A:       return in2m * scaleCon * ChVector<>(10, 600, -75);
  case LL_C:       return in2m * scaleCon * ChVector<>(450, 350, -45);
  case UL_A:       return in2m * scaleCon * ChVector<>(-55, 475, 150);
  case UL_C:       return in2m * scaleCon * ChVector<>(355, 500, 150);
  case SPRING_A:   return in2m * scaleCon * ChVector<>(-65, 575, -25);
  case SPRING_C:   return in2m * scaleCon * ChVector<>(-80, 560, 300);
  case TIEROD_C:   return in2m * scaleCon * ChVector<>(-75, 325, -65);
  case TIEROD_K:   return in2m * scaleCon * ChVector<>(-75, 680, -65);
  case SPINDLE:    return in2m * scaleCon * ChVector<>(0, 750, 0);
  case KNUCKLE_CM: return in2m * scaleCon * ChVector<>(5, 700, -50);
  case LL_CM:      return in2m * scaleCon * ChVector<>(10, 600, -75);
  case UL_CM:      return in2m * scaleCon * ChVector<>(-55, 475, 150);
  default:         return ChVector<>(0, 0, 0);
  }
}

// -----------------------------------------------------------------------------
// Implementations of the getDirection() virtual methods.
// -----------------------------------------------------------------------------

const ChVector<> HMMWV_SolidAxleFront::getDirection(DirectionId which)
{
  switch (which) {
  case UNIV_AXIS_LINK_L:      return ChVector<>(1, 0, 0);
  case UNIV_AXIS_CHASSIS_L:   return ChVector<>(0, 1, 0);
  case UNIV_AXIS_LINK_U:      return ChVector<>(1, 0, 0);
  case UNIV_AXIS_CHASSIS_U:   return ChVector<>(0, 1, 0);
  default:                    return ChVector<>(0, 0, 1);
  }
}

const ChVector<> HMMWV_SolidAxleRear::getDirection(DirectionId which)
{
  switch (which) {
  case UNIV_AXIS_LINK_L:      return ChVector<>(1, 0, 0);
  case UNIV_AXIS_CHASSIS_L:   return ChVector<>(0, 1, 0);
  case UNIV_AXIS_LINK_U:      return ChVector<>(1, 0, 0);
  case UNIV_AXIS_CHASSIS_U:   return ChVector<>(0, 1, 0);
  default:                    return ChVector<>(0, 0, 1);
  }
}

} // end namespace hmmwv
<commit_msg>Update HMMWV_SolidAxle to match data in the SolidAxle JSON files.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Daniel Melanz, Radu Serban
// =============================================================================
//
// Front and Rear HMMWV suspension subsystems (solid axle).
//
// These concrete suspension subsystems are defined with respect to right-handed
// frames with X pointing towards the front, Y to the left, and Z up (as imposed
// by the base class ChSolidAxle) and origins at the midpoint between the wheel
// centers.
//
// All point locations are provided for the left half of the supspension.
//
// =============================================================================

#include "HMMWV_SolidAxle.h"

using namespace chrono;

namespace hmmwv {

// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------

const double     HMMWV_SolidAxleFront::m_ULMass = 1.446;
const double     HMMWV_SolidAxleFront::m_LLMass = 2.892;
const double     HMMWV_SolidAxleFront::m_knuckleMass = 1.356;
const double     HMMWV_SolidAxleFront::m_spindleMass = 0.248;
const double     HMMWV_SolidAxleFront::m_axleTubeMass = 44.958;

const double     HMMWV_SolidAxleFront::m_spindleRadius = 0.06;
const double     HMMWV_SolidAxleFront::m_spindleWidth = 0.06;
const double     HMMWV_SolidAxleFront::m_ULRadius = 0.02;
const double     HMMWV_SolidAxleFront::m_LLRadius = 0.02;
const double     HMMWV_SolidAxleFront::m_axleTubeRadius = 0.03;
const double     HMMWV_SolidAxleFront::m_knuckleRadius = 0.01;

const ChVector<> HMMWV_SolidAxleFront::m_axleTubeCOM(0, 0, 0);

const ChVector<> HMMWV_SolidAxleFront::m_axleTubeInertia(7.744, 0.045, 7.744);
const ChVector<> HMMWV_SolidAxleFront::m_spindleInertia(0.0000558, 0.0000279, 0.0000558);
const ChVector<> HMMWV_SolidAxleFront::m_ULInertia(0.011, 0.011, 0.000142);
const ChVector<> HMMWV_SolidAxleFront::m_LLInertia(0.0514, 0.0514, 0.00037);
const ChVector<> HMMWV_SolidAxleFront::m_knuckleInertia(0.00255, 0.00134, 0.00196);

const double     HMMWV_SolidAxleFront::m_axleInertia = 0.4;

const double     HMMWV_SolidAxleFront::m_springCoefficient  = 267062.0;
const double     HMMWV_SolidAxleFront::m_dampingCoefficient = 22459.0;
const double     HMMWV_SolidAxleFront::m_springRestLength = 0.3948;

// -----------------------------------------------------------------------------

const double     HMMWV_SolidAxleRear::m_ULMass = 1.446;
const double     HMMWV_SolidAxleRear::m_LLMass = 2.892;
const double     HMMWV_SolidAxleRear::m_knuckleMass = 1.356;
const double     HMMWV_SolidAxleRear::m_spindleMass = 0.248;
const double     HMMWV_SolidAxleRear::m_axleTubeMass = 44.958;

const double     HMMWV_SolidAxleRear::m_spindleRadius = 0.06;
const double     HMMWV_SolidAxleRear::m_spindleWidth = 0.06;
const double     HMMWV_SolidAxleRear::m_ULRadius = 0.02;
const double     HMMWV_SolidAxleRear::m_LLRadius = 0.02;
const double     HMMWV_SolidAxleRear::m_axleTubeRadius = 0.03;
const double     HMMWV_SolidAxleRear::m_knuckleRadius = 0.01;

const ChVector<> HMMWV_SolidAxleRear::m_axleTubeCOM(0, 0, 0);

const ChVector<> HMMWV_SolidAxleRear::m_axleTubeInertia(7.744, 0.045, 7.744);
const ChVector<> HMMWV_SolidAxleRear::m_spindleInertia(0.0000558, 0.0000279, 0.0000558);
const ChVector<> HMMWV_SolidAxleRear::m_ULInertia(0.011, 0.011, 0.000142);
const ChVector<> HMMWV_SolidAxleRear::m_LLInertia(0.0514, 0.0514, 0.00037);
const ChVector<> HMMWV_SolidAxleRear::m_knuckleInertia(0.00255, 0.00134, 0.00196);

const double     HMMWV_SolidAxleRear::m_axleInertia = 0.4;

const double     HMMWV_SolidAxleRear::m_springCoefficient = 267062.0;
const double     HMMWV_SolidAxleRear::m_dampingCoefficient = 22459.0;
const double     HMMWV_SolidAxleRear::m_springRestLength = 0.3948;

// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
HMMWV_SolidAxleFront::HMMWV_SolidAxleFront(const std::string& name,
                                           bool               driven)
: ChSolidAxle(name, driven)
{
}

HMMWV_SolidAxleRear::HMMWV_SolidAxleRear(const std::string& name,
                                         bool               driven)
: ChSolidAxle(name, driven)
{
}

// -----------------------------------------------------------------------------
// Implementations of the getLocation() virtual methods.
// -----------------------------------------------------------------------------

const ChVector<> HMMWV_SolidAxleFront::getLocation(PointId which)
{
  switch (which) {
  case SHOCK_A:    return ChVector<>(-0.079, 0.697, -0.030);
  case SHOCK_C:    return ChVector<>(-0.097, 0.679, 0.364);
  case KNUCKLE_L:  return ChVector<>(0.006, 0.849, -0.061);
  case KNUCKLE_U:  return ChVector<>(-0.018, 0.819, 0.091);
  case LL_A:       return ChVector<>(0.012, 0.728, -0.091);
  case LL_C:       return ChVector<>(0.546, 0.425, -0.055);
  case UL_A:       return ChVector<>(-0.067, 0.576, 0.182);
  case UL_C:       return ChVector<>(0.431, 0.606, 0.182);
  case SPRING_A:   return ChVector<>(-0.079, 0.697, -0.030);
  case SPRING_C:   return ChVector<>(-0.097, 0.679, 0.364);
  case TIEROD_C:   return ChVector<>(-0.091, 0.400, -0.079);
  case TIEROD_K:   return ChVector<>(-0.091, 0.825, -0.079);
  case SPINDLE:    return ChVector<>(0, 0.910, 0);
  case KNUCKLE_CM: return ChVector<>(-0.006, 0.834, 0.015);
  case LL_CM:      return ChVector<>(-0.279, 0.577, -0.073);
  case UL_CM:      return ChVector<>(-0.182, 0.591, 0.182);
  default:         return ChVector<>(0, 0, 0);
  }
}

const ChVector<> HMMWV_SolidAxleRear::getLocation(PointId which)
{
  switch (which) {
  case SHOCK_A:    return ChVector<>(-0.079, 0.697, -0.030);
  case SHOCK_C:    return ChVector<>(-0.097, 0.679, 0.364);
  case KNUCKLE_L:  return ChVector<>(0.006, 0.849, -0.061);
  case KNUCKLE_U:  return ChVector<>(-0.018, 0.819, 0.091);
  case LL_A:       return ChVector<>(0.012, 0.728, -0.091);
  case LL_C:       return ChVector<>(0.546, 0.425, -0.055);
  case UL_A:       return ChVector<>(-0.067, 0.576, 0.182);
  case UL_C:       return ChVector<>(0.431, 0.606, 0.182);
  case SPRING_A:   return ChVector<>(-0.079, 0.697, -0.030);
  case SPRING_C:   return ChVector<>(-0.097, 0.679, 0.364);
  case TIEROD_C:   return ChVector<>(-0.091, 0.400, -0.079);
  case TIEROD_K:   return ChVector<>(-0.091, 0.825, -0.079);
  case SPINDLE:    return ChVector<>(0, 0.910, 0);
  case KNUCKLE_CM: return ChVector<>(-0.006, 0.834, 0.015);
  case LL_CM:      return ChVector<>(-0.279, 0.577, -0.073);
  case UL_CM:      return ChVector<>(-0.182, 0.591, 0.182);
  default:         return ChVector<>(0, 0, 0);
  }
}

// -----------------------------------------------------------------------------
// Implementations of the getDirection() virtual methods.
// -----------------------------------------------------------------------------

const ChVector<> HMMWV_SolidAxleFront::getDirection(DirectionId which)
{
  switch (which) {
  case UNIV_AXIS_LINK_L:      return ChVector<>(0, 1, 0);
  case UNIV_AXIS_CHASSIS_L:   return ChVector<>(0, 0, 1);
  case UNIV_AXIS_LINK_U:      return ChVector<>(0, -1, 0);
  case UNIV_AXIS_CHASSIS_U:   return ChVector<>(0, 0, 1);
  default:                    return ChVector<>(0, 0, 1);
  }
}

const ChVector<> HMMWV_SolidAxleRear::getDirection(DirectionId which)
{
  switch (which) {
  case UNIV_AXIS_LINK_L:      return ChVector<>(0, 1, 0);
  case UNIV_AXIS_CHASSIS_L:   return ChVector<>(0, 0, 1);
  case UNIV_AXIS_LINK_U:      return ChVector<>(0, -1, 0);
  case UNIV_AXIS_CHASSIS_U:   return ChVector<>(0, 0, 1);
  default:                    return ChVector<>(0, 0, 1);
  }
}

} // end namespace hmmwv
<|endoftext|>


<commit_before><commit_msg>Doxygenize comments, and move them in front of the functions.<commit_after><|endoftext|>


<commit_before>/*****************************************************************************************
*                                                                                *
* OpenSpace                                                                             *
*                                                                                *
* Copyright (c) 2014-2016                                                               *
*                                                                                *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify,    *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
* permit persons to whom the Software is furnished to do so, subject to the following   *
* conditions:                                                                           *
*                                                                                *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software.                                              *
*                                                                                *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
****************************************************************************************/
#include <modules/base/rendering/screenspaceimage.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/filesystem/filesystem>
#include <openspace/rendering/renderengine.h>
#include <openspace/engine/openspaceengine.h>
#include <ghoul/opengl/textureunit.h>
#include <modules/onscreengui/include/gui.h>

namespace openspace {
	ScreenSpaceImage::ScreenSpaceImage()
		:ScreenSpaceRenderable()
	{
		setName("ScreenSpaceImage");
	}

	ScreenSpaceImage::~ScreenSpaceImage(){}

void ScreenSpaceImage::render(){
	glm::mat4 transform = glm::translate(glm::mat4(1.f), _position.value());
	transform = glm::scale(transform, glm::vec3(_scale.value()));

    // transform.translate(position.value());
    _shader->activate();

    _shader->setUniform("ModelTransform",transform);

	ghoul::opengl::TextureUnit unit;
	unit.activate();
	_texture->bind();
	_shader->setUniform("texture1", unit);

	glBindVertexArray(_quad);
	glDrawArrays(GL_TRIANGLES, 0, 6);

	_shader->deactivate();
}

bool ScreenSpaceImage::initialize(){
	OsEng.gui()._property.registerProperty(&_enabled);
	OsEng.gui()._property.registerProperty(&_flatScreen);

	glGenVertexArrays(1, &_quad); // generate array
	glGenBuffers(1, &_vertexPositionBuffer); // generate buffer
	createPlane();

	_texturePath = "../../data/test.png";

	if(_shader == nullptr) {
    	RenderEngine& renderEngine = OsEng.renderEngine();
        _shader = renderEngine.buildRenderProgram("ScreenSpaceProgram",
            "${MODULE_BASE}/shaders/screnspace_vs.glsl",
            "${MODULE_BASE}/shaders/screnspace_fs.glsl"
            );
        if (!_shader)
            return false;
	}

	loadTexture();

	return isReady();
}
bool ScreenSpaceImage::deinitialize(){

}
void ScreenSpaceImage::update(){

}

bool ScreenSpaceImage::isReady() const{
	bool ready = true;
	if (!_shader)
		ready &= false;
	if(!_texture)
		ready &= false;
	return ready;
}

void ScreenSpaceImage::loadTexture() {
	if (_texturePath != "") {
        std::unique_ptr<ghoul::opengl::Texture> texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath));
		if (texture) {
			// LDEBUG("Loaded texture from '" << absPath(_texturePath) << "'");
			// std::cout<< std::endl << std::endl << "Loaded texture from '" << absPath(_texturePath) << "'" <<std::endl << std::endl;
			texture->uploadTexture();

			// Textures of planets looks much smoother with AnisotropicMipMap rather than linear
			texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);

            _texture = std::move(texture);

            // delete _textureFile;
            // _textureFile = new ghoul::filesystem::File(_texturePath);
            // _textureFile->setCallback([&](const ghoul::filesystem::File&) { _textureIsDirty = true; });
		}
	}
}
}<commit_msg>windows fix in screenspaceimage<commit_after>/*****************************************************************************************
*                                                                                *
* OpenSpace                                                                             *
*                                                                                *
* Copyright (c) 2014-2016                                                               *
*                                                                                *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify,    *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
* permit persons to whom the Software is furnished to do so, subject to the following   *
* conditions:                                                                           *
*                                                                                *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software.                                              *
*                                                                                *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
****************************************************************************************/
#include <modules/base/rendering/screenspaceimage.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/filesystem/filesystem>
#include <openspace/rendering/renderengine.h>
#include <openspace/engine/openspaceengine.h>
#include <ghoul/opengl/textureunit.h>
#include <modules/onscreengui/include/gui.h>

namespace openspace {
	ScreenSpaceImage::ScreenSpaceImage()
		:ScreenSpaceRenderable()
	{
		setName("ScreenSpaceImage");
	}

	ScreenSpaceImage::~ScreenSpaceImage(){}

void ScreenSpaceImage::render(){
	glm::mat4 transform = glm::translate(glm::mat4(1.f), _position.value());
	transform = glm::scale(transform, glm::vec3(_scale.value()));

    // transform.translate(position.value());
    _shader->activate();

    _shader->setUniform("ModelTransform",transform);

	ghoul::opengl::TextureUnit unit;
	unit.activate();
	_texture->bind();
	_shader->setUniform("texture1", unit);

	glBindVertexArray(_quad);
	glDrawArrays(GL_TRIANGLES, 0, 6);

	_shader->deactivate();
}

bool ScreenSpaceImage::initialize(){
	OsEng.gui()._property.registerProperty(&_enabled);
	OsEng.gui()._property.registerProperty(&_flatScreen);

	glGenVertexArrays(1, &_quad); // generate array
	glGenBuffers(1, &_vertexPositionBuffer); // generate buffer
	createPlane();

	_texturePath = "${OPENSPACE_DATA}/test.png";

	if(_shader == nullptr) {
    	RenderEngine& renderEngine = OsEng.renderEngine();
        _shader = renderEngine.buildRenderProgram("ScreenSpaceProgram",
            "${MODULE_BASE}/shaders/screnspace_vs.glsl",
            "${MODULE_BASE}/shaders/screnspace_fs.glsl"
            );
        if (!_shader)
            return false;
	}

	loadTexture();

	return isReady();
}
bool ScreenSpaceImage::deinitialize(){
	return true;
}
void ScreenSpaceImage::update(){

}

bool ScreenSpaceImage::isReady() const{
	bool ready = true;
	if (!_shader)
		ready &= false;
	if(!_texture)
		ready &= false;
	return ready;
}

void ScreenSpaceImage::loadTexture() {
	if (_texturePath != "") {
        std::unique_ptr<ghoul::opengl::Texture> texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath));
		if (texture) {
			// LDEBUG("Loaded texture from '" << absPath(_texturePath) << "'");
			// std::cout<< std::endl << std::endl << "Loaded texture from '" << absPath(_texturePath) << "'" <<std::endl << std::endl;
			texture->uploadTexture();

			// Textures of planets looks much smoother with AnisotropicMipMap rather than linear
			texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);

            _texture = std::move(texture);

            // delete _textureFile;
            // _textureFile = new ghoul::filesystem::File(_texturePath);
            // _textureFile->setCallback([&](const ghoul::filesystem::File&) { _textureIsDirty = true; });
		}
	}
}
}<|endoftext|>


<commit_before>#include "knn.h"

#include <time.h>
#include <math.h>
#include <unordered_map>
#include <map>
#include <utility>
#include <functional>
#include <numeric>
#include <iostream>

using namespace std;

void perform_knn(const int k,
         const data_t* x,
         const data_t* labeled,
         const data_t* labels,
         const int dim,
         const int x_length,
         const int labeled_length,
         data_t* x_pred) {
    // Loop through data points and classify each based on nearest labeled
    // neighbors.
    for (int i = 0; i < x_length; i++) {
#if DEBUG
        if (i%100 == 0) {
            cout << "Done classifying: " << i << endl;
        }
#endif
        knn(k, x, i, labeled, labels, dim, labeled_length, x_pred);
    }
}

void knn(const int k,
         const data_t* x,
         const int i,
         const data_t* labeled,
         const data_t* labels,
         const int dim,
         const int labeled_length,
         data_t* x_pred) {
    float distances[labeled_length];
    // Compute the hamming distances between x and the labeled data.
    for (int j = 0; j < labeled_length; j++) {
        distances[j] = euclid_distance(x + i*dim, labeled + j*dim, dim);
    }
    // Predict the class for this data point.
    x_pred[i] = predict_class(
            distances,
            labels,
            labeled_length,
            k);
}

float euclid_distance(const data_t* x, const data_t* y, const int length) {
    float dist = 0;
    for (int i = 0; i < length; i++) {
        dist += pow(fabs(x[i] - y[i]), 2);
    }
    return sqrt(dist);
}

data_t hamming_distance(const data_t* x, const data_t* y, const int length) {
    data_t dist = 0;
    for (int i = 0; i < length; i++) {
        dist += (data_t) fabs(x[i] - y[i]);
    }
    return dist;
}

int predict_class(const float* distances,
                  const data_t* labels,
                  const int length,
                  const int k) {
    vector< pair<int, float> > min_dist_labels;
    // Compute the labels of the k minimum distances.
    for (int i = 0; i < length; i++) {
        if (min_dist_labels.size() < k) {
            min_dist_labels.push_back(
                    pair<int, float>(labels[i], distances[i]));
        } else if (distances[i] < min_dist_labels.back().second) {
            // Delete the last element, the largest.
            min_dist_labels.pop_back();
            // Insert new smaller distance element.
            min_dist_labels.push_back(
                    pair<int, float>(labels[i], distances[i]));
        }
        // Keep our list sorted so that we can compare new distances to
        // the last element.
        sort(min_dist_labels.begin(), min_dist_labels.end(), compare_labels);
    }
    // Compute the mode of the k labels.
    return mode_labels(min_dist_labels);
}

int mode_labels(const vector< pair<int, float> >& labels) {
    vector<int> counts;
    vector<int> ties;
    for (int i = 0; i < labels.size(); i++) {
        counts.push_back(labels[i].first);
    }

    sort(counts.begin(), counts.end());

    int number = counts[0];
    int mode = number;
    int count = 1;
    int countMode = 1;
    ties.push_back(number);

    for (int i=1; i< counts.size(); i++)
    {
        if (counts[i] == number) { // count occurrences of the current number
            count++;
            if (count > countMode) {
                countMode = count; // mode is the biggest ocurrences
                mode = number;
                ties.clear();
                ties.push_back(mode);
            } else if (count == countMode) {
                ties.push_back(number);
            }
        }
        else { // now this is a different number
            count = 1; // reset count for the new number
            number = counts[i];
        }
    }

    for (int i = 0; i < labels.size(); i++) {
        if (std::find(ties.begin(), ties.end(), labels[i].first) != ties.end()) {
            return labels[i].first;
        }
    }

    return mode;
}

bool compare_labels(const pair<int, float>&i, const pair<int, float>&j) {
    return i.second < j.second;
}

struct timespec diff(struct timespec start, struct timespec end){
  struct timespec temp;
  if ((end.tv_nsec-start.tv_nsec)<0) {
    temp.tv_sec = end.tv_sec-start.tv_sec-1;
    temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
  } else {
    temp.tv_sec = end.tv_sec-start.tv_sec;
    temp.tv_nsec = end.tv_nsec-start.tv_nsec;
  }
  return temp;
}
<commit_msg>removed unneeded import<commit_after>#include "knn.h"

#include <time.h>
#include <math.h>
#include <map>
#include <utility>
#include <functional>
#include <numeric>
#include <iostream>

using namespace std;

void perform_knn(const int k,
         const data_t* x,
         const data_t* labeled,
         const data_t* labels,
         const int dim,
         const int x_length,
         const int labeled_length,
         data_t* x_pred) {
    // Loop through data points and classify each based on nearest labeled
    // neighbors.
    for (int i = 0; i < x_length; i++) {
#if DEBUG
        if (i%100 == 0) {
            cout << "Done classifying: " << i << endl;
        }
#endif
        knn(k, x, i, labeled, labels, dim, labeled_length, x_pred);
    }
}

void knn(const int k,
         const data_t* x,
         const int i,
         const data_t* labeled,
         const data_t* labels,
         const int dim,
         const int labeled_length,
         data_t* x_pred) {
    float distances[labeled_length];
    // Compute the hamming distances between x and the labeled data.
    for (int j = 0; j < labeled_length; j++) {
        distances[j] = euclid_distance(x + i*dim, labeled + j*dim, dim);
    }
    // Predict the class for this data point.
    x_pred[i] = predict_class(
            distances,
            labels,
            labeled_length,
            k);
}

float euclid_distance(const data_t* x, const data_t* y, const int length) {
    float dist = 0;
    for (int i = 0; i < length; i++) {
        dist += pow(fabs(x[i] - y[i]), 2);
    }
    return sqrt(dist);
}

data_t hamming_distance(const data_t* x, const data_t* y, const int length) {
    data_t dist = 0;
    for (int i = 0; i < length; i++) {
        dist += (data_t) fabs(x[i] - y[i]);
    }
    return dist;
}

int predict_class(const float* distances,
                  const data_t* labels,
                  const int length,
                  const int k) {
    vector< pair<int, float> > min_dist_labels;
    // Compute the labels of the k minimum distances.
    for (int i = 0; i < length; i++) {
        if (min_dist_labels.size() < k) {
            min_dist_labels.push_back(
                    pair<int, float>(labels[i], distances[i]));
        } else if (distances[i] < min_dist_labels.back().second) {
            // Delete the last element, the largest.
            min_dist_labels.pop_back();
            // Insert new smaller distance element.
            min_dist_labels.push_back(
                    pair<int, float>(labels[i], distances[i]));
        }
        // Keep our list sorted so that we can compare new distances to
        // the last element.
        sort(min_dist_labels.begin(), min_dist_labels.end(), compare_labels);
    }
    // Compute the mode of the k labels.
    return mode_labels(min_dist_labels);
}

int mode_labels(const vector< pair<int, float> >& labels) {
    vector<int> counts;
    vector<int> ties;
    for (int i = 0; i < labels.size(); i++) {
        counts.push_back(labels[i].first);
    }

    sort(counts.begin(), counts.end());

    int number = counts[0];
    int mode = number;
    int count = 1;
    int countMode = 1;
    ties.push_back(number);

    for (int i=1; i< counts.size(); i++)
    {
        if (counts[i] == number) { // count occurrences of the current number
            count++;
            if (count > countMode) {
                countMode = count; // mode is the biggest ocurrences
                mode = number;
                ties.clear();
                ties.push_back(mode);
            } else if (count == countMode) {
                ties.push_back(number);
            }
        }
        else { // now this is a different number
            count = 1; // reset count for the new number
            number = counts[i];
        }
    }

    for (int i = 0; i < labels.size(); i++) {
        if (std::find(ties.begin(), ties.end(), labels[i].first) != ties.end()) {
            return labels[i].first;
        }
    }

    return mode;
}

bool compare_labels(const pair<int, float>&i, const pair<int, float>&j) {
    return i.second < j.second;
}

struct timespec diff(struct timespec start, struct timespec end){
  struct timespec temp;
  if ((end.tv_nsec-start.tv_nsec)<0) {
    temp.tv_sec = end.tv_sec-start.tv_sec-1;
    temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
  } else {
    temp.tv_sec = end.tv_sec-start.tv_sec;
    temp.tv_nsec = end.tv_nsec-start.tv_nsec;
  }
  return temp;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: doctemplates.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: dv $ $Date: 2001-03-09 14:48:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2001 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SFX_DOCTEMPLATES_HXX_
#define _SFX_DOCTEMPLATES_HXX_

#ifndef  _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef  _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef  _COM_SUN_STAR_FRAME_XSTORABLE_HPP_
#include <com/sun/star/frame/XStorable.hpp>
#endif

#ifndef  _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef  _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_
#include <com/sun/star/lang/XLocalizable.hpp>
#endif
#ifndef  _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef  _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif

#ifndef  _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef  _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif

#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif

#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif

//--------------------------------------------------------------------------------------------------------

#define LOCALE                      ::com::sun::star::lang::Locale
#define REFERENCE                   ::com::sun::star::uno::Reference
#define RUNTIMEEXCEPTION            ::com::sun::star::uno::RuntimeException
#define XCONTENT                    ::com::sun::star::ucb::XContent
#define XDOCUMENTTEMPLATES          ::com::sun::star::frame::XDocumentTemplates
#define XINTERFACE                  ::com::sun::star::uno::XInterface
#define XLOCALIZABLE                ::com::sun::star::lang::XLocalizable
#define XSERVICEINFO                ::com::sun::star::lang::XServiceInfo
#define XSTORABLE                   ::com::sun::star::frame::XStorable

//--------------------------------------------------------------------------------------------------------

class SfxDocTplService_Impl;

class SfxDocTplService: public ::cppu::WeakImplHelper3< XLOCALIZABLE, XDOCUMENTTEMPLATES, XSERVICEINFO >
{
    SfxDocTplService_Impl       *pImp;

public:
                                    SFX_DECL_XSERVICEINFO

                                    SfxDocTplService( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );
                                   ~SfxDocTplService();

    // --- XLocalizable ---
    void SAL_CALL                   setLocale( const LOCALE & eLocale ) throw( RUNTIMEEXCEPTION );
    LOCALE SAL_CALL                 getLocale() throw( RUNTIMEEXCEPTION );

    // --- XDocumentTemplates ---
    REFERENCE< XCONTENT > SAL_CALL  getContent() throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               storeTemplate( const ::rtl::OUString& GroupName,
                                                   const ::rtl::OUString& TemplateName,
                                                   const REFERENCE< XSTORABLE >& Storable ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               addTemplate( const ::rtl::OUString& GroupName,
                                                 const ::rtl::OUString& TemplateName,
                                                 const ::rtl::OUString& SourceURL ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               removeTemplate( const ::rtl::OUString& GroupName,
                                                    const ::rtl::OUString& TemplateName ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               addGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               removeGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
    void SAL_CALL                   update() throw( RUNTIMEEXCEPTION );
};

#endif
<commit_msg>Added renameTemplate/Group<commit_after>/*************************************************************************
 *
 *  $RCSfile: doctemplates.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dv $ $Date: 2001-03-23 15:12:04 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2001 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SFX_DOCTEMPLATES_HXX_
#define _SFX_DOCTEMPLATES_HXX_

#ifndef  _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef  _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef  _COM_SUN_STAR_FRAME_XSTORABLE_HPP_
#include <com/sun/star/frame/XStorable.hpp>
#endif

#ifndef  _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef  _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_
#include <com/sun/star/lang/XLocalizable.hpp>
#endif
#ifndef  _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef  _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif

#ifndef  _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef  _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif

#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif

#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif

//--------------------------------------------------------------------------------------------------------

#define LOCALE                      ::com::sun::star::lang::Locale
#define REFERENCE                   ::com::sun::star::uno::Reference
#define RUNTIMEEXCEPTION            ::com::sun::star::uno::RuntimeException
#define XCONTENT                    ::com::sun::star::ucb::XContent
#define XDOCUMENTTEMPLATES          ::com::sun::star::frame::XDocumentTemplates
#define XINTERFACE                  ::com::sun::star::uno::XInterface
#define XLOCALIZABLE                ::com::sun::star::lang::XLocalizable
#define XSERVICEINFO                ::com::sun::star::lang::XServiceInfo
#define XSTORABLE                   ::com::sun::star::frame::XStorable

//--------------------------------------------------------------------------------------------------------

class SfxDocTplService_Impl;

class SfxDocTplService: public ::cppu::WeakImplHelper3< XLOCALIZABLE, XDOCUMENTTEMPLATES, XSERVICEINFO >
{
    SfxDocTplService_Impl       *pImp;

public:
                                    SFX_DECL_XSERVICEINFO

                                    SfxDocTplService( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );
                                   ~SfxDocTplService();

    // --- XLocalizable ---
    void SAL_CALL                   setLocale( const LOCALE & eLocale ) throw( RUNTIMEEXCEPTION );
    LOCALE SAL_CALL                 getLocale() throw( RUNTIMEEXCEPTION );

    // --- XDocumentTemplates ---
    REFERENCE< XCONTENT > SAL_CALL  getContent() throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               storeTemplate( const ::rtl::OUString& GroupName,
                                                   const ::rtl::OUString& TemplateName,
                                                   const REFERENCE< XSTORABLE >& Storable ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               addTemplate( const ::rtl::OUString& GroupName,
                                                 const ::rtl::OUString& TemplateName,
                                                 const ::rtl::OUString& SourceURL ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               removeTemplate( const ::rtl::OUString& GroupName,
                                                    const ::rtl::OUString& TemplateName ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               renameTemplate( const ::rtl::OUString& GroupName,
                                                    const ::rtl::OUString& OldTemplateName,
                                                    const ::rtl::OUString& NewTemplateName ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               addGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               removeGroup( const ::rtl::OUString& GroupName ) throw( RUNTIMEEXCEPTION );
    sal_Bool SAL_CALL               renameGroup( const ::rtl::OUString& OldGroupName,
                                                 const ::rtl::OUString& NewGroupName ) throw( RUNTIMEEXCEPTION );
    void SAL_CALL                   update() throw( RUNTIMEEXCEPTION );
};

#endif
<|endoftext|>


<commit_before>#include "WolframLibrary.h"

DLLEXPORT mint
WolframLibrary_getVersion()
{
   return WolframLibraryVersion;
}

DLLEXPORT int
WolframLibrary_initialize( WolframLibraryData libData )
{
   return 0;
}

DLLEXPORT void
WolframLibrary_uninitialize( WolframLibraryData libData )
{
   return;
}

DLLEXPORT int
constantzero ( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res )
{
   MArgument_setInteger (Res, 0);
   return LIBRARY_NO_ERROR;
}

void
work( double *inputs, double *outputs, const mint* dims, int side )
{
   int filterLength = side*2+1;
   int OY = (dims[3]-2*side)*filterLength*filterLength;
   int OF = (dims[2]-2*side)*(dims[3]-2*side)*filterLength*filterLength;
   int OL = dims[1]*(dims[2]-2*side)*(dims[3]-2*side)*filterLength*filterLength;
   int IY = dims[3];
   int IF = dims[2]*dims[3];
   int IL = (dims[1]*dims[2]*dims[3]);

   for ( int l = 0 ; l < dims[0]; l++ )
      for ( int f = 0 ; f < dims[1] ; f++ )
         for ( int y = 0 ; y < dims[2]-2*side ; y++ )
            for ( int x = 0 ; x < dims[3]-2*side ; x++ )
               for ( int sy = -side ; sy < 1+side ; sy++ )
                  for ( int sx = -side ; sx < 1+side ; sx++ )
                     //(*outputs)[l][y][x][sy+1][sx+1] = (*inputs)[l][f][y+sy+1][x+sx+1];
                     outputs[OL*l + OF*(f) + OY*(y) + (filterLength*filterLength)*(x) + filterLength*(sy+side) + sx+side] =
						inputs[IL*l + IF*(f) + IY*(y+sy+side) + (x+sx+side)];
}

/*
   Input: N*F*(Y+2)*(X+2) array of doubles
   Output: N*F*Y*X*3*3 array of doubles

   Requires: the data part of the input is Y*X padded on either side by .0 (hence Y+2*X+2)
*/
DLLEXPORT int
NNCPUExtensionOverlappingPartition( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res )
{
   MTensor inputTensor = MArgument_getMTensor (Args[0]);
   double* inputs = libData -> MTensor_getRealData ( inputTensor );
   mint const* dims;
   dims = libData->MTensor_getDimensions( inputTensor );

   MTensor outputTensor;
   mint type = MType_Real;
   mint dimsOutput[6];
   mint rank = 6;
   int err;

   mint runLength = MArgument_getInteger(Args[1]);
   int side = (runLength-1)/2; //refers to how far filter extends from centre, e.g. 5*5 filter extends 2 from centre

   dimsOutput[0] = dims[0];
   dimsOutput[1] = dims[1];
   dimsOutput[2] = dims[2]-2*side;
   dimsOutput[3] = dims[3]-2*side;
   dimsOutput[4] = runLength;
   dimsOutput[5] = runLength;

   err = libData -> MTensor_new ( type, rank, dimsOutput, &outputTensor);
   double* ptr = libData -> MTensor_getRealData ( outputTensor );

   work( inputs, ptr, dims, side );

   MArgument_setMTensor ( Res, outputTensor );
   return LIBRARY_NO_ERROR;
}
<commit_msg>NNOverlapPartition speed ups<commit_after>#include "WolframLibrary.h"

DLLEXPORT mint
WolframLibrary_getVersion()
{
   return WolframLibraryVersion;
}

DLLEXPORT int
WolframLibrary_initialize( WolframLibraryData libData )
{
   return 0;
}

DLLEXPORT void
WolframLibrary_uninitialize( WolframLibraryData libData )
{
   return;
}

DLLEXPORT int
constantzero ( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res )
{
   MArgument_setInteger (Res, 0);
   return LIBRARY_NO_ERROR;
}

void
work( double *inputs, double *outputs, const mint* dims, int side )
{
   int filterLength = side*2+1;
   int OY = (dims[3]-2*side)*filterLength*filterLength;
   int OF = (dims[2]-2*side)*(dims[3]-2*side)*filterLength*filterLength;
   int OL = dims[1]*(dims[2]-2*side)*(dims[3]-2*side)*filterLength*filterLength;
   int IY = dims[3];
   int IF = dims[2]*dims[3];
   int IL = (dims[1]*dims[2]*dims[3]);

   int outputOffset, inputOffset;
   int dof, dif;
   for ( int l = 0 ; l < dims[0]; l++ )
      for ( int f = 0 ; f < dims[1] ; f++ )
      {
         outputOffset = OL*l + OF*(f);
         inputOffset = IL*l + IF*(f);

         for ( int y = 0 ; y < dims[2]-2*side ; y++ )
            for ( int x = 0 ; x < dims[3]-2*side ; x++ )
               for ( int sy = 0; sy < filterLength ; sy++ )
               {
                  dof = outputOffset + OY*(y) + (filterLength*filterLength)*(x) + filterLength*(sy);
                  dif = inputOffset + IY*(y+sy) + x;
                  for ( int sx = 0 ; sx < filterLength ; sx++ )
                     outputs[dof + sx] = inputs[dif + sx];
               }
      }
}

/*
   Input: N*F*(Y+2*SIDE)*(X+2*SIDE) array of doubles
   Output: N*F*Y*X*FLENGTH*FLENGTH array of doubles

   Requires: the data part of the input is Y*X padded on either side by .0 (hence Y+2*X+2)
*/
DLLEXPORT int
NNCPUExtensionOverlappingPartition( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res )
{
   MTensor inputTensor = MArgument_getMTensor (Args[0]);
   double* inputs = libData -> MTensor_getRealData ( inputTensor );
   mint const* dims;
   dims = libData->MTensor_getDimensions( inputTensor );

   MTensor outputTensor;
   mint type = MType_Real;
   mint dimsOutput[6];
   mint rank = 6;
   int err;

   mint runLength = MArgument_getInteger(Args[1]);
   int side = (runLength-1)/2; //refers to how far filter extends from centre, e.g. 5*5 filter extends 2 from centre

   dimsOutput[0] = dims[0];
   dimsOutput[1] = dims[1];
   dimsOutput[2] = dims[2]-2*side;
   dimsOutput[3] = dims[3]-2*side;
   dimsOutput[4] = runLength;
   dimsOutput[5] = runLength;

   err = libData -> MTensor_new ( type, rank, dimsOutput, &outputTensor);
   double* ptr = libData -> MTensor_getRealData ( outputTensor );

   work( inputs, ptr, dims, side );

   MArgument_setMTensor ( Res, outputTensor );
   return LIBRARY_NO_ERROR;
}
<|endoftext|>


<commit_before>#ifndef COMMON_H
#define COMMON_H

#include <string>

#define VERSION_MAJOR "0"
#define VERSION_MINOR_HI "0"
#define VERSION_MINOR_LO "0"
#define VERSION_SUFFIX " alpha"

#ifndef COMMIT_ID
#define COMMIT_ID unknown
#endif
#define STRINGIZE(x) #x
#define STRINGIZE_VALUE_OF(x) STRINGIZE(x)
#ifndef BUILD_DATE
#define BUILD_DATE __DATE__
#endif
#ifndef BUILD_TIME
#define BUILD_TIME __TIME__
#endif

#define PROJECT_URL "https://github.com/ivanbilych/jougen"

const std::string versionMajor { VERSION_MAJOR };
const std::string versionMinorHi { VERSION_MINOR_HI };
const std::string versionMinorLo { VERSION_MINOR_LO };
const std::string versionSuffix { VERSION_SUFFIX };
const std::string programVersion { versionMajor + "." + versionMinorHi + "." + versionMinorLo + versionSuffix };
const std::string buildDate { BUILD_DATE };
const std::string buildTime { BUILD_TIME };
const std::string buildTimestamp { buildDate + " " + buildTime };
const std::string buildCommit { STRINGIZE_VALUE_OF(COMMIT_ID) };
const std::string projectURL { PROJECT_URL };

#endif // COMMON_H
<commit_msg>versionInfo: Bumped version number to 0.1<commit_after>#ifndef COMMON_H
#define COMMON_H

#include <string>

#define VERSION_MAJOR "0"
#define VERSION_MINOR_HI "1"
#define VERSION_MINOR_LO "0"
#define VERSION_SUFFIX " alpha"

#ifndef COMMIT_ID
#define COMMIT_ID unknown
#endif
#define STRINGIZE(x) #x
#define STRINGIZE_VALUE_OF(x) STRINGIZE(x)
#ifndef BUILD_DATE
#define BUILD_DATE __DATE__
#endif
#ifndef BUILD_TIME
#define BUILD_TIME __TIME__
#endif

#define PROJECT_URL "https://github.com/ivanbilych/jougen"

const std::string versionMajor { VERSION_MAJOR };
const std::string versionMinorHi { VERSION_MINOR_HI };
const std::string versionMinorLo { VERSION_MINOR_LO };
const std::string versionSuffix { VERSION_SUFFIX };
const std::string programVersion { versionMajor + "." + versionMinorHi + "." + versionMinorLo + versionSuffix };
const std::string buildDate { BUILD_DATE };
const std::string buildTime { BUILD_TIME };
const std::string buildTimestamp { buildDate + " " + buildTime };
const std::string buildCommit { STRINGIZE_VALUE_OF(COMMIT_ID) };
const std::string projectURL { PROJECT_URL };

#endif // COMMON_H
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <vector>
#include <cmath>
#include <cstring>
using std::string;
using std::vector;
using std::make_pair;
using std::pow;
using std::ceil;

#include <Exceptions.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Kernel.hpp>
#include <Observation.hpp>
using isa::Exceptions::OpenCLError;
using isa::OpenCL::CLData;
using isa::utils::giga;
using isa::utils::toStringValue;
using isa::utils::toString;
using isa::utils::replace;
using isa::OpenCL::Kernel;
using AstroData::Observation;

#ifndef FOLDING_HPP
#define FOLDING_HPP

namespace PulsarSearch {

// OpenCL folding algorithm
template< typename T > class Folding : public Kernel< T > {
public:
	Folding(string name, string dataType);

	void generateCode() throw (OpenCLError);
	void operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError);

	inline void setNrDMsPerBlock(unsigned int DMs);
	inline void setNrPeriodsPerBlock(unsigned int periods);
	inline void setNrBinsPerBlock(unsigned int bins);

	inline void setNrDMsPerThread(unsigned int DMs);
	inline void setNrPeriodsPerThread(unsigned int periods);
	inline void setNrBinsPerThread(unsigned int bins);

	inline void setObservation(Observation< T > * obs);

private:
	unsigned int nrDMsPerBlock;
	unsigned int nrPeriodsPerBlock;
	unsigned int nrBinsPerBlock;
	unsigned int nrDMsPerThread;
	unsigned int nrPeriodsPerThread;
	unsigned int nrBinsPerThread;
	cl::NDRange globalSize;
	cl::NDRange localSize;

	Observation< T > * observation;
};

// Implementation
template< typename T > Folding< T >::Folding(string name, string dataType) : Kernel< T >(name, dataType), nrDMsPerBlock(0), nrPeriodsPerBlock(0), nrBinsPerBlock(0), nrDMsPerThread(0), nrPeriodsPerThread(0), nrBinsPerThread(0), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), observation(0) {}

template< typename T > void Folding< T >::generateCode() throw (OpenCLError) {
	// Begin kernel's template
	string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond());
	string nrPaddedDMs_s  = toStringValue< unsigned int >(observation->getNrPaddedDMs());
	string nrPeriods_s = toStringValue< unsigned int >(observation->getNrPeriods());
	string nrBins_s = toStringValue< unsigned int >(observation->getNrBins());
	string nrDMsPerBlock_s = toStringValue< unsigned int >(nrDMsPerBlock);
	string nrDMsPerThread_s = toStringValue< unsigned int >(nrDMsPerThread);
	string nrPeriodsPerBlock_s = toStringValue< unsigned int >(nrPeriodsPerBlock);
	string nrPeriodsPerThread_s = toStringValue< unsigned int >(nrPeriodsPerThread);
	string nrBinsPerBlock_s = toStringValue< unsigned int >(nrBinsPerBlock);
	string nrBinsPerThread_s = toStringValue< unsigned int >(nrBinsPerThread);

	delete this->code;
	this->code = new string();
	*(this->code) = "__kernel void " + this->name + "(__global const " + this->dataType + " * const restrict samples, __global " + this->dataType + " * const restrict bins, __global unsigned int * const restrict counters) {\n"
	"<%DEFS%>"
	"\n"
	"<%COMPUTE%>"
	"\n"
	"<%STORE%>"
	"}\n";

	string defsTemplate = "const unsigned int DM<%DM_NUM%> = (get_group_id(0) * " + nrDMsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(0) + (<%DM_NUM%> * " + nrDMsPerBlock_s + "));\n"
		"const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + nrPeriodsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(1) + (<%PERIOD_NUM%> * " + nrPeriodsPerBlock_s + ");\n"
		"const unsigned int bin<%BIN_NUM%> = (get_group_id(2) * " + nrBinsPerBlock_s + " * " + nrBinsPerThread_s + ") + get_local_id(2) + (<%BIN_NUM%> * " + nrBinsPerBlock_s + ");\n"
		"const unsigned int period<%PERIOD_NUM%>Value = (period<%PERIOD_NUM%> + 1) * " + nrBins_s + ";\n"
		"unsigned int foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
		+ this->dataType + " foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
		"const unsigned int pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = counters[(bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n";

	string computeTemplate = "unsigned int sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (bin<%BIN_NUM%> * period<%PERIOD_NUM%>) + bin<%BIN_NUM%> + ((pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / (period<%PERIOD_NUM%> + 1)) * period<%PERIOD_NUM%>Value) + (pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % (period<%PERIOD_NUM%> + 1));\n"
	"if ( (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") == 0 ) {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
	"} else {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") - (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / "+ nrSamplesPerSecond_s + ");\n"
	"}\n"
	"while ( sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> < " + nrSamplesPerSecond_s + " ) {\n"
	"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += samples[(sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n"
	"foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
	"if ( ((foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) % (period<%PERIOD_NUM%> + 1)) == 0 ) {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += period<%PERIOD_NUM%>Value;\n"
	"} else {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
	"}\n"
	"}\n";

	string storeTemplate = "if ( foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> > 0 ) {\n"
	"const unsigned int outputItem = (bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>;\n"
	"const "+ this->dataType + " pValue = bins[outputItem];\n"
	+ this->dataType + " addedFraction = 0;"
	"addedFraction = convert_float(foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) / (foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>);\n"
	"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> /= foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
	"counters[outputItem] = pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
	"bins[outputItem] = (addedFraction * foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) + ((1.0f - addedFraction) * pValue);\n"
	"}\n";
	// End kernel's template

	string * defs = new string();
	string * computes = new string();
	string * stores = new string();
	for ( unsigned int DM = 0; DM < nrDMsPerThread; DM++ ) {
		string * DM_s = toString< unsigned int >(DM);

		for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {
			string * period_s = toString< unsigned int >(period);

			for ( unsigned int bin = 0; bin < nrBinsPerThread; bin++ ) {
				string * bin_s = toString< unsigned int >(bin);
				string * temp = 0;

				temp = replace(&defsTemplate, "<%BIN_NUM%>", *bin_s);
				temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
				temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
				defs->append(*temp);
				delete temp;

				temp = replace(&computeTemplate, "<%BIN_NUM%>", *bin_s);
				temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
				temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
				computes->append(*temp);
				delete temp;

				temp = replace(&storeTemplate, "<%BIN_NUM%>", *bin_s);
				temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
				temp = replace(temp, "<%DM_NUM%>", DM_s, true);
				stores->append(*temp);
				delete temp;

				delete bin_s;
			}

			delete period_s;
		}

		delete DM_s;
	}
	this->code = replace(this->code, "<%DEFS%>", *defs, true);
	this->code = replace(this->code, "<%COMPUTE%>", *computes. true);
	this->code = replace(this->code, "<%STORE%>", *stores, true);
	delete defs;
	delete computes;
	delete stores;

	globalSize = cl::NDRange(observation->getNrDMs() / nrDMsPerThread, observation->getNrPeriods() / nrPeriodsPerThread, observation->getNrBins() / nrBinsPerThread);
	localSize = cl::NDRange(nrDMsPerBlock, nrPeriodsPerBlock, nrBinsPerBlock);

	this->gflop = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * observation->getNrSamplesPerSecond());

	this->compile();
}

template< typename T > void Folding< T >::operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError) {
	this->setArgument(0, *(input->getDeviceData()));
	this->setArgument(1, *(output->getDeviceData()));
	this->setArgument(2, *(counters->getDeviceData()));

	this->run(globalSize, localSize);
}

template< typename T > inline void Folding< T >::setNrDMsPerBlock(unsigned int DMs) {
	nrDMsPerBlock = DMs;
}

template< typename T > inline void Folding< T >::setNrPeriodsPerBlock(unsigned int periods) {
	nrPeriodsPerBlock = periods;
}

template< typename T > inline void Folding< T >::setNrBinsPerBlock(unsigned int bins) {
	nrBinsPerBlock = bins;
}

template< typename T > inline void Folding< T >::setNrDMsPerThread(unsigned int DMs) {
	nrDMsPerThread = DMs;
}

template< typename T > inline void Folding< T >::setNrPeriodsPerThread(unsigned int periods) {
	nrPeriodsPerThread = periods;
}

template< typename T > inline void Folding< T >::setNrBinsPerThread(unsigned int bins) {
	nrBinsPerThread = bins;
}

template< typename T > inline void Folding< T >::setObservation(Observation< T > * obs) {
	observation = obs;
}

} // PulsarSearch

#endif // FOLDING_HPP
<commit_msg>Couple of typos. Fixed.<commit_after>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <vector>
#include <cmath>
#include <cstring>
using std::string;
using std::vector;
using std::make_pair;
using std::pow;
using std::ceil;

#include <Exceptions.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Kernel.hpp>
#include <Observation.hpp>
using isa::Exceptions::OpenCLError;
using isa::OpenCL::CLData;
using isa::utils::giga;
using isa::utils::toStringValue;
using isa::utils::toString;
using isa::utils::replace;
using isa::OpenCL::Kernel;
using AstroData::Observation;

#ifndef FOLDING_HPP
#define FOLDING_HPP

namespace PulsarSearch {

// OpenCL folding algorithm
template< typename T > class Folding : public Kernel< T > {
public:
	Folding(string name, string dataType);

	void generateCode() throw (OpenCLError);
	void operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError);

	inline void setNrDMsPerBlock(unsigned int DMs);
	inline void setNrPeriodsPerBlock(unsigned int periods);
	inline void setNrBinsPerBlock(unsigned int bins);

	inline void setNrDMsPerThread(unsigned int DMs);
	inline void setNrPeriodsPerThread(unsigned int periods);
	inline void setNrBinsPerThread(unsigned int bins);

	inline void setObservation(Observation< T > * obs);

private:
	unsigned int nrDMsPerBlock;
	unsigned int nrPeriodsPerBlock;
	unsigned int nrBinsPerBlock;
	unsigned int nrDMsPerThread;
	unsigned int nrPeriodsPerThread;
	unsigned int nrBinsPerThread;
	cl::NDRange globalSize;
	cl::NDRange localSize;

	Observation< T > * observation;
};

// Implementation
template< typename T > Folding< T >::Folding(string name, string dataType) : Kernel< T >(name, dataType), nrDMsPerBlock(0), nrPeriodsPerBlock(0), nrBinsPerBlock(0), nrDMsPerThread(0), nrPeriodsPerThread(0), nrBinsPerThread(0), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), observation(0) {}

template< typename T > void Folding< T >::generateCode() throw (OpenCLError) {
	// Begin kernel's template
	string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond());
	string nrPaddedDMs_s  = toStringValue< unsigned int >(observation->getNrPaddedDMs());
	string nrPeriods_s = toStringValue< unsigned int >(observation->getNrPeriods());
	string nrBins_s = toStringValue< unsigned int >(observation->getNrBins());
	string nrDMsPerBlock_s = toStringValue< unsigned int >(nrDMsPerBlock);
	string nrDMsPerThread_s = toStringValue< unsigned int >(nrDMsPerThread);
	string nrPeriodsPerBlock_s = toStringValue< unsigned int >(nrPeriodsPerBlock);
	string nrPeriodsPerThread_s = toStringValue< unsigned int >(nrPeriodsPerThread);
	string nrBinsPerBlock_s = toStringValue< unsigned int >(nrBinsPerBlock);
	string nrBinsPerThread_s = toStringValue< unsigned int >(nrBinsPerThread);

	delete this->code;
	this->code = new string();
	*(this->code) = "__kernel void " + this->name + "(__global const " + this->dataType + " * const restrict samples, __global " + this->dataType + " * const restrict bins, __global unsigned int * const restrict counters) {\n"
	"<%DEFS%>"
	"\n"
	"<%COMPUTE%>"
	"\n"
	"<%STORE%>"
	"}\n";

	string defsTemplate = "const unsigned int DM<%DM_NUM%> = (get_group_id(0) * " + nrDMsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(0) + (<%DM_NUM%> * " + nrDMsPerBlock_s + "));\n"
		"const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + nrPeriodsPerBlock_s + " * " + nrDMsPerThread_s + ") + get_local_id(1) + (<%PERIOD_NUM%> * " + nrPeriodsPerBlock_s + ");\n"
		"const unsigned int bin<%BIN_NUM%> = (get_group_id(2) * " + nrBinsPerBlock_s + " * " + nrBinsPerThread_s + ") + get_local_id(2) + (<%BIN_NUM%> * " + nrBinsPerBlock_s + ");\n"
		"const unsigned int period<%PERIOD_NUM%>Value = (period<%PERIOD_NUM%> + 1) * " + nrBins_s + ";\n"
		"unsigned int foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
		+ this->dataType + " foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
		"const unsigned int pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = counters[(bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n";

	string computeTemplate = "unsigned int sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (bin<%BIN_NUM%> * period<%PERIOD_NUM%>) + bin<%BIN_NUM%> + ((pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / (period<%PERIOD_NUM%> + 1)) * period<%PERIOD_NUM%>Value) + (pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % (period<%PERIOD_NUM%> + 1));\n"
	"if ( (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") == 0 ) {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n"
	"} else {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> = (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> % "+ nrSamplesPerSecond_s + ") - (sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> / "+ nrSamplesPerSecond_s + ");\n"
	"}\n"
	"while ( sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> < " + nrSamplesPerSecond_s + " ) {\n"
	"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += samples[(sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n"
	"foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
	"if ( ((foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) % (period<%PERIOD_NUM%> + 1)) == 0 ) {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> += period<%PERIOD_NUM%>Value;\n"
	"} else {\n"
	"sampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
	"}\n"
	"}\n";

	string storeTemplate = "if ( foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> > 0 ) {\n"
	"const unsigned int outputItem = (bin<%BIN_NUM%> * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>;\n"
	"const "+ this->dataType + " pValue = bins[outputItem];\n"
	+ this->dataType + " addedFraction = 0;"
	"addedFraction = convert_float(foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) / (foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>);\n"
	"foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> /= foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
	"counters[outputItem] = pCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%> + foldedCounterDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
	"bins[outputItem] = (addedFraction * foldedSampleDM<%DM_NUM%>p<%PERIOD_NUM%>b<%BIN_NUM%>) + ((1.0f - addedFraction) * pValue);\n"
	"}\n";
	// End kernel's template

	string * defs = new string();
	string * computes = new string();
	string * stores = new string();
	for ( unsigned int DM = 0; DM < nrDMsPerThread; DM++ ) {
		string * DM_s = toString< unsigned int >(DM);

		for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {
			string * period_s = toString< unsigned int >(period);

			for ( unsigned int bin = 0; bin < nrBinsPerThread; bin++ ) {
				string * bin_s = toString< unsigned int >(bin);
				string * temp = 0;

				temp = replace(&defsTemplate, "<%BIN_NUM%>", *bin_s);
				temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
				temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
				defs->append(*temp);
				delete temp;

				temp = replace(&computeTemplate, "<%BIN_NUM%>", *bin_s);
				temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
				temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
				computes->append(*temp);
				delete temp;

				temp = replace(&storeTemplate, "<%BIN_NUM%>", *bin_s);
				temp = replace(temp, "<%PERIOD_NUM%>", *period_s, true);
				temp = replace(temp, "<%DM_NUM%>", *DM_s, true);
				stores->append(*temp);
				delete temp;

				delete bin_s;
			}

			delete period_s;
		}

		delete DM_s;
	}
	this->code = replace(this->code, "<%DEFS%>", *defs, true);
	this->code = replace(this->code, "<%COMPUTE%>", *computes, true);
	this->code = replace(this->code, "<%STORE%>", *stores, true);
	delete defs;
	delete computes;
	delete stores;

	globalSize = cl::NDRange(observation->getNrDMs() / nrDMsPerThread, observation->getNrPeriods() / nrPeriodsPerThread, observation->getNrBins() / nrBinsPerThread);
	localSize = cl::NDRange(nrDMsPerBlock, nrPeriodsPerBlock, nrBinsPerBlock);

	this->gflop = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * observation->getNrSamplesPerSecond());

	this->compile();
}

template< typename T > void Folding< T >::operator()(CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError) {
	this->setArgument(0, *(input->getDeviceData()));
	this->setArgument(1, *(output->getDeviceData()));
	this->setArgument(2, *(counters->getDeviceData()));

	this->run(globalSize, localSize);
}

template< typename T > inline void Folding< T >::setNrDMsPerBlock(unsigned int DMs) {
	nrDMsPerBlock = DMs;
}

template< typename T > inline void Folding< T >::setNrPeriodsPerBlock(unsigned int periods) {
	nrPeriodsPerBlock = periods;
}

template< typename T > inline void Folding< T >::setNrBinsPerBlock(unsigned int bins) {
	nrBinsPerBlock = bins;
}

template< typename T > inline void Folding< T >::setNrDMsPerThread(unsigned int DMs) {
	nrDMsPerThread = DMs;
}

template< typename T > inline void Folding< T >::setNrPeriodsPerThread(unsigned int periods) {
	nrPeriodsPerThread = periods;
}

template< typename T > inline void Folding< T >::setNrBinsPerThread(unsigned int bins) {
	nrBinsPerThread = bins;
}

template< typename T > inline void Folding< T >::setObservation(Observation< T > * obs) {
	observation = obs;
}

} // PulsarSearch

#endif // FOLDING_HPP
<|endoftext|>


<commit_before>// $Id$
//
// Class to make PicoTracks in AOD/ESD events.
//
// Author: S.Aiola, C.Loizides

#include <TClonesArray.h>
#include <TRandom3.h>
#include "AliAODEvent.h"
#include "AliAODTrack.h"
#include "AliAnalysisManager.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"
#include "AliEmcalPicoTrackMaker.h"
#include "AliLog.h"
#include "AliPicoTrack.h"
#include "AliVTrack.h"

ClassImp(AliEmcalPicoTrackMaker)

//________________________________________________________________________
AliEmcalPicoTrackMaker::AliEmcalPicoTrackMaker() :
  AliAnalysisTaskSE("AliEmcalPicoTrackMaker"),
  fTracksOutName("PicoTracks"),
  fTracksInName("tracks"),
  fMinTrackPt(0),
  fMaxTrackPt(1000),
  fMinTrackEta(-10),
  fMaxTrackEta(10),
  fMinTrackPhi(-10),
  fMaxTrackPhi(10),
  fTrackEfficiency(1),
  fTracksIn(0),
  fTracksOut(0)
{
  // Constructor.

  fAODfilterBits[0] = -1;
  fAODfilterBits[1] = -1;
}

//________________________________________________________________________
AliEmcalPicoTrackMaker::AliEmcalPicoTrackMaker(const char *name) :
  AliAnalysisTaskSE(name),
  fTracksOutName("PicoTracks"),
  fTracksInName("tracks"),
  fMinTrackPt(0),
  fMaxTrackPt(1000),
  fMinTrackEta(-10),
  fMaxTrackEta(10),
  fMinTrackPhi(-10),
  fMaxTrackPhi(10),
  fTrackEfficiency(1),
  fTracksIn(0),
  fTracksOut(0)
{
  // Constructor.

  fAODfilterBits[0] = -1;
  fAODfilterBits[1] = -1;
  fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks";
}

//________________________________________________________________________
AliEmcalPicoTrackMaker::~AliEmcalPicoTrackMaker()
{
  // Destructor.
}

//________________________________________________________________________
void AliEmcalPicoTrackMaker::UserCreateOutputObjects()
{
  // Create my user objects.

  fTracksOut = new TClonesArray("AliPicoTrack");
  fTracksOut->SetName(fTracksOutName);
}

//________________________________________________________________________
void AliEmcalPicoTrackMaker::UserExec(Option_t *)
{
  // Main loop, called for each event.

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
  if (!am) {
    AliError("Manager zero, returning");
    return;
  }

  // retrieve tracks from input.
  if (!fTracksIn) {
    fTracksIn = dynamic_cast<TClonesArray*>(InputEvent()->FindListObject(fTracksInName));
    if (!fTracksIn) {
      AliError(Form("Could not retrieve tracks %s!", fTracksInName.Data()));
      return;
    }
    if (!fTracksIn->GetClass()->GetBaseClass("AliVParticle")) {
      AliError(Form("%s: Collection %s does not contain AliVParticle objects!", GetName(), fTracksInName.Data()));
      return;
    }
  }

  // add tracks to event if not yet there
  fTracksOut->Delete();
  if (!(InputEvent()->FindListObject(fTracksOutName))) {
    InputEvent()->AddObject(fTracksOut);
  }

  // loop over tracks
  const Int_t Ntracks = fTracksIn->GetEntriesFast();
  for (Int_t iTracks = 0, nacc = 0; iTracks < Ntracks; ++iTracks) {

    AliVTrack *track = static_cast<AliVTrack*>(fTracksIn->At(iTracks));

    if (!track)
      continue;

    if (track->Pt() > fMaxTrackPt || track->Pt() < fMinTrackPt)
      continue;

    if (track->Eta() < fMinTrackEta || track->Eta() > fMaxTrackEta ||
	track->Phi() < fMinTrackPhi || track->Phi() > fMaxTrackPhi)
      continue;

    if (fTrackEfficiency < 1) {
      Double_t r = gRandom->Rndm();
      if (fTrackEfficiency < r)
	continue;
    }

    Bool_t isEmc = kFALSE;
    if (TMath::Abs(track->GetTrackEtaOnEMCal()) < 0.75 &&
	track->GetTrackPhiOnEMCal() > 70 * TMath::DegToRad() &&
	track->GetTrackPhiOnEMCal() < 190 * TMath::DegToRad())
      isEmc = kTRUE;

    AliPicoTrack *picotrack = new ((*fTracksOut)[nacc]) AliPicoTrack(track->Pt(),
									 track->Eta(),
									 track->Phi(),
									 track->Charge(),
									 track->GetLabel(),
									 AliPicoTrack::GetTrackType(track),
									 track->GetTrackEtaOnEMCal(),
									 track->GetTrackPhiOnEMCal(),
									 track->GetTrackPtOnEMCal(),
									 isEmc);
    picotrack->SetTrack(track);
    ++nacc;
  }
}
<commit_msg>cosmetics<commit_after>// $Id$
//
// Class to make PicoTracks in AOD/ESD events.
//
// Author: S.Aiola, C.Loizides

#include <TClonesArray.h>
#include <TRandom3.h>
#include "AliAODEvent.h"
#include "AliAODTrack.h"
#include "AliAnalysisManager.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"
#include "AliEmcalPicoTrackMaker.h"
#include "AliLog.h"
#include "AliPicoTrack.h"
#include "AliVTrack.h"

ClassImp(AliEmcalPicoTrackMaker)

//________________________________________________________________________
AliEmcalPicoTrackMaker::AliEmcalPicoTrackMaker() :
  AliAnalysisTaskSE("AliEmcalPicoTrackMaker"),
  fTracksOutName("PicoTracks"),
  fTracksInName("tracks"),
  fMinTrackPt(0),
  fMaxTrackPt(1000),
  fMinTrackEta(-10),
  fMaxTrackEta(10),
  fMinTrackPhi(-10),
  fMaxTrackPhi(10),
  fTrackEfficiency(1),
  fTracksIn(0),
  fTracksOut(0)
{
  // Constructor.

  fAODfilterBits[0] = -1;
  fAODfilterBits[1] = -1;
}

//________________________________________________________________________
AliEmcalPicoTrackMaker::AliEmcalPicoTrackMaker(const char *name) :
  AliAnalysisTaskSE(name),
  fTracksOutName("PicoTracks"),
  fTracksInName("tracks"),
  fMinTrackPt(0),
  fMaxTrackPt(1000),
  fMinTrackEta(-10),
  fMaxTrackEta(10),
  fMinTrackPhi(-10),
  fMaxTrackPhi(10),
  fTrackEfficiency(1),
  fTracksIn(0),
  fTracksOut(0)
{
  // Constructor.

  fAODfilterBits[0] = -1;
  fAODfilterBits[1] = -1;
  fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks";
}

//________________________________________________________________________
AliEmcalPicoTrackMaker::~AliEmcalPicoTrackMaker()
{
  // Destructor.
}

//________________________________________________________________________
void AliEmcalPicoTrackMaker::UserCreateOutputObjects()
{
  // Create my user objects.

  fTracksOut = new TClonesArray("AliPicoTrack");
  fTracksOut->SetName(fTracksOutName);
}

//________________________________________________________________________
void AliEmcalPicoTrackMaker::UserExec(Option_t *)
{
  // Main loop, called for each event.

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
  if (!am) {
    AliError("Manager zero, returning");
    return;
  }

  // retrieve tracks from input.
  if (!fTracksIn) {
    fTracksIn = dynamic_cast<TClonesArray*>(InputEvent()->FindListObject(fTracksInName));
    if (!fTracksIn) {
      AliError(Form("Could not retrieve tracks %s!", fTracksInName.Data()));
      return;
    }
    if (!fTracksIn->GetClass()->GetBaseClass("AliVParticle")) {
      AliError(Form("%s: Collection %s does not contain AliVParticle objects!", GetName(), fTracksInName.Data()));
      return;
    }
  }

  // add tracks to event if not yet there
  fTracksOut->Delete();
  if (!(InputEvent()->FindListObject(fTracksOutName))) {
    InputEvent()->AddObject(fTracksOut);
  }

  // loop over tracks
  const Int_t Ntracks = fTracksIn->GetEntriesFast();
  for (Int_t iTracks = 0, nacc = 0; iTracks < Ntracks; ++iTracks) {

    AliVTrack *track = static_cast<AliVTrack*>(fTracksIn->At(iTracks));

    if (!track)
      continue;

    if (track->Pt() > fMaxTrackPt || track->Pt() < fMinTrackPt)
      continue;

    if (track->Eta() < fMinTrackEta || track->Eta() > fMaxTrackEta ||
	track->Phi() < fMinTrackPhi || track->Phi() > fMaxTrackPhi)
      continue;

    if (fTrackEfficiency < 1) {
      Double_t r = gRandom->Rndm();
      if (fTrackEfficiency < r)
	continue;
    }

    Bool_t isEmc = kFALSE;
    if (TMath::Abs(track->GetTrackEtaOnEMCal()) < 0.75 &&
	track->GetTrackPhiOnEMCal() > 70 * TMath::DegToRad() &&
	track->GetTrackPhiOnEMCal() < 190 * TMath::DegToRad())
      isEmc = kTRUE;

    AliPicoTrack *picotrack = new ((*fTracksOut)[nacc]) AliPicoTrack(track->Pt(),
								     track->Eta(),
								     track->Phi(),
								     track->Charge(),
								     track->GetLabel(),
								     AliPicoTrack::GetTrackType(track),
								     track->GetTrackEtaOnEMCal(),
								     track->GetTrackPhiOnEMCal(),
								     track->GetTrackPtOnEMCal(),
								     isEmc);
    picotrack->SetTrack(track);
    ++nacc;
  }
}
<|endoftext|>