<commit_before>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "deferred_shading_demo/deferred_shading_demo.h"

#include "deferred_shading_demo/shader_constants.h"

#include <DirectXColors.h>
#include <sstream>

namespace DeferredShadingDemo {

void DeferredShadingDemo::DrawFrame(double deltaTime) {
	RenderMainPass();
	RenderHUD();

	uint syncInterval = m_vsync ? 1 : 0;
	m_swapChain->Present(syncInterval, 0);
}

void DeferredShadingDemo::RenderMainPass() {
	// Clear the material list
	m_frameMaterialList.clear();

	// Bind the gbufferRTVs and depth/stencil view to the pipeline.
	m_immediateContext->OMSetRenderTargets(2, &m_gBufferRTVs[0], m_depthStencilBuffer->GetDepthStencil());

	// Clear the Render Targets and DepthStencil
	m_immediateContext->ClearRenderTargetView(m_renderTargetView, DirectX::Colors::LightGray);
	for (auto gbufferRTV : m_gBufferRTVs) {
		m_immediateContext->ClearRenderTargetView(gbufferRTV, DirectX::Colors::Black);
	}
	m_immediateContext->ClearDepthStencilView(m_depthStencilBuffer->GetDepthStencil(), D3D11_CLEAR_DEPTH, 0.0f, 0);

	// Set States
	m_immediateContext->PSSetSamplers(0, 1, &m_diffuseSampleState);
	float blendFactor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
	m_immediateContext->OMSetBlendState(m_blendStates.BlendDisabled(), blendFactor, 0xFFFFFFFF);
	m_immediateContext->OMSetDepthStencilState(m_depthStencilStates.ReverseDepthWriteEnabled(), 0);
	ID3D11RasterizerState *rasterState = m_wireframe ? m_rasterizerStates.Wireframe() : m_rasterizerStates.BackFaceCull();
	m_immediateContext->RSSetState(rasterState);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	m_immediateContext->VSSetShader(m_gbufferVertexShader, nullptr, 0);
	m_immediateContext->PSSetShader(m_gbufferPixelShader, nullptr, 0);

	m_immediateContext->IASetInputLayout(m_gBufferInputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Fetch the transpose matricies
	DirectX::XMMATRIX worldMatrix = m_worldViewProj.world;
	DirectX::XMMATRIX viewMatrix = m_worldViewProj.view;
	DirectX::XMMATRIX projectionMatrix = m_worldViewProj.projection;

	uint materialIndex = 0;

	// Cache the matrix multiplication
	DirectX::XMMATRIX viewProj = viewMatrix * projectionMatrix;

	for (uint i = 0; i < m_models.size(); ++i) {
		m_frameMaterialList.push_back(m_models[i].GetSubsetMaterial(0));

		DirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewProj);

		SetGBufferShaderObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_frameMaterialList.size() - 1);

		// Draw the models
		m_models[i].DrawSubset(m_immediateContext);
	}

	// Cleanup (aka make the runtime happy)
	m_immediateContext->OMSetRenderTargets(0, 0, 0);

	// Final gather pass
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);

	// Full screen triangle setup
	m_immediateContext->IASetInputLayout(m_fullscreenTriangleInputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	m_immediateContext->VSSetShader(m_fullscreenTriangleVertexShader, nullptr, 0);
	m_immediateContext->GSSetShader(0, 0, 0);
	m_immediateContext->PSSetShader(m_noCullFinalGatherPixelShader, nullptr, 0);

	m_immediateContext->RSSetState(m_rasterizerStates.NoCull());

	DirectX::XMMATRIX invViewProj = DirectX::XMMatrixInverse(nullptr, viewProj);
	SetNoCullFinalGatherShaderConstants(DirectX::XMMatrixTranspose(projectionMatrix), DirectX::XMMatrixTranspose(invViewProj));

	m_immediateContext->PSSetShaderResources(0, 3, &m_gBufferSRVs.front());

	// Set light buffers
	SetLightBuffers();

	ID3D11ShaderResourceView *srvArray[2];
	srvArray[0] = m_pointLightBuffer->GetShaderResource();
	//srvArray[1] = m_spotLightBuffer->GetShaderResource();
	m_immediateContext->PSSetShaderResources(3, 1, srvArray);

	// Set material list
	SetMaterialList();

	m_fullScreenQuad.DrawSubset(m_immediateContext);

	// Cleanup (aka make the runtime happy)
	m_immediateContext->VSSetShader(0, 0, 0);
	m_immediateContext->GSSetShader(0, 0, 0);
	m_immediateContext->PSSetShader(0, 0, 0);
	m_immediateContext->OMSetRenderTargets(0, 0, 0);
	ID3D11ShaderResourceView* nullSRV[6] = {0, 0, 0, 0, 0, 0};
	m_immediateContext->VSSetShaderResources(0, 6, nullSRV);
	m_immediateContext->PSSetShaderResources(0, 6, nullSRV);
	//m_immediateContext->CSSetShaderResources(0, 8, nullSRV);
	//ID3D11UnorderedAccessView *nullUAV[1] = {0};
	//m_immediateContext->CSSetUnorderedAccessViews(0, 1, nullUAV, 0);
}

void DeferredShadingDemo::SetGBufferShaderObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, uint materialIndex) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_gBufferVertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	GBufferVertexShaderObjectConstants *vertexShaderObjectConstants = static_cast<GBufferVertexShaderObjectConstants *>(mappedResource.pData);
	vertexShaderObjectConstants->World = worldMatrix;
	vertexShaderObjectConstants->WorldViewProj = worldViewProjMatrix;

	m_immediateContext->Unmap(m_gBufferVertexShaderObjectConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(1, 1, &m_gBufferVertexShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_gBufferPixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	GBufferPixelShaderObjectConstants *pixelShaderObjectConstants = static_cast<GBufferPixelShaderObjectConstants *>(mappedResource.pData);
	pixelShaderObjectConstants->MaterialIndex = materialIndex;

	m_immediateContext->Unmap(m_gBufferPixelShaderObjectConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(1, 1, &m_gBufferPixelShaderObjectConstantsBuffer);
}

void DeferredShadingDemo::SetNoCullFinalGatherShaderConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &invViewProjMatrix) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_noCullFinalGatherPixelShaderConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	NoCullFinalGatherPixelShaderFrameConstants *pixelShaderFrameConstants = static_cast<NoCullFinalGatherPixelShaderFrameConstants *>(mappedResource.pData);
	pixelShaderFrameConstants->gProjection = projMatrix;
	pixelShaderFrameConstants->gInvViewProjection = invViewProjMatrix;
	pixelShaderFrameConstants->gDirectionalLight = m_directionalLight;
	pixelShaderFrameConstants->gEyePosition = m_camera.GetCameraPosition();

	m_immediateContext->Unmap(m_noCullFinalGatherPixelShaderConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(0, 1, &m_noCullFinalGatherPixelShaderConstantsBuffer);
}

void DeferredShadingDemo::SetLightBuffers() {
	uint numPointLights = m_pointLights.size();
	//uint numSpotLights = m_gameStateManager->SpotLights.size();

	assert(m_pointLightBuffer->NumElements() == numPointLights);
	//assert(m_spotLightBuffer->NumElements() == numSpotLights);

	Common::PointLight *pointLightArray = m_pointLightBuffer->MapDiscard(m_immediateContext);
	for (unsigned int i = 0; i < m_pointLights.size(); ++i) {
		pointLightArray[i] = m_pointLights[i];
	}
	m_pointLightBuffer->Unmap(m_immediateContext);

	//Common::SpotLight *spotLightArray = m_spotLightBuffer->MapDiscard(m_immediateContext);
	//for (unsigned int i = 0; i < m_gameStateManager->SpotLights.size(); ++i) {
	//	spotLightArray[i] = m_gameStateManager->SpotLights[i];
	//}
	//m_pointLightBuffer->Unmap(m_immediateContext);
}

void DeferredShadingDemo::SetMaterialList() {
	uint numMaterials = m_frameMaterialList.size();
	assert(numMaterials <= kMaxMaterialsPerFrame);

	Common::BlinnPhongMaterial *materialArray = m_frameMaterialListBuffer->MapDiscard(m_immediateContext);
	for (uint i = 0; i < numMaterials; ++i) {
		materialArray[i] = m_frameMaterialList[i];
	}
	m_frameMaterialListBuffer->Unmap(m_immediateContext);

	ID3D11ShaderResourceView *view = m_frameMaterialListBuffer->GetShaderResource();
	m_immediateContext->PSSetShaderResources(5, 1, &view);
}

void DeferredShadingDemo::RenderHUD() {
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);

	m_spriteRenderer.Begin(m_immediateContext, Common::SpriteRenderer::Point);
	std::wostringstream stream;
	stream << L"FPS: " << m_fps << L"\nFrame Time: " << m_frameTime << L" (ms)";

	DirectX::XMFLOAT4X4 transform{1, 0, 0, 0,
		0, 1, 0, 0,
		0, 0, 1, 0,
		25, 25, 0, 1};
	m_spriteRenderer.RenderText(m_timesNewRoman12Font, stream.str().c_str(), transform, DirectX::XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f) /* Yellow */);
	m_spriteRenderer.End();

	TwDraw();

	// Cleanup (aka make the runtime happy)
	m_immediateContext->OMSetRenderTargets(0, 0, 0);
}

} // End of namespace DeferredShadingDemo
<commit_msg>DEFERRED_SHADING_DEMO: Move the backbuffer RenderTarget clear down to after it's bound to the pipeline<commit_after>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "deferred_shading_demo/deferred_shading_demo.h"

#include "deferred_shading_demo/shader_constants.h"

#include <DirectXColors.h>
#include <sstream>

namespace DeferredShadingDemo {

void DeferredShadingDemo::DrawFrame(double deltaTime) {
	RenderMainPass();
	RenderHUD();

	uint syncInterval = m_vsync ? 1 : 0;
	m_swapChain->Present(syncInterval, 0);
}

void DeferredShadingDemo::RenderMainPass() {
	// Clear the material list
	m_frameMaterialList.clear();

	// Bind the gbufferRTVs and depth/stencil view to the pipeline.
	m_immediateContext->OMSetRenderTargets(2, &m_gBufferRTVs[0], m_depthStencilBuffer->GetDepthStencil());

	// Clear the Render Targets and DepthStencil
	for (auto gbufferRTV : m_gBufferRTVs) {
		m_immediateContext->ClearRenderTargetView(gbufferRTV, DirectX::Colors::Black);
	}
	m_immediateContext->ClearDepthStencilView(m_depthStencilBuffer->GetDepthStencil(), D3D11_CLEAR_DEPTH, 0.0f, 0);

	// Set States
	m_immediateContext->PSSetSamplers(0, 1, &m_diffuseSampleState);
	float blendFactor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
	m_immediateContext->OMSetBlendState(m_blendStates.BlendDisabled(), blendFactor, 0xFFFFFFFF);
	m_immediateContext->OMSetDepthStencilState(m_depthStencilStates.ReverseDepthWriteEnabled(), 0);
	ID3D11RasterizerState *rasterState = m_wireframe ? m_rasterizerStates.Wireframe() : m_rasterizerStates.BackFaceCull();
	m_immediateContext->RSSetState(rasterState);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	m_immediateContext->VSSetShader(m_gbufferVertexShader, nullptr, 0);
	m_immediateContext->PSSetShader(m_gbufferPixelShader, nullptr, 0);

	m_immediateContext->IASetInputLayout(m_gBufferInputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Fetch the transpose matricies
	DirectX::XMMATRIX worldMatrix = m_worldViewProj.world;
	DirectX::XMMATRIX viewMatrix = m_worldViewProj.view;
	DirectX::XMMATRIX projectionMatrix = m_worldViewProj.projection;

	uint materialIndex = 0;

	// Cache the matrix multiplication
	DirectX::XMMATRIX viewProj = viewMatrix * projectionMatrix;

	for (uint i = 0; i < m_models.size(); ++i) {
		m_frameMaterialList.push_back(m_models[i].GetSubsetMaterial(0));

		DirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewProj);

		SetGBufferShaderObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_frameMaterialList.size() - 1);

		// Draw the models
		m_models[i].DrawSubset(m_immediateContext);
	}

	// Cleanup (aka make the runtime happy)
	m_immediateContext->OMSetRenderTargets(0, 0, 0);

	// Final gather pass
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);
	m_immediateContext->ClearRenderTargetView(m_renderTargetView, DirectX::Colors::LightGray);

	// Full screen triangle setup
	m_immediateContext->IASetInputLayout(m_fullscreenTriangleInputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	m_immediateContext->VSSetShader(m_fullscreenTriangleVertexShader, nullptr, 0);
	m_immediateContext->GSSetShader(0, 0, 0);
	m_immediateContext->PSSetShader(m_noCullFinalGatherPixelShader, nullptr, 0);

	m_immediateContext->RSSetState(m_rasterizerStates.NoCull());

	DirectX::XMMATRIX invViewProj = DirectX::XMMatrixInverse(nullptr, viewProj);
	SetNoCullFinalGatherShaderConstants(DirectX::XMMatrixTranspose(projectionMatrix), DirectX::XMMatrixTranspose(invViewProj));

	m_immediateContext->PSSetShaderResources(0, 3, &m_gBufferSRVs.front());

	// Set light buffers
	SetLightBuffers();

	ID3D11ShaderResourceView *srvArray[2];
	srvArray[0] = m_pointLightBuffer->GetShaderResource();
	//srvArray[1] = m_spotLightBuffer->GetShaderResource();
	m_immediateContext->PSSetShaderResources(3, 1, srvArray);

	// Set material list
	SetMaterialList();

	m_fullScreenQuad.DrawSubset(m_immediateContext);

	// Cleanup (aka make the runtime happy)
	m_immediateContext->VSSetShader(0, 0, 0);
	m_immediateContext->GSSetShader(0, 0, 0);
	m_immediateContext->PSSetShader(0, 0, 0);
	m_immediateContext->OMSetRenderTargets(0, 0, 0);
	ID3D11ShaderResourceView* nullSRV[6] = {0, 0, 0, 0, 0, 0};
	m_immediateContext->VSSetShaderResources(0, 6, nullSRV);
	m_immediateContext->PSSetShaderResources(0, 6, nullSRV);
	//m_immediateContext->CSSetShaderResources(0, 8, nullSRV);
	//ID3D11UnorderedAccessView *nullUAV[1] = {0};
	//m_immediateContext->CSSetUnorderedAccessViews(0, 1, nullUAV, 0);
}

void DeferredShadingDemo::SetGBufferShaderObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, uint materialIndex) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_gBufferVertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	GBufferVertexShaderObjectConstants *vertexShaderObjectConstants = static_cast<GBufferVertexShaderObjectConstants *>(mappedResource.pData);
	vertexShaderObjectConstants->World = worldMatrix;
	vertexShaderObjectConstants->WorldViewProj = worldViewProjMatrix;

	m_immediateContext->Unmap(m_gBufferVertexShaderObjectConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(1, 1, &m_gBufferVertexShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_gBufferPixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	GBufferPixelShaderObjectConstants *pixelShaderObjectConstants = static_cast<GBufferPixelShaderObjectConstants *>(mappedResource.pData);
	pixelShaderObjectConstants->MaterialIndex = materialIndex;

	m_immediateContext->Unmap(m_gBufferPixelShaderObjectConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(1, 1, &m_gBufferPixelShaderObjectConstantsBuffer);
}

void DeferredShadingDemo::SetNoCullFinalGatherShaderConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &invViewProjMatrix) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_noCullFinalGatherPixelShaderConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	NoCullFinalGatherPixelShaderFrameConstants *pixelShaderFrameConstants = static_cast<NoCullFinalGatherPixelShaderFrameConstants *>(mappedResource.pData);
	pixelShaderFrameConstants->gProjection = projMatrix;
	pixelShaderFrameConstants->gInvViewProjection = invViewProjMatrix;
	pixelShaderFrameConstants->gDirectionalLight = m_directionalLight;
	pixelShaderFrameConstants->gEyePosition = m_camera.GetCameraPosition();

	m_immediateContext->Unmap(m_noCullFinalGatherPixelShaderConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(0, 1, &m_noCullFinalGatherPixelShaderConstantsBuffer);
}

void DeferredShadingDemo::SetLightBuffers() {
	uint numPointLights = m_pointLights.size();
	//uint numSpotLights = m_gameStateManager->SpotLights.size();

	assert(m_pointLightBuffer->NumElements() == numPointLights);
	//assert(m_spotLightBuffer->NumElements() == numSpotLights);

	Common::PointLight *pointLightArray = m_pointLightBuffer->MapDiscard(m_immediateContext);
	for (unsigned int i = 0; i < m_pointLights.size(); ++i) {
		pointLightArray[i] = m_pointLights[i];
	}
	m_pointLightBuffer->Unmap(m_immediateContext);

	//Common::SpotLight *spotLightArray = m_spotLightBuffer->MapDiscard(m_immediateContext);
	//for (unsigned int i = 0; i < m_gameStateManager->SpotLights.size(); ++i) {
	//	spotLightArray[i] = m_gameStateManager->SpotLights[i];
	//}
	//m_pointLightBuffer->Unmap(m_immediateContext);
}

void DeferredShadingDemo::SetMaterialList() {
	uint numMaterials = m_frameMaterialList.size();
	assert(numMaterials <= kMaxMaterialsPerFrame);

	Common::BlinnPhongMaterial *materialArray = m_frameMaterialListBuffer->MapDiscard(m_immediateContext);
	for (uint i = 0; i < numMaterials; ++i) {
		materialArray[i] = m_frameMaterialList[i];
	}
	m_frameMaterialListBuffer->Unmap(m_immediateContext);

	ID3D11ShaderResourceView *view = m_frameMaterialListBuffer->GetShaderResource();
	m_immediateContext->PSSetShaderResources(5, 1, &view);
}

void DeferredShadingDemo::RenderHUD() {
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);

	m_spriteRenderer.Begin(m_immediateContext, Common::SpriteRenderer::Point);
	std::wostringstream stream;
	stream << L"FPS: " << m_fps << L"\nFrame Time: " << m_frameTime << L" (ms)";

	DirectX::XMFLOAT4X4 transform{1, 0, 0, 0,
		0, 1, 0, 0,
		0, 0, 1, 0,
		25, 25, 0, 1};
	m_spriteRenderer.RenderText(m_timesNewRoman12Font, stream.str().c_str(), transform, DirectX::XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f) /* Yellow */);
	m_spriteRenderer.End();

	TwDraw();

	// Cleanup (aka make the runtime happy)
	m_immediateContext->OMSetRenderTargets(0, 0, 0);
}

} // End of namespace DeferredShadingDemo
<|endoftext|>


<commit_before>// coding: utf-8
/* Copyright (c) 2014, Electronic Kiwi
* All Rights Reserved.
*
* The file is part of the xpcc-playground and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/

#include <xpcc/architecture.hpp>
#include <xpcc/debug/logger.hpp>
#include "../../xpcc/examples/stm32f3_discovery/stm32f3_discovery.hpp"

// Create an IODeviceWrapper around the Uart Peripheral we want to use
xpcc::IODeviceWrapper< Usart2 > loggerDevice;

// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::error(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

#include <xpcc_git_info.hpp>
#include <xpcc_project_info.hpp>

#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/periodic_timer.hpp>
#include <xpcc/processing/protothread.hpp>
#include "../cc1101/cc1101.hpp"

class MainThread : public xpcc::pt::Protothread
{
public:
	MainThread() : blinkTimer(500)
	{
	}

	/// Needs to be called as often as possible.
	bool
	run()
	{
		if(blinkTimer.isExpired()) {
			LedSouth::toggle();
		}

		PT_BEGIN();

		// try to initialize the device
		static Radio::InitializeError e;
		e = PT_CALL(radio.initialize(this));
		if(e != Radio::InitializeError::None) {
			XPCC_LOG_ERROR << XPCC_FILE_INFO;
			XPCC_LOG_ERROR << "Error trying to initialize the cc1101: ";
			XPCC_LOG_ERROR << Radio::enumToString(e) << xpcc::endl;
		} else {
			XPCC_LOG_DEBUG << XPCC_FILE_INFO << "Initialized cc1101." << xpcc::endl;
		}

		// main loop
		while(true){
			PT_YIELD();
		}

		PT_END();
	}

public:
	struct CC1101Config {
		typedef SpiSimpleMaster3 SpiMaster;
		typedef GpioOutputA15    Cs;
		typedef GpioInputB4      Miso;
		typedef GpioD6           Gdo0;
		typedef GpioD4           Gdo2;
	};

private:
	typedef xpcc::radio::CC1101<CC1101Config> Radio;
	xpcc::Timeout<> timer;
	xpcc::PeriodicTimer<> blinkTimer;
	Radio radio;
};

MainThread mainThread;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();
	xpcc::cortex::SysTickTimer::enable();

	LedNorth::setOutput(xpcc::Gpio::Low);
	LedSouth::setOutput(xpcc::Gpio::Low);

	// Initialize Usart
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx);
	Usart2::initialize<defaultSystemClock, 115200>(10);

	// Print project information
	XPCC_LOG_INFO << "[log-start] " XPCC_PROJECT_NAME ": " __DATE__ "@" __TIME__ << xpcc::endl;
	XPCC_LOG_INFO << "[git] " XPCC_GIT_SHA_ABBR " " XPCC_GIT_SUBJECT << xpcc::endl;
	XPCC_LOG_INFO << "[git] " XPCC_GIT_AUTHOR "<" XPCC_GIT_AUTHOR_EMAIL ">" << xpcc::endl;

	// Initialize Spi
	MainThread::CC1101Config::Cs::setOutput(xpcc::Gpio::High);
	MainThread::CC1101Config::Miso::connect(SpiSimpleMaster3::Miso);
	GpioOutputB5::connect(SpiSimpleMaster3::Mosi);
	GpioOutputB3::connect(SpiSimpleMaster3::Sck);
	SpiSimpleMaster3::initialize<defaultSystemClock, 1125 * kHz1>();
	//SpiSimpleMaster3::initialize<defaultSystemClock, 140625>();

	while (1)
	{
		mainThread.run();
	}

	return 0;
}
<commit_msg>CC1101 Test: can configure Gdo0 as high impedance.<commit_after>// coding: utf-8
/* Copyright (c) 2014, Electronic Kiwi
* All Rights Reserved.
*
* The file is part of the xpcc-playground and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/

#include <xpcc/architecture.hpp>
#include <xpcc/debug/logger.hpp>
#include "../../xpcc/examples/stm32f3_discovery/stm32f3_discovery.hpp"

// Create an IODeviceWrapper around the Uart Peripheral we want to use
xpcc::IODeviceWrapper< Usart2 > loggerDevice;

// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::error(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

#include <xpcc_git_info.hpp>
#include <xpcc_project_info.hpp>

#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/periodic_timer.hpp>
#include <xpcc/processing/protothread.hpp>
#include "../cc1101/cc1101.hpp"

class MainThread : public xpcc::pt::Protothread
{
public:
	MainThread() : blinkTimer(500)
	{
	}

	/// Needs to be called as often as possible.
	bool
	run()
	{
		if(blinkTimer.isExpired()) {
			LedSouth::toggle();
		}

		PT_BEGIN();

		// try to initialize the device
		static Radio::InitializeError e;
		e = PT_CALL(radio.initialize(this));
		if(e != Radio::InitializeError::None) {
			XPCC_LOG_ERROR << XPCC_FILE_INFO;
			XPCC_LOG_ERROR << "Error trying to initialize the cc1101: ";
			XPCC_LOG_ERROR << Radio::enumToString(e) << xpcc::endl;
		} else {
			XPCC_LOG_DEBUG << XPCC_FILE_INFO << "Initialized cc1101." << xpcc::endl;
		}
		// Configure Gdo0 as high impedance
		PT_CALL(radio.configureGdo(this,
			Radio::Gdo::Gdo0,
			Radio::GdoInverted::No,
			Radio::GdoSignalSelection::HighImpedance));

		// main loop
		while(true){
			PT_YIELD();
		}

		PT_END();
	}

public:
	struct CC1101Config {
		typedef SpiSimpleMaster3 SpiMaster;
		typedef GpioOutputA15    Cs;
		typedef GpioInputB4      Miso;
		typedef GpioInputD6      Gdo0;
		typedef GpioInputD4      Gdo2;
	};

private:
	typedef xpcc::radio::CC1101<CC1101Config> Radio;
	xpcc::Timeout<> timer;
	xpcc::PeriodicTimer<> blinkTimer;
	Radio radio;
};

MainThread mainThread;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();
	xpcc::cortex::SysTickTimer::enable();

	LedNorth::setOutput(xpcc::Gpio::Low);
	LedSouth::setOutput(xpcc::Gpio::Low);

	// Initialize Usart
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx);
	Usart2::initialize<defaultSystemClock, 115200>(10);

	// Print project information
	XPCC_LOG_INFO << "[log-start] " XPCC_PROJECT_NAME ": " __DATE__ "@" __TIME__ << xpcc::endl;
	XPCC_LOG_INFO << "[git] " XPCC_GIT_SHA_ABBR " " XPCC_GIT_SUBJECT << xpcc::endl;
	XPCC_LOG_INFO << "[git] " XPCC_GIT_AUTHOR "<" XPCC_GIT_AUTHOR_EMAIL ">" << xpcc::endl;

	// Initialize Spi
	MainThread::CC1101Config::Cs::setOutput(xpcc::Gpio::High);
	MainThread::CC1101Config::Miso::connect(SpiSimpleMaster3::Miso);
	GpioOutputB5::connect(SpiSimpleMaster3::Mosi);
	GpioOutputB3::connect(SpiSimpleMaster3::Sck);
	SpiSimpleMaster3::initialize<defaultSystemClock, 1125 * kHz1>();
	//SpiSimpleMaster3::initialize<defaultSystemClock, 140625>();

	// Initialize Gdos
	MainThread::CC1101Config::Gdo0::setInput();
	MainThread::CC1101Config::Gdo2::setInput();

	while (1)
	{
		mainThread.run();
	}

	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2015 Esri.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <QSettings>
#include <QGuiApplication>
#include <QQuickView>
#include <QCommandLineParser>
#include <QDir>
#include <QQmlEngine>

#define STRINGIZE(x) #x
#define QUOTE(x) STRINGIZE(x)

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

#ifdef Q_OS_WIN
  // Force usage of OpenGL ES through ANGLE on Windows
  QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
#endif

  // Intialize application view
  QQuickView view;
  view.setResizeMode(QQuickView::SizeRootObjectToView);

  // Add the import Path
  view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
  // Add the Runtime and Extras path
  view.engine()->addImportPath(QUOTE(ARCGIS_RUNTIME_IMPORT_PATH));
  // Add the Toolkit path
  view.engine()->addImportPath(QUOTE(ARCGIS_TOOLKIT_IMPORT_PATH));

  // Set the source
  view.setSource(QUrl("qrc:/Samples/Layers/RasterLayerFile/RasterLayerFile.qml"));

  view.show();

  return app.exec();
}
<commit_msg>adding linux replace logic<commit_after>// Copyright 2015 Esri.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <QSettings>
#include <QGuiApplication>
#include <QQuickView>
#include <QCommandLineParser>
#include <QDir>
#include <QQmlEngine>

#define STRINGIZE(x) #x
#define QUOTE(x) STRINGIZE(x)

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

#ifdef Q_OS_WIN
  // Force usage of OpenGL ES through ANGLE on Windows
  QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
#endif

  // Intialize application view
  QQuickView view;
  view.setResizeMode(QQuickView::SizeRootObjectToView);

  QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
  QString arcGISToolkitImportPath = QUOTE(ARCGIS_TOOLKIT_IMPORT_PATH);

#if defined(LINUX_PLATFORM_REPLACEMENT)
  // on some linux platforms the string 'linux' is replaced with 1
  // fix the replacement paths which were created
  QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT);
  arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive);
  arcGISToolkitImportPath = arcGISToolkitImportPath.replace(replaceString, "linux", Qt::CaseSensitive);
#endif

  // Add the Runtime and Extras path
  view.engine()->addImportPath(arcGISRuntimeImportPath);
  // Add the Toolkit path
  view.engine()->addImportPath(arcGISToolkitImportPath);

  // Set the source
  view.setSource(QUrl("qrc:/Samples/Layers/RasterLayerFile/RasterLayerFile.qml"));

  view.show();

  return app.exec();
}
<|endoftext|>


<commit_before>//
// This macro add an analysis task for computing efficiency.
// It will have as output an AliCFContainer with several steps:
//
//  0) all resonances in MC which decay in the pair specified
//  1) subset of (0) whose daughters are in acceptance
//  2) subset of (1) whose daughters satisfy quality track cuts (covariance, chi square && nTPCclusters)
//  3) subset of (2) whose daughters satisfy primary track cuts (nsigma to vertex, no kink daughters)
//  4) subset of (3) whose daughters satisty the BB TPC compatibility cut at 3 sigma
//
Bool_t AddAnalysisTaskRsnEff
(
  Bool_t      useBB    = kFALSE,
  Double_t    sigmaTPC = 0.065,
  const char *outFile  = "eff"
)
{
  // retrieve analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // common suffixes
  TString suf[2];
  suf[0] = "nopid";
  suf[1] = "pid";

  // create task
  AliRsnAnalysisEffSE *task[2];
  task[0] = new AliRsnAnalysisEffSE("EffNoPID");
  task[1] = new AliRsnAnalysisEffSE("EffPID");

  // set prior probabilities for PID
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->SetPriorProbability(AliPID::kElectron, 0.02);
    task[i]->SetPriorProbability(AliPID::kMuon,     0.02);
    task[i]->SetPriorProbability(AliPID::kPion,     0.83);
    task[i]->SetPriorProbability(AliPID::kKaon,     0.07);
    task[i]->SetPriorProbability(AliPID::kProton,   0.06);
    task[i]->DumpPriors();
  }

  // pair definitions:
  // phi   --> K+ K-
  // kstar --> K+ pi- & K- pi+
  AliRsnPairDef *pairPhi    = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kKaon, 333);
  AliRsnPairDef *pairKStar1 = new AliRsnPairDef('-', AliPID::kKaon, '+', AliPID::kPion, 313);
  AliRsnPairDef *pairKStar2 = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kPion, 313);
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->AddPairDef(pairPhi);
    task[i]->AddPairDef(pairKStar1);
    task[i]->AddPairDef(pairKStar2);
  }

  // axis definition
  //  0) transverse momentum
  //  1) pseudo-rapidity
  //  2) multiplicity (estimated with SPD tracklets - uncorrected)
  AliRsnFunctionAxis *axisPt   = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairPt,       40,  0.0,  10.0);
  AliRsnFunctionAxis *axisEta  = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairEta,      20, -1.5,   1.5);
  AliRsnFunctionAxis *axisMult = new AliRsnFunctionAxis(AliRsnFunctionAxis::kEventMult,     8,  0.0, 200.0);
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->AddAxis(axisMult);
    task[i]->AddAxis(axisPt);
    task[i]->AddAxis(axisEta);
  }

  // define cuts for event selection:
  // this will determine the filling of bins in the "info" histograms
  // and should be computed as additional correction factor in efficiency
  AliRsnCutPrimaryVertex *cutVertex   = new AliRsnCutPrimaryVertex("cutVertex", 3);
  AliRsnCutSet           *cutSetEvent = new AliRsnCutSet("eventCuts");
  cutSetEvent->AddCut(cutVertex);
  cutSetEvent->SetCutScheme("cutVertex");
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->SetEventCuts(cutSetEvent);
  }

  //
  // *** STEP 0 - All resonances which decay in the specified pairs
  //
  // This step does not need any kind of definition, since
  // its requirement is automatically checked during execution,
  // but to avoid segfaults, it is better to initialize a cut manager.
  //
  AliRsnCutMgr *cutMgrMC_step0 = new AliRsnCutMgr("mc_step0", "");

  //
  // *** STEP 1 - Acceptance
  //
  // Here we add a cut on the pseudorapidity for both tracks
  //
  AliRsnCutStd *cutEta = new AliRsnCutStd("cutEta", AliRsnCutStd::kEta, -0.9, 0.9);

  AliRsnCutMgr *cutMgrMC_step1    = new AliRsnCutMgr("mc_step1", "");
  AliRsnCutSet *cutSetTrack_step1 = new AliRsnCutSet("mc_step1_tracks");

  cutSetTrack_step1->AddCut(cutEta);
  cutSetTrack_step1->SetCutScheme("cutEta");
  cutMgrMC_step1   ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step1);

  //
  // *** STEP 2 - Reconstruction & track quality
  //
  // Use the interface to AliESDtrackCuts
  // and set only the cuts we are interested in
  AliRsnCutESDPrimary *cutQuality = new AliRsnCutESDPrimary("cutCov");
  cutQuality->GetCuts()->SetMaxCovDiagonalElements(2.0, 2.0, 0.5, 0.5, 2.0);
  cutQuality->GetCuts()->SetRequireSigmaToVertex(kTRUE);
  cutQuality->GetCuts()->SetMaxNsigmaToVertex(10000.0);
  cutQuality->GetCuts()->SetRequireTPCRefit(kTRUE);
  cutQuality->GetCuts()->SetAcceptKinkDaughters(kTRUE);
  cutQuality->GetCuts()->SetMinNClustersTPC(50);
  cutQuality->GetCuts()->SetMaxChi2PerClusterTPC(3.5);

  AliRsnCutMgr *cutMgrESD_step2   = new AliRsnCutMgr("esd_step2", "");
  AliRsnCutSet *cutSetTrack_step2 = new AliRsnCutSet("esd_step2_tracks");

  cutSetTrack_step2->AddCut(cutQuality);
  cutSetTrack_step2->SetCutScheme("cutQuality");
  cutMgrESD_step2  ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step2);

  //
  // *** STEP 3 - Primary tracks
  //
  // Use the interface to AliESDtrackCuts
  // and set only the cuts we are interested in
  // we also disable the cuts we applied before, for clarity
  AliRsnCutESDPrimary *cutESDPrimary = new AliRsnCutESDPrimary("cutESDPrimary");
  cutESDPrimary->GetCuts()->SetMaxCovDiagonalElements(100.0, 100.0, 100.0, 100.0, 100.0);
  cutESDPrimary->GetCuts()->SetRequireSigmaToVertex(kTRUE);
  cutESDPrimary->GetCuts()->SetMaxNsigmaToVertex(3.0);
  cutESDPrimary->GetCuts()->SetRequireTPCRefit(kFALSE);
  cutESDPrimary->GetCuts()->SetAcceptKinkDaughters(kFALSE);
  cutESDPrimary->GetCuts()->SetMinNClustersTPC(0);
  cutESDPrimary->GetCuts()->SetMaxChi2PerClusterTPC(100000000.0);

  AliRsnCutMgr *cutMgrESD_step3   = new AliRsnCutMgr("esd_step3", "");
  AliRsnCutSet *cutSetTrack_step3 = new AliRsnCutSet("esd_step3_tracks");

  cutSetTrack_step3->AddCut(cutESDPrimary);
  cutSetTrack_step3->SetCutScheme("cutESDPrimary");
  cutMgrESD_step3  ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step3);

  //
  // *** STEP 4 - Two possibilities (depend on the first macro argument)
  //
  // option 1 = Bethe-Bloch cut in 3 sigma (the sigma is one argument)
  // option 2 = realistic Bayesian PID with all detectors
  //
  AliRsnCutMgr *cutMgrESD_step4[2];
  AliRsnCutSet *cutSetTrack_step4[2];

  cutMgrESD_step4[0] = new AliRsnCutMgr("esd_step4_nopid", "");
  cutMgrESD_step4[1] = new AliRsnCutMgr("esd_step4_pid", "");
  cutSetTrack_step4[0] = new AliRsnCutSet("esd_step4_tracks_nopid");
  cutSetTrack_step4[1] = new AliRsnCutSet("esd_step4_tracks_pid");

  // Bethe-Bloch with kaon mass hypothesis
  AliRsnCutBetheBloch *cutKaonBB = new AliRsnCutBetheBloch("cutKaonBB", 3.0 * sigmaTPC, AliPID::kKaon);
  cutKaonBB->SetCalibConstant(0, 0.76176e-1);
  cutKaonBB->SetCalibConstant(1, 10.632);
  cutKaonBB->SetCalibConstant(2, 0.13279e-4);
  cutKaonBB->SetCalibConstant(3, 1.8631);
  cutKaonBB->SetCalibConstant(4, 1.9479);

  // cuts for realistic PID match
  AliRsnCutStd *cutRealisticPID = new AliRsnCutStd("cutKaonPID", AliRsnCutStd::kRealisticPIDMatch, 0);

  cutSetTrack_step4[0]->AddCut(cutKaonBB);
  cutSetTrack_step4[0]->SetCutScheme("cutKaonBB");

  cutSetTrack_step4[1]->AddCut(cutRealisticPID);
  cutSetTrack_step4[1]->SetCutScheme("cutRealisticPID");

  cutMgrESD_step4[0]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[0]);
  cutMgrESD_step4[1]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[1]);

  // add all steps to the task
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->AddStepMC (cutMgrMC_step0);
    task[i]->AddStepMC (cutMgrMC_step1);
    task[i]->AddStepESD(cutMgrESD_step2);
    task[i]->AddStepESD(cutMgrESD_step3);
    task[i]->AddStepESD(cutMgrESD_step4[i]);
  }

  // connect containers and finalize
  for (Int_t i = 0; i < 2; i++)
  {
    mgr->AddTask(task[i]);
    mgr->ConnectInput(task[i], 0, mgr->GetCommonInputContainer());

    // create paths for the output in the common file
    Char_t infoPath[500], effPath[500];
    sprintf(infoPath , "%s:PWG2RSNINFO" , AliAnalysisManager::GetCommonFileName());
    sprintf(effPath  , "%s:PWG2RSNEFF%s", AliAnalysisManager::GetCommonFileName(), suf[i].Data());

    // initialize and connect container for the output
    AliAnalysisDataContainer *info = 0x0, *out = 0x0;
    info = mgr->CreateContainer(Form("EffInfo_%s", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, infoPath);
    out  = mgr->CreateContainer(Form("EFF_%s", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, effPath);

    mgr->ConnectOutput(task[i], 1, info);
    mgr->ConnectOutput(task[i], 2, out);
  }

  return kTRUE;
}
<commit_msg>fix number of bins mismatch<commit_after>//
// This macro add an analysis task for computing efficiency.
// It will have as output an AliCFContainer with several steps:
//
//  0) all resonances in MC which decay in the pair specified
//  1) subset of (0) whose daughters are in acceptance
//  2) subset of (1) whose daughters satisfy quality track cuts (covariance, chi square && nTPCclusters)
//  3) subset of (2) whose daughters satisfy primary track cuts (nsigma to vertex, no kink daughters)
//  4) subset of (3) whose daughters satisty the BB TPC compatibility cut at 3 sigma
//
Bool_t AddAnalysisTaskRsnEff
(
  Bool_t      useBB    = kFALSE,
  Double_t    sigmaTPC = 0.065,
  const char *outFile  = "eff"
)
{
  // retrieve analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // common suffixes
  TString suf[2];
  suf[0] = "nopid";
  suf[1] = "pid";

  // create task
  AliRsnAnalysisEffSE *task[2];
  task[0] = new AliRsnAnalysisEffSE("EffNoPID");
  task[1] = new AliRsnAnalysisEffSE("EffPID");

  // set prior probabilities for PID
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->SetPriorProbability(AliPID::kElectron, 0.02);
    task[i]->SetPriorProbability(AliPID::kMuon,     0.02);
    task[i]->SetPriorProbability(AliPID::kPion,     0.83);
    task[i]->SetPriorProbability(AliPID::kKaon,     0.07);
    task[i]->SetPriorProbability(AliPID::kProton,   0.06);
    task[i]->DumpPriors();
  }

  // pair definitions:
  // phi   --> K+ K-
  // kstar --> K+ pi- & K- pi+
  AliRsnPairDef *pairPhi    = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kKaon, 333);
  AliRsnPairDef *pairKStar1 = new AliRsnPairDef('-', AliPID::kKaon, '+', AliPID::kPion, 313);
  AliRsnPairDef *pairKStar2 = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kPion, 313);
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->AddPairDef(pairPhi);
    task[i]->AddPairDef(pairKStar1);
    task[i]->AddPairDef(pairKStar2);
  }

  // axis definition
  //  0) transverse momentum
  //  1) pseudo-rapidity
  //  2) multiplicity (estimated with SPD tracklets - uncorrected)
  AliRsnFunctionAxis *axisPt   = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairPt,       50,  0.0,  10.0);
  AliRsnFunctionAxis *axisEta  = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairEta,      20, -1.5,   1.5);
  AliRsnFunctionAxis *axisMult = new AliRsnFunctionAxis(AliRsnFunctionAxis::kEventMult,     8,  0.0, 200.0);
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->AddAxis(axisMult);
    task[i]->AddAxis(axisPt);
    task[i]->AddAxis(axisEta);
  }

  // define cuts for event selection:
  // this will determine the filling of bins in the "info" histograms
  // and should be computed as additional correction factor in efficiency
  AliRsnCutPrimaryVertex *cutVertex   = new AliRsnCutPrimaryVertex("cutVertex", 3);
  AliRsnCutSet           *cutSetEvent = new AliRsnCutSet("eventCuts");
  cutSetEvent->AddCut(cutVertex);
  cutSetEvent->SetCutScheme("cutVertex");
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->SetEventCuts(cutSetEvent);
  }

  //
  // *** STEP 0 - All resonances which decay in the specified pairs
  //
  // This step does not need any kind of definition, since
  // its requirement is automatically checked during execution,
  // but to avoid segfaults, it is better to initialize a cut manager.
  //
  AliRsnCutMgr *cutMgrMC_step0 = new AliRsnCutMgr("mc_step0", "");

  //
  // *** STEP 1 - Acceptance
  //
  // Here we add a cut on the pseudorapidity for both tracks
  //
  AliRsnCutStd *cutEta = new AliRsnCutStd("cutEta", AliRsnCutStd::kEta, -0.9, 0.9);

  AliRsnCutMgr *cutMgrMC_step1    = new AliRsnCutMgr("mc_step1", "");
  AliRsnCutSet *cutSetTrack_step1 = new AliRsnCutSet("mc_step1_tracks");

  cutSetTrack_step1->AddCut(cutEta);
  cutSetTrack_step1->SetCutScheme("cutEta");
  cutMgrMC_step1   ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step1);

  //
  // *** STEP 2 - Reconstruction & track quality
  //
  // Use the interface to AliESDtrackCuts
  // and set only the cuts we are interested in
  AliRsnCutESDPrimary *cutQuality = new AliRsnCutESDPrimary("cutCov");
  cutQuality->GetCuts()->SetMaxCovDiagonalElements(2.0, 2.0, 0.5, 0.5, 2.0);
  cutQuality->GetCuts()->SetRequireSigmaToVertex(kTRUE);
  cutQuality->GetCuts()->SetMaxNsigmaToVertex(10000.0);
  cutQuality->GetCuts()->SetRequireTPCRefit(kTRUE);
  cutQuality->GetCuts()->SetAcceptKinkDaughters(kTRUE);
  cutQuality->GetCuts()->SetMinNClustersTPC(50);
  cutQuality->GetCuts()->SetMaxChi2PerClusterTPC(3.5);

  AliRsnCutMgr *cutMgrESD_step2   = new AliRsnCutMgr("esd_step2", "");
  AliRsnCutSet *cutSetTrack_step2 = new AliRsnCutSet("esd_step2_tracks");

  cutSetTrack_step2->AddCut(cutQuality);
  cutSetTrack_step2->SetCutScheme("cutQuality");
  cutMgrESD_step2  ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step2);

  //
  // *** STEP 3 - Primary tracks
  //
  // Use the interface to AliESDtrackCuts
  // and set only the cuts we are interested in
  // we also disable the cuts we applied before, for clarity
  AliRsnCutESDPrimary *cutESDPrimary = new AliRsnCutESDPrimary("cutESDPrimary");
  cutESDPrimary->GetCuts()->SetMaxCovDiagonalElements(100.0, 100.0, 100.0, 100.0, 100.0);
  cutESDPrimary->GetCuts()->SetRequireSigmaToVertex(kTRUE);
  cutESDPrimary->GetCuts()->SetMaxNsigmaToVertex(3.0);
  cutESDPrimary->GetCuts()->SetRequireTPCRefit(kFALSE);
  cutESDPrimary->GetCuts()->SetAcceptKinkDaughters(kFALSE);
  cutESDPrimary->GetCuts()->SetMinNClustersTPC(0);
  cutESDPrimary->GetCuts()->SetMaxChi2PerClusterTPC(100000000.0);

  AliRsnCutMgr *cutMgrESD_step3   = new AliRsnCutMgr("esd_step3", "");
  AliRsnCutSet *cutSetTrack_step3 = new AliRsnCutSet("esd_step3_tracks");

  cutSetTrack_step3->AddCut(cutESDPrimary);
  cutSetTrack_step3->SetCutScheme("cutESDPrimary");
  cutMgrESD_step3  ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step3);

  //
  // *** STEP 4 - Two possibilities (depend on the first macro argument)
  //
  // option 1 = Bethe-Bloch cut in 3 sigma (the sigma is one argument)
  // option 2 = realistic Bayesian PID with all detectors
  //
  AliRsnCutMgr *cutMgrESD_step4[2];
  AliRsnCutSet *cutSetTrack_step4[2];

  cutMgrESD_step4[0] = new AliRsnCutMgr("esd_step4_nopid", "");
  cutMgrESD_step4[1] = new AliRsnCutMgr("esd_step4_pid", "");
  cutSetTrack_step4[0] = new AliRsnCutSet("esd_step4_tracks_nopid");
  cutSetTrack_step4[1] = new AliRsnCutSet("esd_step4_tracks_pid");

  // Bethe-Bloch with kaon mass hypothesis
  AliRsnCutBetheBloch *cutKaonBB = new AliRsnCutBetheBloch("cutKaonBB", 3.0 * sigmaTPC, AliPID::kKaon);
  cutKaonBB->SetCalibConstant(0, 0.76176e-1);
  cutKaonBB->SetCalibConstant(1, 10.632);
  cutKaonBB->SetCalibConstant(2, 0.13279e-4);
  cutKaonBB->SetCalibConstant(3, 1.8631);
  cutKaonBB->SetCalibConstant(4, 1.9479);

  // cuts for realistic PID match
  AliRsnCutStd *cutRealisticPID = new AliRsnCutStd("cutKaonPID", AliRsnCutStd::kRealisticPIDMatch, 0);

  cutSetTrack_step4[0]->AddCut(cutKaonBB);
  cutSetTrack_step4[0]->SetCutScheme("cutKaonBB");

  cutSetTrack_step4[1]->AddCut(cutRealisticPID);
  cutSetTrack_step4[1]->SetCutScheme("cutRealisticPID");

  cutMgrESD_step4[0]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[0]);
  cutMgrESD_step4[1]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[1]);

  // add all steps to the task
  for (Int_t i = 0; i < 2; i++)
  {
    task[i]->AddStepMC (cutMgrMC_step0);
    task[i]->AddStepMC (cutMgrMC_step1);
    task[i]->AddStepESD(cutMgrESD_step2);
    task[i]->AddStepESD(cutMgrESD_step3);
    task[i]->AddStepESD(cutMgrESD_step4[i]);
  }

  // connect containers and finalize
  for (Int_t i = 0; i < 2; i++)
  {
    mgr->AddTask(task[i]);
    mgr->ConnectInput(task[i], 0, mgr->GetCommonInputContainer());

    // create paths for the output in the common file
    Char_t infoPath[500], effPath[500];
    sprintf(infoPath , "%s:PWG2RSNINFO" , AliAnalysisManager::GetCommonFileName());
    sprintf(effPath  , "%s:PWG2RSNEFF%s", AliAnalysisManager::GetCommonFileName(), suf[i].Data());

    // initialize and connect container for the output
    AliAnalysisDataContainer *info = 0x0, *out = 0x0;
    info = mgr->CreateContainer(Form("EffInfo_%s", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, infoPath);
    out  = mgr->CreateContainer(Form("EFF_%s", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, effPath);

    mgr->ConnectOutput(task[i], 1, info);
    mgr->ConnectOutput(task[i], 2, out);
  }

  return kTRUE;
}
<|endoftext|>


<commit_before>
// Copyright (c) 2012, 2013 Lionel MOISAN.
// Copyright (c) 2012, 2013 Pascal MONASSE.
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
#define OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_

//-------------------
// Generic implementation of ACRANSAC
//-------------------
// The A contrario parametrization have been first explained in [1] and
//  later extended to generic model estimation in [2] (with a demonstration for
//  the homography) and extended and use at large scale for Structure from
//  Motion in [3].
//
//--
//  [1] Lionel Moisan, Berenger Stival,
//  A probalistic criterion to detect rigid point matches between
//  two images and estimate the fundamental matrix.
//  IJCV 04.
//--
//  [2] Lionel Moisan, Pierre Moulon, Pascal Monasse.
//  Automatic Homographic Registration of a Pair of Images,
//    with A Contrario Elimination of Outliers
//  Image Processing On Line (IPOL), 2012.
//  http://dx.doi.org/10.5201/ipol.2012.mmm-oh
//--
//  [3] Pierre Moulon, Pascal Monasse and Renaud Marlet.
//  Adaptive Structure from Motion with a contrario mode estimation.
//  In 11th Asian Conference on Computer Vision (ACCV 2012)
//--

#include <algorithm>
#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <numeric>
#include <vector>

#include "openMVG/robust_estimation/rand_sampling.hpp"

namespace openMVG {
namespace robust{

/// logarithm (base 10) of binomial coefficient
static double logcombi(size_t k, size_t n)
{
  if (k>=n || k<=0) return(0.0);
  if (n-k<k) k=n-k;
  double r = 0.0;
  for (size_t i = 1; i <= k; i++)
    r += log10((double)(n-i+1))-log10((double)i);

  return r;
}

/// tabulate logcombi(.,n)
template<typename Type>
static void makelogcombi_n(size_t n, std::vector<Type> & l)
{
  l.resize(n+1);
  for (size_t k = 0; k <= n; k++)
    l[k] = static_cast<Type>( logcombi(k,n) );
}

/// tabulate logcombi(k,.)
template<typename Type>
static void makelogcombi_k(size_t k, size_t nmax, std::vector<Type> & l)
{
  l.resize(nmax+1);
  for (size_t n = 0; n <= nmax; n++)
    l[n] = static_cast<Type>(logcombi(k,n));
}

/// Distance and associated index
typedef std::pair<double,size_t> ErrorIndex;

/// Find best NFA and its index wrt square error threshold in e.
static ErrorIndex bestNFA(
  int startIndex, //number of point required for estimation
  double logalpha0,
  const std::vector<ErrorIndex>& e,
  double loge0,
  double maxThreshold,
  const std::vector<float> &logc_n,
  const std::vector<float> &logc_k,
  double multError = 1.0)
{
  ErrorIndex bestIndex(std::numeric_limits<double>::infinity(), startIndex);
  const size_t n = e.size();
  for(size_t k = startIndex + 1; k <= n && e[k - 1].first <= maxThreshold; ++k)
  {
    double logalpha = logalpha0 + multError * log10(e[k - 1].first + std::numeric_limits<float>::min());
    ErrorIndex index(loge0 +
                     logalpha * (double) (k - startIndex) +
                     logc_n[k] +
                     logc_k[k], k);

    if(index.first < bestIndex.first)
      bestIndex = index;
  }
  return bestIndex;
}

/// Pick a random sample
/// \param sizeSample The size of the sample.
/// \param vec_index  The possible data indices.
/// \param sample The random sample of sizeSample indices (output).
static void UniformSample(int sizeSample,
  const std::vector<size_t> &vec_index,
  std::vector<size_t> *sample)
{
  sample->resize(sizeSample);
  random_sample(sizeSample, vec_index.size(), sample);
  for(int i = 0; i < sizeSample; ++i)
    (*sample)[i] = vec_index[ (*sample)[i] ];
}

/**
 * @brief ACRANSAC routine (ErrorThreshold, NFA)
 *
 * @param[in] kernel model and metric object
 * @param[out] vec_inliers points that fit the estimated model
 * @param[in] nIter maximum number of consecutive iterations
 * @param[out] model returned model if found
 * @param[in] precision upper bound of the precision (squared error)
 * @param[in] bVerbose display console log
 *
 * @return (errorMax, minNFA)
 */
template<typename Kernel>
std::pair<double, double> ACRANSAC(const Kernel &kernel,
  std::vector<size_t> & vec_inliers,
  size_t nIter = 1024,
  typename Kernel::Model * model = NULL,
  double precision = std::numeric_limits<double>::infinity(),
  bool bVerbose = false)
{
  vec_inliers.clear();

  const size_t sizeSample = Kernel::MINIMUM_SAMPLES;
  const size_t nData = kernel.NumSamples();
  if(nData <= (size_t)sizeSample)
    return std::make_pair(0.0,0.0);

  const double maxThreshold = (precision==std::numeric_limits<double>::infinity()) ?
    std::numeric_limits<double>::infinity() :
    precision * kernel.normalizer2()(0,0) * kernel.normalizer2()(0,0);

  std::vector<ErrorIndex> vec_residuals(nData); // [residual,index]
  std::vector<double> vec_residuals_(nData);
  std::vector<size_t> vec_sample(sizeSample); // Sample indices

  // Possible sampling indices [0,..,nData] (will change in the optimization phase)
  std::vector<size_t> vec_index(nData);
  std::iota(vec_index.begin(), vec_index.end(), 0);

  // Precompute log combi
  double loge0 = log10((double)Kernel::MAX_MODELS * (nData-sizeSample));
  std::vector<float> vec_logc_n, vec_logc_k;
  makelogcombi_n(nData, vec_logc_n);
  makelogcombi_k(sizeSample, nData, vec_logc_k);

  // Output parameters
  double minNFA = std::numeric_limits<double>::infinity();
  double errorMax = std::numeric_limits<double>::infinity();

  // Reserve 10% of iterations for focused sampling
  size_t nIterReserve = nIter/10;
  nIter -= nIterReserve;

  // Main estimation loop.
  for (size_t iter=0; iter < nIter; ++iter)
  {
    UniformSample(sizeSample, vec_index, &vec_sample); // Get random sample

    std::vector<typename Kernel::Model> vec_models; // Up to max_models solutions
    kernel.Fit(vec_sample, &vec_models);

    // Evaluate models
    bool better = false;
    for (size_t k = 0; k < vec_models.size(); ++k)
    {
      // Residuals computation and ordering
      kernel.Errors(vec_models[k], vec_residuals_);
      for (size_t i = 0; i < nData; ++i)
      {
        const double error = vec_residuals_[i];
        vec_residuals[i] = ErrorIndex(error, i);
      }
      std::sort(vec_residuals.begin(), vec_residuals.end());

      // Most meaningful discrimination inliers/outliers
      const ErrorIndex best = bestNFA(
        sizeSample,
        kernel.logalpha0(),
        vec_residuals,
        loge0,
        maxThreshold,
        vec_logc_n,
        vec_logc_k,
        kernel.multError());

      if (best.first < minNFA /*&& vec_residuals[best.second-1].first < errorMax*/)
      {
        // A better model was found
        better = true;
        minNFA = best.first;
        vec_inliers.resize(best.second);
        for (size_t i=0; i<best.second; ++i)
          vec_inliers[i] = vec_residuals[i].second;
        errorMax = vec_residuals[best.second-1].first; // Error threshold
        if(model) *model = vec_models[k];

        if(bVerbose)
        {
          std::cout << "  nfa=" << minNFA
            << " inliers=" << best.second << "/" << nData
            << " precisionNormalized=" << errorMax
            << " precision=" << kernel.unormalizeError(errorMax)
            << " (iter=" << iter;
          std::cout << ",sample=";
          std::copy(vec_sample.begin(), vec_sample.end(),
            std::ostream_iterator<size_t>(std::cout, ","));
          std::cout << ")" <<std::endl;
        }
      }
    }

    // ACRANSAC optimization: draw samples among best set of inliers so far
    if((better && minNFA<0) || (iter+1==nIter && nIterReserve))
    {
      if(vec_inliers.empty())
      { // No model found at all so far
        nIter++; // Continue to look for any model, even not meaningful
        nIterReserve--;
      }
      else
      {
        // ACRANSAC optimization: draw samples among best set of inliers so far
        vec_index = vec_inliers;
        if(nIterReserve)
        {
          nIter = iter + 1 + nIterReserve;
          nIterReserve = 0;
        }
      }
    }
  }

  if(minNFA >= 0)
    vec_inliers.clear();

  if (!vec_inliers.empty())
  {
    if (model)
      kernel.Unnormalize(model);
    errorMax = kernel.unormalizeError(errorMax);
  }

  return std::make_pair(errorMax, minNFA);
}

} // namespace robust
} // namespace openMVG
#endif // OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
<commit_msg>[robust_estimator] partial fix for acransac  (ce0850d)<commit_after>
// Copyright (c) 2012, 2013 Lionel MOISAN.
// Copyright (c) 2012, 2013 Pascal MONASSE.
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
#define OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_

//-------------------
// Generic implementation of ACRANSAC
//-------------------
// The A contrario parametrization have been first explained in [1] and
//  later extended to generic model estimation in [2] (with a demonstration for
//  the homography) and extended and use at large scale for Structure from
//  Motion in [3].
//
//--
//  [1] Lionel Moisan, Berenger Stival,
//  A probalistic criterion to detect rigid point matches between
//  two images and estimate the fundamental matrix.
//  IJCV 04.
//--
//  [2] Lionel Moisan, Pierre Moulon, Pascal Monasse.
//  Automatic Homographic Registration of a Pair of Images,
//    with A Contrario Elimination of Outliers
//  Image Processing On Line (IPOL), 2012.
//  http://dx.doi.org/10.5201/ipol.2012.mmm-oh
//--
//  [3] Pierre Moulon, Pascal Monasse and Renaud Marlet.
//  Adaptive Structure from Motion with a contrario mode estimation.
//  In 11th Asian Conference on Computer Vision (ACCV 2012)
//--

#include <algorithm>
#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <numeric>
#include <vector>

#include "openMVG/robust_estimation/rand_sampling.hpp"

namespace openMVG {
namespace robust{

/// logarithm (base 10) of binomial coefficient
static double logcombi(size_t k, size_t n)
{
  if (k>=n || k<=0) return(0.0);
  if (n-k<k) k=n-k;
  double r = 0.0;
  for (size_t i = 1; i <= k; i++)
    r += log10((double)(n-i+1))-log10((double)i);

  return r;
}

/// tabulate logcombi(.,n)
template<typename Type>
static void makelogcombi_n(size_t n, std::vector<Type> & l)
{
  l.resize(n+1);
  for (size_t k = 0; k <= n; k++)
    l[k] = static_cast<Type>( logcombi(k,n) );
}

/// tabulate logcombi(k,.)
template<typename Type>
static void makelogcombi_k(size_t k, size_t nmax, std::vector<Type> & l)
{
  l.resize(nmax+1);
  for (size_t n = 0; n <= nmax; n++)
    l[n] = static_cast<Type>(logcombi(k,n));
}

/// Distance and associated index
typedef std::pair<double,size_t> ErrorIndex;

/// Find best NFA and its index wrt square error threshold in e.
static ErrorIndex bestNFA(
  int startIndex, //number of point required for estimation
  double logalpha0,
  const std::vector<ErrorIndex>& e,
  double loge0,
  double maxThreshold,
  const std::vector<float> &logc_n,
  const std::vector<float> &logc_k,
  double multError = 1.0)
{
  ErrorIndex bestIndex(std::numeric_limits<double>::infinity(), startIndex);
  const size_t n = e.size();
  for(size_t k = startIndex + 1; k <= n && e[k - 1].first <= maxThreshold; ++k)
  {
    const double logalpha = logalpha0 + multError * log10(e[k - 1].first + std::numeric_limits<float>::epsilon());
    ErrorIndex index(loge0 +
                     logalpha * (double) (k - startIndex) +
                     logc_n[k] +
                     logc_k[k], k);

    if(index.first < bestIndex.first)
      bestIndex = index;
  }
  return bestIndex;
}

/// Pick a random sample
/// \param sizeSample The size of the sample.
/// \param vec_index  The possible data indices.
/// \param sample The random sample of sizeSample indices (output).
static void UniformSample(int sizeSample,
  const std::vector<size_t> &vec_index,
  std::vector<size_t> *sample)
{
  sample->resize(sizeSample);
  random_sample(sizeSample, vec_index.size(), sample);
  for(int i = 0; i < sizeSample; ++i)
    (*sample)[i] = vec_index[ (*sample)[i] ];
}

/**
 * @brief ACRANSAC routine (ErrorThreshold, NFA)
 *
 * @param[in] kernel model and metric object
 * @param[out] vec_inliers points that fit the estimated model
 * @param[in] nIter maximum number of consecutive iterations
 * @param[out] model returned model if found
 * @param[in] precision upper bound of the precision (squared error)
 * @param[in] bVerbose display console log
 *
 * @return (errorMax, minNFA)
 */
template<typename Kernel>
std::pair<double, double> ACRANSAC(const Kernel &kernel,
  std::vector<size_t> & vec_inliers,
  size_t nIter = 1024,
  typename Kernel::Model * model = NULL,
  double precision = std::numeric_limits<double>::infinity(),
  bool bVerbose = false)
{
  vec_inliers.clear();

  const size_t sizeSample = Kernel::MINIMUM_SAMPLES;
  const size_t nData = kernel.NumSamples();
  if(nData <= (size_t)sizeSample)
    return std::make_pair(0.0,0.0);

  const double maxThreshold = (precision==std::numeric_limits<double>::infinity()) ?
    std::numeric_limits<double>::infinity() :
    precision * kernel.normalizer2()(0,0) * kernel.normalizer2()(0,0);

  std::vector<ErrorIndex> vec_residuals(nData); // [residual,index]
  std::vector<double> vec_residuals_(nData);
  std::vector<size_t> vec_sample(sizeSample); // Sample indices

  // Possible sampling indices [0,..,nData] (will change in the optimization phase)
  std::vector<size_t> vec_index(nData);
  std::iota(vec_index.begin(), vec_index.end(), 0);

  // Precompute log combi
  double loge0 = log10((double)Kernel::MAX_MODELS * (nData-sizeSample));
  std::vector<float> vec_logc_n, vec_logc_k;
  makelogcombi_n(nData, vec_logc_n);
  makelogcombi_k(sizeSample, nData, vec_logc_k);

  // Output parameters
  double minNFA = std::numeric_limits<double>::infinity();
  double errorMax = std::numeric_limits<double>::infinity();

  // Reserve 10% of iterations for focused sampling
  size_t nIterReserve = nIter/10;
  nIter -= nIterReserve;

  // Main estimation loop.
  for (size_t iter=0; iter < nIter; ++iter)
  {
    UniformSample(sizeSample, vec_index, &vec_sample); // Get random sample

    std::vector<typename Kernel::Model> vec_models; // Up to max_models solutions
    kernel.Fit(vec_sample, &vec_models);

    // Evaluate models
    bool better = false;
    for (size_t k = 0; k < vec_models.size(); ++k)
    {
      // Residuals computation and ordering
      kernel.Errors(vec_models[k], vec_residuals_);
      for (size_t i = 0; i < nData; ++i)
      {
        const double error = vec_residuals_[i];
        vec_residuals[i] = ErrorIndex(error, i);
      }
      std::sort(vec_residuals.begin(), vec_residuals.end());

      // Most meaningful discrimination inliers/outliers
      const ErrorIndex best = bestNFA(
        sizeSample,
        kernel.logalpha0(),
        vec_residuals,
        loge0,
        maxThreshold,
        vec_logc_n,
        vec_logc_k,
        kernel.multError());

      if (best.first < minNFA /*&& vec_residuals[best.second-1].first < errorMax*/)
      {
        // A better model was found
        better = true;
        minNFA = best.first;
        vec_inliers.resize(best.second);
        for (size_t i=0; i<best.second; ++i)
          vec_inliers[i] = vec_residuals[i].second;
        errorMax = vec_residuals[best.second-1].first; // Error threshold
        if(model) *model = vec_models[k];

        if(bVerbose)
        {
          std::cout << "  nfa=" << minNFA
            << " inliers=" << best.second << "/" << nData
            << " precisionNormalized=" << errorMax
            << " precision=" << kernel.unormalizeError(errorMax)
            << " (iter=" << iter;
          std::cout << ",sample=";
          std::copy(vec_sample.begin(), vec_sample.end(),
            std::ostream_iterator<size_t>(std::cout, ","));
          std::cout << ")" <<std::endl;
        }
      }
    }

    // ACRANSAC optimization: draw samples among best set of inliers so far
    if((better && minNFA<0) || (iter+1==nIter && nIterReserve))
    {
      if(vec_inliers.empty())
      { // No model found at all so far
        nIter++; // Continue to look for any model, even not meaningful
        nIterReserve--;
      }
      else
      {
        // ACRANSAC optimization: draw samples among best set of inliers so far
        vec_index = vec_inliers;
        if(nIterReserve)
        {
          nIter = iter + 1 + nIterReserve;
          nIterReserve = 0;
        }
      }
    }
  }

  if(minNFA >= 0)
    vec_inliers.clear();

  if (!vec_inliers.empty())
  {
    if (model)
      kernel.Unnormalize(model);
    errorMax = kernel.unormalizeError(errorMax);
  }

  return std::make_pair(errorMax, minNFA);
}

} // namespace robust
} // namespace openMVG
#endif // OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "gputest.hpp"
#include <iostream>
#include <string>

#include <opencv2/opencv.hpp>
#include <opencv2/gpu/gpu.hpp>

class CV_GpuMeanShift : public CvTest
{
    public:
        CV_GpuMeanShift();
    protected:
        void run(int);
};

CV_GpuMeanShift::CV_GpuMeanShift(): CvTest( "GPU-MeanShift", "meanshift" ){}

void CV_GpuMeanShift::run(int )
{
        int spatialRad = 30;
        int colorRad = 30;

        cv::Mat img = cv::imread(std::string(ts->get_data_path()) + "meanshift/con.png");
        cv::Mat img_template = cv::imread(std::string(ts->get_data_path()) + "meanshift/con_result.png");

        cv::Mat rgba;
        cvtColor(img, rgba, CV_BGR2BGRA);

        cv::gpu::GpuMat res;

        cv::gpu::meanShiftFiltering_GPU( cv::gpu::GpuMat(rgba), res, spatialRad, colorRad );

        res.convertTo(res, img_template.type());

        double norm = cv::norm(res, img_template, cv::NORM_INF);

        ts->set_failed_test_info((norm < 0.5) ? CvTS::OK : CvTS::FAIL_GENERIC);
}

CV_GpuMeanShift CV_GpuMeanShift_test;
<commit_msg>rename con.png to  cones.png in test gpu<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "gputest.hpp"
#include <iostream>
#include <string>

#include <opencv2/opencv.hpp>
#include <opencv2/gpu/gpu.hpp>

class CV_GpuMeanShift : public CvTest
{
    public:
        CV_GpuMeanShift();
    protected:
        void run(int);
};

CV_GpuMeanShift::CV_GpuMeanShift(): CvTest( "GPU-MeanShift", "meanshift" ){}

void CV_GpuMeanShift::run(int )
{
        int spatialRad = 30;
        int colorRad = 30;

        cv::Mat img = cv::imread(std::string(ts->get_data_path()) + "meanshift/cones.png");
        cv::Mat img_template = cv::imread(std::string(ts->get_data_path()) + "meanshift/con_result.png");

        cv::Mat rgba;
        cvtColor(img, rgba, CV_BGR2BGRA);

        cv::gpu::GpuMat res;

        cv::gpu::meanShiftFiltering_GPU( cv::gpu::GpuMat(rgba), res, spatialRad, colorRad );

        res.convertTo(res, img_template.type());

        double norm = cv::norm(res, img_template, cv::NORM_INF);

        ts->set_failed_test_info((norm < 0.5) ? CvTS::OK : CvTS::FAIL_GENERIC);
}

CV_GpuMeanShift CV_GpuMeanShift_test;
<|endoftext|>