<commit_before>#include "GameManager.h"
#include "menu/PauseMenu.h"
#include "menu/Player.h"

#include <Indie.h>

namespace Symp {

GameManager::GameManager(const char *title, int width, int height, int bpp, bool vsync, bool fs, bool dBuffer){
	//Initialize the engine
	IndieLib::init(IND_DEBUG_MODE);
	m_pWindow = new Window();
	m_pRender = new Render();
	m_pWindow->setWindow(m_pRender->init(title, width, height, bpp, vsync, fs, dBuffer));
	m_pWindow->setCursor(true);
	m_pInputManager = new InputManager(m_pRender);
	m_pParser = new Parser("../assets/data.xml");
	//m_pSoundManager = new SoundManager();
	//m_pSoundManager->loadSound("../assets/audio/test.wav"); //test sound

	//Initialize the game elements to null and start the menu
	m_pMenuManager =  nullptr;
	m_pLevelManager = nullptr;
	switchToMenu();
}

GameManager::~GameManager(){
	IndieLib::end();
	delete m_pWindow;
	delete m_pRender;
	delete m_pInputManager;
	delete m_pMenuManager;
}

/**
* @brief Displays the game when it needs to be
* This function displays the game, usually called from a menu.
* @see MenuManager
* @see updateGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToGame(){
	//Reset the menuManager attribut
	m_pMenuManager->setLevelChoosen(false);

	EntityManager::getInstance();
	EntityManager::initRender(m_pRender);

	if (m_pLevelManager == nullptr) {
		//If no game have been created before then create a new one (from the main menu)
		m_pLevelManager = new LevelManager();
		loadLevel(m_pMenuManager->getLevelToLoad().c_str());
	 	m_bIsInGame = true;
	}
	else{
		m_bIsInGame = true;
	}
}

/**
* @brief Clear the game entities and attributes for displaying the main menu
* @see MenuManager
* @see EntityManager
* @see LevelManager
* @see updateMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::clear(){
	EntityManager::getInstance()->deleteAllEntities();
	delete m_pLevelManager;
	delete m_pMenuManager;
	EntityManager::removeInstance();
	m_pMenuManager = nullptr;
	m_pLevelManager = nullptr;
}

/**
* @brief Displays the menus when it needs to be
* This function displays wether the main menu, or the PauseMenu. This function can be called in game for displaying
* again the main menus, in this case, the #GameManager needs to be cleared using the #clear() function. To display the
* game, see #switchToGame().
* @see MenuManager
* @see updateMenu()
* @see switchToGame()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToMenu(){
	//If the MenuManager doesn't exists, means at the first launch or when the user quit the game, then create it.
	if (m_pMenuManager == nullptr){

		//Retrive data from the player data file
		std::pair<Player*, std::vector<Player*>> playerData = m_pParser->loadPlayerData();

		//Start the menus
		m_pMenuManager = new MenuManager(m_pRender, playerData);
 		m_bIsInGame = false;
 		//manage Camera
		m_pRender->setCamera();
 		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);

 	}else {

 		//Pause menu
 		RenderEntity* pDino = EntityManager::getInstance()->getRenderDino();
 		PauseMenu* pPauseMenu = new PauseMenu(m_pMenuManager, pDino->getPosX(), pDino->getPosY());
 		m_pMenuManager->setState(pPauseMenu);
 		m_bIsInGame = false;
 	}
}

/**
* @brief The main loop of the game responsible the application to run
* @see updateMenu()
* @see updateGame()
* @see switchToGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::startMainLoop(){
	//If the user didn't closed the window or didn't clicked a "quit" button, then update
	while (!m_pMenuManager->isAboutToQuit() && !m_pInputManager->quit())
	{
		m_pInputManager->update();
 		if(m_bIsInGame) {
			updateGame();
		}
		else {
			updateMenu();
		}
	}
}

/**
* @brief Update the game part of the application each loop
* @see updateMenu()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateGame() {
	//move dino
	PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
		float impulse = pDino->getMass() * 1;
	if (m_pInputManager->isKeyPressed(IND_KEYLEFT)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(-impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}
	if (m_pInputManager->isKeyPressed(IND_KEYRIGHT)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}
	if (m_pInputManager->isKeyPressed(IND_KEYUP)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, -impulse), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}
	if (m_pInputManager->isKeyPressed(IND_KEYDOWN)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, impulse), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}

	//manage Camera
	m_pRender->setCamera();
	m_pRender->setCameraPosition(pDino->getPosition().x, pDino->getPosition().y);

	//update all list of entities
	EntityManager::getInstance()->updateEntities();

	//sound
	if (m_pInputManager->isKeyPressed(IND_SPACE)){
		//m_pSoundManager->play(0); //seg fault : still no song !
	}

	//render openGL
	m_pRender->clearViewPort(60, 60, 60);
	m_pRender->beginScene();
	EntityManager::getInstance()->renderEntities();
	m_pRender->endScene();

	//Pause
	if (m_pInputManager->onKeyPress(IND_ESCAPE)){
		switchToMenu();
	}
}

/**
* @brief Update the menu part of the application each loop
* @see updateGame()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateMenu() {
	//manage camera
	m_pRender->setCamera();

	//Forward inputs
	if (m_pInputManager->onKeyPress(IND_KEYDOWN)){
		m_pMenuManager->handleKeyPressed("KEYDOWN");
	}
	else if (m_pInputManager->onKeyPress(IND_KEYUP)){
		m_pMenuManager->handleKeyPressed("KEYUP");
	}
	else if (m_pInputManager->isMouseMotion()){
		// Mouse hover
		m_pMenuManager->handleMouseHover(m_pInputManager->getMouseX(), m_pInputManager->getMouseY());
	}
	else if(m_pInputManager->onMouseButtonPress(IND_MBUTTON_LEFT)){
		// Clic
		m_pMenuManager->handleMouseClic(m_pInputManager->getMouseX(), m_pInputManager->getMouseY());
	}
	else if (m_pInputManager->onKeyPress(IND_ESCAPE) && m_pMenuManager->isDisplayingPauseState()){
		// Hidding the Pause menu
		m_pMenuManager->setLevelChoosen(false);
		m_bIsInGame = true;
	}

	// The PauseMenu need not to refresh the window in order to displayed upon the game view
	if(!m_pMenuManager->isDisplayingPauseState()){
		m_pRender->clearViewPort(60, 60, 60);
	}
	// Otherwise, all the menus needs to refresh the window
	m_pRender->beginScene();
	m_pMenuManager->renderEntities();
	m_pRender->endScene();

	//Manage user decisions
	if(m_pMenuManager->isLevelChoosen()){
		// If the game part needs to be launch
		switchToGame();
		m_pMenuManager->clear();
	}else if (m_pMenuManager->isGoingBackToMenu() && m_pMenuManager->isDisplayingPauseState()){
		// If the user wants to go back to the main menu from the pause menu
		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
		clear();
		switchToMenu();
	}
}

void GameManager::loadLevel(const char* mapFile) {
	EntityManager::getInstance()->deleteAllEntities();
	EntityManager::getInstance()->addDino();
	m_pLevelManager->loadLevel(mapFile);
}

}
<commit_msg>add the mouse offsets for the pause menu<commit_after>#include "GameManager.h"
#include "menu/PauseMenu.h"
#include "menu/Player.h"

#include <Indie.h>

namespace Symp {

GameManager::GameManager(const char *title, int width, int height, int bpp, bool vsync, bool fs, bool dBuffer){
	//Initialize the engine
	IndieLib::init(IND_DEBUG_MODE);
	m_pWindow = new Window();
	m_pRender = new Render();
	m_pWindow->setWindow(m_pRender->init(title, width, height, bpp, vsync, fs, dBuffer));
	m_pWindow->setCursor(true);
	m_pInputManager = new InputManager(m_pRender);
	m_pParser = new Parser("../assets/data.xml");
	//m_pSoundManager = new SoundManager();
	//m_pSoundManager->loadSound("../assets/audio/test.wav"); //test sound

	//Initialize the game elements to null and start the menu
	m_pMenuManager =  nullptr;
	m_pLevelManager = nullptr;
	switchToMenu();
}

GameManager::~GameManager(){
	IndieLib::end();
	delete m_pWindow;
	delete m_pRender;
	delete m_pInputManager;
	delete m_pMenuManager;
}

/**
* @brief Displays the game when it needs to be
* This function displays the game, usually called from a menu.
* @see MenuManager
* @see updateGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToGame(){
	//Reset the menuManager attribut
	m_pMenuManager->setLevelChoosen(false);

	EntityManager::getInstance();
	EntityManager::initRender(m_pRender);

	if (m_pLevelManager == nullptr) {
		//If no game have been created before then create a new one (from the main menu)
		m_pLevelManager = new LevelManager();
		loadLevel(m_pMenuManager->getLevelToLoad().c_str());
	 	m_bIsInGame = true;
	}
	else{
		m_bIsInGame = true;
	}
}

/**
* @brief Clear the game entities and attributes for displaying the main menu
* @see MenuManager
* @see EntityManager
* @see LevelManager
* @see updateMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::clear(){
	EntityManager::getInstance()->deleteAllEntities();
	delete m_pLevelManager;
	delete m_pMenuManager;
	EntityManager::removeInstance();
	m_pMenuManager = nullptr;
	m_pLevelManager = nullptr;
}

/**
* @brief Displays the menus when it needs to be
* This function displays wether the main menu, or the PauseMenu. This function can be called in game for displaying
* again the main menus, in this case, the #GameManager needs to be cleared using the #clear() function. To display the
* game, see #switchToGame().
* @see MenuManager
* @see updateMenu()
* @see switchToGame()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToMenu(){
	//If the MenuManager doesn't exists, means at the first launch or when the user quit the game, then create it.
	if (m_pMenuManager == nullptr){

		//Retrive data from the player data file
		std::pair<Player*, std::vector<Player*>> playerData = m_pParser->loadPlayerData();

		//Start the menus
		m_pMenuManager = new MenuManager(m_pRender, playerData);
 		m_bIsInGame = false;
 		//manage Camera
		m_pRender->setCamera();
 		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);

 	}else {

 		//Pause menu
 		RenderEntity* pDino = EntityManager::getInstance()->getRenderDino();
 		PauseMenu* pPauseMenu = new PauseMenu(m_pMenuManager, pDino->getPosX(), pDino->getPosY());
 		m_pMenuManager->setState(pPauseMenu);
 		m_bIsInGame = false;
 	}
}

/**
* @brief The main loop of the game responsible the application to run
* @see updateMenu()
* @see updateGame()
* @see switchToGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::startMainLoop(){
	//If the user didn't closed the window or didn't clicked a "quit" button, then update
	while (!m_pMenuManager->isAboutToQuit() && !m_pInputManager->quit())
	{
		m_pInputManager->update();
 		if(m_bIsInGame) {
			updateGame();
		}
		else {
			updateMenu();
		}
	}
}

/**
* @brief Update the game part of the application each loop
* @see updateMenu()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateGame() {
	//move dino
	PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
	float impulse = pDino->getMass() * 1;
	if (m_pInputManager->isKeyPressed(IND_KEYLEFT)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(-impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}
	if (m_pInputManager->isKeyPressed(IND_KEYRIGHT)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}
	if (m_pInputManager->isKeyPressed(IND_KEYUP)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, -impulse), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}
	if (m_pInputManager->isKeyPressed(IND_KEYDOWN)){
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, impulse), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}

	//manage Camera
	m_pRender->setCamera();
	m_pRender->setCameraPosition(pDino->getPosition().x, pDino->getPosition().y);

	//update all list of entities
	EntityManager::getInstance()->updateEntities();

	//sound
	if (m_pInputManager->isKeyPressed(IND_SPACE)){
		//m_pSoundManager->play(0); //seg fault : still no song !
	}

	//render openGL
	m_pRender->clearViewPort(60, 60, 60);
	m_pRender->beginScene();
	EntityManager::getInstance()->renderEntities();
	m_pRender->endScene();

	//Pause
	if (m_pInputManager->onKeyPress(IND_ESCAPE)){
		switchToMenu();
	}
}

/**
* @brief Update the menu part of the application each loop
* @see updateGame()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateMenu() {
	//Forward inputs

	//The following offsets are necessary to the mouse pointer to click on the pause menu
	//because it's not the same coordinate space
	int offsetX = 0;
	int offsetY = 0;
	if(m_pMenuManager->isDisplayingPauseState()){
		PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
		offsetX = pDino->getPosition().x - m_pWindow->getIND_Window()->getWidth()*0.5;
		offsetY = pDino->getPosition().y - m_pWindow->getIND_Window()->getHeight()*0.5;
	}

	if (m_pInputManager->onKeyPress(IND_KEYDOWN)){
		m_pMenuManager->handleKeyPressed("KEYDOWN");
	}
	else if (m_pInputManager->onKeyPress(IND_KEYUP)){
		m_pMenuManager->handleKeyPressed("KEYUP");
	}
	else if (m_pInputManager->isMouseMotion()){
		// Mouse hover
		m_pMenuManager->handleMouseHover(m_pInputManager->getMouseX()+offsetX, m_pInputManager->getMouseY()+offsetY);
	}
	else if(m_pInputManager->onMouseButtonPress(IND_MBUTTON_LEFT)){
		// Clic
		m_pMenuManager->handleMouseClic(m_pInputManager->getMouseX()+offsetX, m_pInputManager->getMouseY()+offsetY);
	}
	else if (m_pInputManager->onKeyPress(IND_ESCAPE) && m_pMenuManager->isDisplayingPauseState()){
		// Hidding the Pause menu
		m_pMenuManager->setLevelChoosen(false);
		m_bIsInGame = true;
	}

	// The PauseMenu need not to refresh the window in order to displayed upon the game view
	if(!m_pMenuManager->isDisplayingPauseState()){
		m_pRender->clearViewPort(60, 60, 60);
	}
	// Otherwise, all the menus needs to refresh the window
	m_pRender->beginScene();
	m_pMenuManager->renderEntities();
	m_pRender->endScene();

	//manage camera
	m_pRender->setCamera();
	//Manage user decisions
	if(m_pMenuManager->isLevelChoosen()){
		// If the game part needs to be launch
		switchToGame();
		m_pMenuManager->clear();
	}else if (m_pMenuManager->isGoingBackToMenu() && m_pMenuManager->isDisplayingPauseState()){
		// If the user wants to go back to the main menu from the pause menu
		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
		clear();
		switchToMenu();
	}
}

void GameManager::loadLevel(const char* mapFile) {
	EntityManager::getInstance()->deleteAllEntities();
	EntityManager::getInstance()->addDino();
	m_pLevelManager->loadLevel(mapFile);
}

}
<|endoftext|>


<commit_before>//
// Copyright (c) 2017 The Khronos Group Inc.
//
// 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 "../../../test_common/harness/compat.h"

#include <stdio.h>
#include <string.h>

#if !defined(_WIN32)
#include <unistd.h>
#include <sys/time.h>
#endif

#include "../testBase.h"

bool             gDebugTrace = false, gTestSmallImages = false, gTestMaxImages = false, gTestRounding = false, gEnablePitch = false;
int              gTypesToTest = 0;
cl_channel_type  gChannelTypeToUse = (cl_channel_type)-1;
cl_channel_order gChannelOrderToUse = (cl_channel_order)-1;
cl_device_type   gDeviceType = CL_DEVICE_TYPE_DEFAULT;
cl_context       context;
cl_command_queue queue;

extern int test_image_set( cl_device_id device, MethodsToTest testMethod );

#define MAX_ALLOWED_STD_DEVIATION_IN_MB        8.0

void printUsage( const char *execName )
{
    const char *p = strrchr( execName, '/' );
    if ( p != NULL )
        execName = p + 1;

    log_info( "Usage: %s [debug_trace] [small_images]\n", execName );
    log_info( "Where:\n" );
    log_info( "\t1D - Only test 1D images\n" );
    log_info( "\t2D - Only test 2D images\n" );
    log_info( "\t3D - Only test 3D images\n" );
    log_info( "\t1Darray - Only test 1D image arrays\n" );
    log_info( "\t2Darray - Only test 2D image arrays\n" );
    log_info( "\n" );
    log_info( "\tThe following flags specify the types to test. They can be combined; if none are specified, all are tested:\n" );
    log_info( "\t\tint - Test integer fill\n" );
    log_info( "\t\tuint - Test unsigned integer fill\n" );
    log_info( "\t\tfloat - Test float fill\n" );
    log_info( "\n" );
    log_info( "\tdebug_trace - Enables additional debug info logging\n" );
    log_info( "\tsmall_images - Runs every format through a loop of widths 1-13 and heights 1-9, instead of random sizes\n" );
    log_info( "\tmax_images - Runs every format through a set of size combinations with the max values, max values - 1, and max values / 128\n" );
    log_info( "\tuse_pitches - Enables row and slice pitches\n" );
    log_info( "You may also use appropriate CL_ channel type and ordering constants.\n" );
}

int main(int argc, const char *argv[])
{
    cl_platform_id   platform;
    cl_device_id     device;
    cl_channel_type  chanType;
    cl_channel_order chanOrder;
    char             str[ 128 ];
    int              testMethods = 0;
    bool             randomize = false;

    test_start();

    checkDeviceTypeOverride( &gDeviceType );

    // Parse arguments
    for ( int i = 1; i < argc; i++ )
    {
        strncpy( str, argv[ i ], sizeof( str ) - 1 );

        if ( strcmp( str, "cpu" ) == 0 || strcmp( str, "CL_DEVICE_TYPE_CPU" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_CPU;
        else if ( strcmp( str, "gpu" ) == 0 || strcmp( str, "CL_DEVICE_TYPE_GPU" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_GPU;
        else if ( strcmp( str, "accelerator" ) == 0 || strcmp( str, "CL_DEVICE_TYPE_ACCELERATOR" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_ACCELERATOR;
        else if ( strcmp( str, "CL_DEVICE_TYPE_DEFAULT" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_DEFAULT;

        else if ( strcmp( str, "debug_trace" ) == 0 )
            gDebugTrace = true;

        else if ( strcmp( str, "small_images" ) == 0 )
            gTestSmallImages = true;
        else if ( strcmp( str, "max_images" ) == 0 )
            gTestMaxImages = true;

        else if ( strcmp( str, "use_pitches" ) == 0 )
            gEnablePitch = true;

        else if ( strcmp( str, "randomize" ) == 0 )
            randomize = true;

        else if ( strcmp( str, "1D" ) == 0 )
            testMethods |= k1D;
        else if ( strcmp( str, "2D" ) == 0 )
            testMethods |= k2D;
        else if ( strcmp( str, "3D" ) == 0 )
            testMethods |= k3D;
        else if( strcmp( str, "1Darray" ) == 0 )
            testMethods |= k1DArray;
        else if( strcmp( str, "2Darray" ) == 0 )
            testMethods |= k2DArray;

        else if( strcmp( str, "int" ) == 0 )
            gTypesToTest |= kTestInt;
        else if( strcmp( str, "uint" ) == 0 )
            gTypesToTest |= kTestUInt;
        else if( strcmp( str, "float" ) == 0 )
            gTypesToTest |= kTestFloat;

        else if ( strcmp( str, "help" ) == 0 || strcmp( str, "?" ) == 0 )
        {
            printUsage( argv[ 0 ] );
            return -1;
        }

        else if ( ( chanType = get_channel_type_from_name( str ) ) != (cl_channel_type)-1 )
            gChannelTypeToUse = chanType;

        else if ( ( chanOrder = get_channel_order_from_name( str ) ) != (cl_channel_order)-1 )
            gChannelOrderToUse = chanOrder;
        else
        {
            log_error( "ERROR: Unknown argument %d: %s.  Exiting....\n", i, str );
            return -1;
        }

    }

    if (testMethods == 0)
        testMethods = k1D | k2D | k3D | k1DArray | k2DArray;
    if ( gTypesToTest == 0 )
        gTypesToTest = kTestAllTypes;

    // Seed the random # generators
    if ( randomize )
    {
        gRandomSeed = (cl_uint) time( NULL );
        log_info( "Random seed: %u.\n", gRandomSeed );
        gReSeed = 1;
    }

    int error;
    // Get our platform
    error = clGetPlatformIDs(1, &platform, NULL);
    if ( error )
    {
        print_error( error, "Unable to get platform" );
        test_finish();
        return -1;
    }

    // Get our device
    error = clGetDeviceIDs(platform,  gDeviceType, 1, &device, NULL );
    if ( error )
    {
        print_error( error, "Unable to get specified device" );
        test_finish();
        return -1;
    }

    char deviceName[ 128 ], deviceVendor[ 128 ], deviceVersion[ 128 ];
    error = clGetDeviceInfo( device, CL_DEVICE_NAME, sizeof( deviceName ), deviceName, NULL );
    error |= clGetDeviceInfo( device, CL_DEVICE_VENDOR, sizeof( deviceVendor ), deviceVendor, NULL );
    error |= clGetDeviceInfo( device, CL_DEVICE_VERSION, sizeof( deviceVersion ), deviceVersion, NULL );
    if ( error != CL_SUCCESS )
    {
        print_error( error, "Unable to get device information" );
        test_finish();
        return -1;
    }
    log_info("Using compute device: Name = %s, Vendor = %s, Version = %s\n", deviceName, deviceVendor, deviceVersion );

    // Check for image support
    if (checkForImageSupport( device ) == CL_IMAGE_FORMAT_NOT_SUPPORTED) {
        log_info("Device does not support images. Skipping test.\n");
        test_finish();
        return 0;
    }

    // Create a context to test with
    context = clCreateContext( NULL, 1, &device, notify_callback, NULL, &error );
    if ( error != CL_SUCCESS )
    {
        print_error( error, "Unable to create testing context" );
        test_finish();
        return -1;
    }

    // Create a queue against the context
    queue = clCreateCommandQueueWithProperties( context, device, 0, &error );
    if ( error != CL_SUCCESS )
    {
        print_error( error, "Unable to create testing command queue" );
        test_finish();
        return -1;
    }

    if ( gTestSmallImages )
        log_info( "Note: Using small test images\n" );

    // Run the test now
    int ret = 0;
    for ( int test = k1D; test <= k3D; test <<= 1 )
    {
        if ( testMethods & test )
            ret += test_image_set( device, (MethodsToTest)test );
    }

    error = clFinish(queue);
    if (error)
        print_error(error, "clFinish failed.");

    if (gTestFailure == 0) {
        if (gTestCount > 1)
            log_info("PASSED %d of %d tests.\n", gTestCount, gTestCount);
        else
            log_info("PASSED test.\n");
    }
    else if (gTestFailure > 0) {
        if (gTestCount > 1)
            log_error("FAILED %d of %d tests.\n", gTestFailure, gTestCount);
        else
            log_error("FAILED test.\n");
    }

    // Clean up
    clReleaseCommandQueue(queue);
    clReleaseContext(context);
    test_finish();

    if (gTestFailure > 0)
        return gTestFailure;

    return ret;
}
<commit_msg>cl21: Convert images/clFillImage to testHarness (#93)<commit_after>//
// Copyright (c) 2017 The Khronos Group Inc.
//
// 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 "../../../test_common/harness/compat.h"

#include <stdio.h>
#include <string.h>

#if !defined(_WIN32)
#include <unistd.h>
#include <sys/time.h>
#endif

#include "../testBase.h"
#include "../../../test_common/harness/testHarness.h"

bool             gDebugTrace = false, gTestSmallImages = false, gTestMaxImages = false, gTestRounding = false, gEnablePitch = false;
int              gTypesToTest = 0;
cl_channel_type  gChannelTypeToUse = (cl_channel_type)-1;
cl_channel_order gChannelOrderToUse = (cl_channel_order)-1;
cl_device_type   gDeviceType = CL_DEVICE_TYPE_DEFAULT;
cl_context       context;
cl_command_queue queue;
static cl_device_id device;

extern int test_image_set( cl_device_id device, MethodsToTest testMethod );
static void printUsage( const char *execName );

#define MAX_ALLOWED_STD_DEVIATION_IN_MB        8.0

int test_1D(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
    return test_image_set(device, k1D);
}
int test_2D(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
    return test_image_set(device, k2D);
}
int test_3D(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
    return test_image_set(device, k3D);
}
int test_1Darray(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
    return test_image_set(device, k1DArray);
}
int test_2Darray(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
    return test_image_set(device, k2DArray);
}

basefn basefn_list[] = {
    test_1D,
    test_2D,
    test_3D,
    test_1Darray,
    test_2Darray,
};

const char *basefn_names[] = {
    "1D",
    "2D",
    "3D",
    "1Darray",
    "2Darray",
};

ct_assert((sizeof(basefn_names) / sizeof(basefn_names[0])) == (sizeof(basefn_list) / sizeof(basefn_list[0])));

int num_fns = sizeof(basefn_names) / sizeof(char *);

int main(int argc, const char *argv[])
{
    cl_platform_id   platform;
    cl_channel_type  chanType;
    cl_channel_order chanOrder;
    bool             randomize = false;

    test_start();

    checkDeviceTypeOverride( &gDeviceType );

    const char ** argList = (const char **)calloc( argc, sizeof( char*) );

    if( NULL == argList )
    {
        log_error( "Failed to allocate memory for argList array.\n" );
        return 1;
    }

    argList[0] = argv[0];
    size_t argCount = 1;

    // Parse arguments
    for ( int i = 1; i < argc; i++ )
    {
        if ( strcmp( argv[i], "cpu" ) == 0 || strcmp( argv[i], "CL_DEVICE_TYPE_CPU" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_CPU;
        else if ( strcmp( argv[i], "gpu" ) == 0 || strcmp( argv[i], "CL_DEVICE_TYPE_GPU" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_GPU;
        else if ( strcmp( argv[i], "accelerator" ) == 0 || strcmp( argv[i], "CL_DEVICE_TYPE_ACCELERATOR" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_ACCELERATOR;
        else if ( strcmp( argv[i], "CL_DEVICE_TYPE_DEFAULT" ) == 0 )
            gDeviceType = CL_DEVICE_TYPE_DEFAULT;

        else if ( strcmp( argv[i], "debug_trace" ) == 0 )
            gDebugTrace = true;

        else if ( strcmp( argv[i], "small_images" ) == 0 )
            gTestSmallImages = true;
        else if ( strcmp( argv[i], "max_images" ) == 0 )
            gTestMaxImages = true;

        else if ( strcmp( argv[i], "use_pitches" ) == 0 )
            gEnablePitch = true;

        else if ( strcmp( argv[i], "randomize" ) == 0 )
            randomize = true;

        else if( strcmp( argv[i], "int" ) == 0 )
            gTypesToTest |= kTestInt;
        else if( strcmp( argv[i], "uint" ) == 0 )
            gTypesToTest |= kTestUInt;
        else if( strcmp( argv[i], "float" ) == 0 )
            gTypesToTest |= kTestFloat;

        else if ( strcmp( argv[i], "--help" ) == 0 || strcmp( argv[i], "-h" ) == 0 )
        {
            printUsage( argv[ 0 ] );
            return -1;
        }

        else if ( ( chanType = get_channel_type_from_name( argv[i] ) ) != (cl_channel_type)-1 )
            gChannelTypeToUse = chanType;

        else if ( ( chanOrder = get_channel_order_from_name( argv[i] ) ) != (cl_channel_order)-1 )
            gChannelOrderToUse = chanOrder;
        else
        {
            argList[argCount] = argv[i];
            argCount++;
        }
    }

    if ( gTypesToTest == 0 )
        gTypesToTest = kTestAllTypes;

    // Seed the random # generators
    if ( randomize )
    {
        gRandomSeed = (cl_uint) time( NULL );
        log_info( "Random seed: %u.\n", gRandomSeed );
        gReSeed = 1;
    }

    int error;
    // Get our platform
    error = clGetPlatformIDs(1, &platform, NULL);
    if ( error )
    {
        print_error( error, "Unable to get platform" );
        test_finish();
        return -1;
    }

    // Get our device
    error = clGetDeviceIDs(platform,  gDeviceType, 1, &device, NULL );
    if ( error )
    {
        print_error( error, "Unable to get specified device" );
        test_finish();
        return -1;
    }

    char deviceName[ 128 ], deviceVendor[ 128 ], deviceVersion[ 128 ];
    error = clGetDeviceInfo( device, CL_DEVICE_NAME, sizeof( deviceName ), deviceName, NULL );
    error |= clGetDeviceInfo( device, CL_DEVICE_VENDOR, sizeof( deviceVendor ), deviceVendor, NULL );
    error |= clGetDeviceInfo( device, CL_DEVICE_VERSION, sizeof( deviceVersion ), deviceVersion, NULL );
    if ( error != CL_SUCCESS )
    {
        print_error( error, "Unable to get device information" );
        test_finish();
        return -1;
    }
    log_info("Using compute device: Name = %s, Vendor = %s, Version = %s\n", deviceName, deviceVendor, deviceVersion );

    // Check for image support
    if (checkForImageSupport( device ) == CL_IMAGE_FORMAT_NOT_SUPPORTED) {
        log_info("Device does not support images. Skipping test.\n");
        test_finish();
        return 0;
    }

    // Create a context to test with
    context = clCreateContext( NULL, 1, &device, notify_callback, NULL, &error );
    if ( error != CL_SUCCESS )
    {
        print_error( error, "Unable to create testing context" );
        test_finish();
        return -1;
    }

    // Create a queue against the context
    queue = clCreateCommandQueueWithProperties( context, device, 0, &error );
    if ( error != CL_SUCCESS )
    {
        print_error( error, "Unable to create testing command queue" );
        test_finish();
        return -1;
    }

    if ( gTestSmallImages )
        log_info( "Note: Using small test images\n" );

    int ret = parseAndCallCommandLineTests( argCount, argList, NULL, num_fns, basefn_list, basefn_names, true, 0, 0 );

    error = clFinish(queue);
    if (error)
        print_error(error, "clFinish failed.");

    if (gTestFailure == 0) {
        if (gTestCount > 1)
            log_info("PASSED %d of %d sub-tests.\n", gTestCount, gTestCount);
        else
            log_info("PASSED sub-test.\n");
    }
    else if (gTestFailure > 0) {
        if (gTestCount > 1)
            log_error("FAILED %d of %d sub-tests.\n", gTestFailure, gTestCount);
        else
            log_error("FAILED sub-test.\n");
    }

    // Clean up
    clReleaseCommandQueue(queue);
    clReleaseContext(context);
    free(argList);
    test_finish();

    return ret;
}

static void printUsage( const char *execName )
{
    const char *p = strrchr( execName, '/' );
    if ( p != NULL )
        execName = p + 1;

    log_info( "Usage: %s [options] [test_names]\n", execName );
    log_info( "Options:\n" );
    log_info( "\tThe following flags specify the types to test. They can be combined; if none are specified, all are tested:\n" );
    log_info( "\t\tint - Test integer fill\n" );
    log_info( "\t\tuint - Test unsigned integer fill\n" );
    log_info( "\t\tfloat - Test float fill\n" );
    log_info( "\n" );
    log_info( "\trandomize - Uses random seed\n" );
    log_info( "\tdebug_trace - Enables additional debug info logging\n" );
    log_info( "\tsmall_images - Runs every format through a loop of widths 1-13 and heights 1-9, instead of random sizes\n" );
    log_info( "\tmax_images - Runs every format through a set of size combinations with the max values, max values - 1, and max values / 128\n" );
    log_info( "\tuse_pitches - Enables row and slice pitches\n" );
    log_info( "\n" );
    log_info( "Test names:\n" );
    for( int i = 0; i < num_fns; i++ )
    {
        log_info( "\t%s\n", basefn_names[i] );
    }
    log_info( "\n" );
    log_info( "You may also use appropriate CL_ channel type and ordering constants.\n" );
}
<|endoftext|>


<commit_before>
//----------------------------  template.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2005, 2008, 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  template.cc  ---------------------------

// test VectorTools::interpolate_boundary_values for codim=1

#include "../tests.h"
#include <fstream>
#include <base/logstream.h>
#include <base/function_lib.h>
#include <grid/tria.h>
#include <grid/grid_in.h>
#include <dofs/dof_handler.h>
#include <fe/fe_q.h>
#include <numerics/vectors.h>

#include <string>

std::ofstream logfile("interpolate_boundary_values_01/output");

template <int dim, int spacedim>
void test(std::string filename) {
    Triangulation<dim, spacedim> tria;
    GridIn<dim, spacedim> gi;
    gi.attach_triangulation (tria);
    std::ifstream in (filename.c_str());
    gi.read_ucd (in);

    deallog << tria.n_active_cells() << " active cells" << std::endl;

    FE_Q<dim,spacedim> fe(2);
    DoFHandler<dim,spacedim> dof_handler (tria);
    dof_handler.distribute_dofs (fe);

    deallog << dof_handler.n_dofs() << " degrees of freedom" << std::endl;

    std::map<unsigned int, double> bv;
    VectorTools::interpolate_boundary_values (dof_handler,
					      0,
					      Functions::SquareFunction<spacedim>(),
					      bv);
    deallog << bv.size() << " boundary degrees of freedom" << std::endl;

    for (std::map<unsigned int, double>::const_iterator i = bv.begin();
	 i != bv.end(); ++i)
      deallog << i->first << ' ' << i->second << std::endl;
}

int main ()
{
  deallog.attach(logfile);
  deallog.depth_console(0);

  test<2,3>("grids/square.inp");
  test<2,3>("grids/sphere_1.inp");

  return 0;
}

<commit_msg>Fix file paths.<commit_after>
//----------------------------  template.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2005, 2008, 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  template.cc  ---------------------------

// test VectorTools::interpolate_boundary_values for codim=1

#include "../tests.h"
#include <fstream>
#include <base/logstream.h>
#include <base/function_lib.h>
#include <grid/tria.h>
#include <grid/grid_in.h>
#include <dofs/dof_handler.h>
#include <fe/fe_q.h>
#include <numerics/vectors.h>

#include <string>

std::ofstream logfile("interpolate_boundary_values_01/output");

template <int dim, int spacedim>
void test(std::string filename) {
    Triangulation<dim, spacedim> tria;
    GridIn<dim, spacedim> gi;
    gi.attach_triangulation (tria);
    std::ifstream in (filename.c_str());
    gi.read_ucd (in);

    deallog << tria.n_active_cells() << " active cells" << std::endl;

    FE_Q<dim,spacedim> fe(2);
    DoFHandler<dim,spacedim> dof_handler (tria);
    dof_handler.distribute_dofs (fe);

    deallog << dof_handler.n_dofs() << " degrees of freedom" << std::endl;

    std::map<unsigned int, double> bv;
    VectorTools::interpolate_boundary_values (dof_handler,
					      0,
					      Functions::SquareFunction<spacedim>(),
					      bv);
    deallog << bv.size() << " boundary degrees of freedom" << std::endl;

    for (std::map<unsigned int, double>::const_iterator i = bv.begin();
	 i != bv.end(); ++i)
      deallog << i->first << ' ' << i->second << std::endl;
}

int main ()
{
  deallog.attach(logfile);
  deallog.depth_console(0);

  test<2,3>("../codim_one/grids/square.inp");
  test<2,3>("../codim_one/grids/sphere_1.inp");

  return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl/io/vtk_lib_io.h>
#include <pcl/impl/point_types.hpp>
#include <pcl/registration/icp.h>
#include <pcl/visualization/cloud_viewer.h>
#include <fstream>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/organized_fast_mesh.h>
#include <sstream>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/filters/voxel_grid.h>
//#include <pcl/PCLPointCloud2.h>//1.7 only

using namespace std;

void ShowCloud (pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, int index)
{
	stringstream title;
       	title << "Cloud "<<index;
	pcl::visualization::CloudViewer viewer (title.str());
	viewer.showCloud (cloud);
	while (!viewer.wasStopped ())
	{
	}
}

void ReadCloud (pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, ifstream& file, int index, bool useBGR)
{
	char dsize[4];
	file.read (dsize, 4);
	cout<<"READ: "<<(int)(dsize[0])<<" "<<(int)(dsize[1])<<" "<<(int)(dsize[2])<<" "<<(int)(dsize[3])<<endl;
	ifstream::pos_type size = (unsigned char)dsize[0];
	size = size<<8;
	size += (unsigned char)dsize[1];
	size = size<<8;
	size += (unsigned char)dsize[2];
	size = size<<8;
	size += (unsigned char)dsize[3];
	cout<<"Got Size: "<<size<<" "<<endl;
	char* memblock = new char [10*size];
	file.read (memblock, 10*size);
	unsigned char* umem = reinterpret_cast<unsigned char*>(memblock);

	cloud->width    = size;
	cloud->height   = 1;
	cloud->is_dense = false;
	cloud->points.resize (cloud->width * cloud->height);
	for (size_t i = 0; i < cloud->points.size (); ++i)
	{
			cloud->points[i].x = (signed short)(((umem[i*10+0])<<8) + umem[i*10+1]);
			cloud->points[i].y = (signed short)(((umem[i*10+2])<<8) + umem[i*10+3]);
			cloud->points[i].z = -(signed short)(((umem[i*10+4])<<8) + umem[i*10+5]);
			cloud->points[i].x/=1000;
			cloud->points[i].y/=1000;
			cloud->points[i].z/=1000;

			if(i<5 || i+5>=cloud->points.size())
			{
				cout<<"Point: "<<i<<" "<<cloud->points[i].x<<" "<<cloud->points[i].y<<" "<<cloud->points[i].z<<endl;
			}
		if(!useBGR)
		{

			cloud->points[i].b = memblock[i*10+6];
			cloud->points[i].g = memblock[i*10+7];
			cloud->points[i].r = memblock[i*10+8];
			cloud->points[i].a = memblock[i*10+9];
		}
		else
		{
			if(index%3==0)
			{
				cloud->points[i].b = 255;
				cloud->points[i].g = 0;
				cloud->points[i].r = 0;
				cloud->points[i].a = 0;
			}
			else if (index%3==1)
			{
				cloud->points[i].b = 0;
				cloud->points[i].g = 255;
				cloud->points[i].r = 0;
				cloud->points[i].a = 0;

			}
			else
			{
				cloud->points[i].b = 0;
				cloud->points[i].g = 0;
				cloud->points[i].r = 255;
				cloud->points[i].a = 0;
			}
		}
	}

	cout<<"Set cloud"<<endl;

	delete[] memblock;
}

void SaveToPly(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, string name)
{
	pcl::PLYWriter plyWriter;
	plyWriter.write(name, *cloud);
}

void MakePolygons(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud)
{
	pcl::OrganizedFastMesh<pcl::PointXYZRGBA> ofm;
	ofm.setInputCloud(cloud);
	pcl::PolygonMesh polymesh;
	ofm.reconstruct(polymesh);
	cout<<"Done constructing mesh"<<endl;

	//pcl::io::savePolygonFileSTL("sample2.stl",polymesh);
/*
	pcl::PLYWriter plyWriter;
	plyWriter.writeASCII("sample.ply",cloud);*/
	/*
	// Normal estimation*
	pcl::NormalEstimation<pcl::PointXYZRGBA, pcl::Normal> n;
	pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
	pcl::search::KdTree<pcl::PointXYZRGBA>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGBA>);
	tree->setInputCloud (cloud);
	n.setInputCloud (cloud);n.setSearchMethod (tree);
	n.setKSearch (20);
	n.compute (*normals);
	// normals should not contain the point normals + surface curvatures

	// Concatenate the XYZ and normal fields*
	pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);
	pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
	// cloud_with_normals = cloud + normals

	// Create search tree*
	pcl::search::KdTree<pcl::PointNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointNormal>);
	tree2->setInputCloud (cloud_with_normals);

	// Initialize objects
	pcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3;
	pcl::PolygonMesh triangles;

	// Set the maximum distance between connected points (maximum edge length)
	gp3.setSearchRadius (0.025);

	// Set typical values for the parameters
	gp3.setMu (2.5);
	gp3.setMaximumNearestNeighbors (100);
	gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
	gp3.setMinimumAngle(M_PI/18); // 10 degrees
	gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
	gp3.setNormalConsistency(false);

	// Get result
	gp3.setInputCloud (cloud_with_normals);
	gp3.setSearchMethod (tree2);
	gp3.reconstruct (triangles);

	// Additional vertex information
	std::vector<int> parts = gp3.getPartIDs();
	std::vector<int> states = gp3.getPointStates();*/
}

void FilterCloud(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud)
{
	sensor_msgs::PointCloud2::Ptr msg (new sensor_msgs::PointCloud2);
	sensor_msgs::PointCloud2::Ptr cloud_filtered (new sensor_msgs::PointCloud2);
	//pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::toROSMsg (*cloud, *msg);

	std::cerr << "PointCloud before filtering: " << cloud->width * cloud->height
		<< endl;

	// Create the filtering object
	pcl::VoxelGrid<sensor_msgs::PointCloud2> sor;
	sor.setInputCloud (msg);
	sor.setLeafSize (10.0f, 10.0f, 10.0f);
	sor.filter (*cloud_filtered);

	std::cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height
		<< endl;
}

int main (int argc, char** argv)
{
	cout<<"Usage: [# iterations], [Use rgb], [ply file name], [use ICP]"<<endl;
	int iters = 3;
	if(argc>1)
	{
		sscanf(argv[1],"%d",&iters);
		cout<<"Iters: "<<iters<<endl;
	}

	bool useBGR = 1;
	int a;
	if(argc>2)
	{
		sscanf(argv[2],"%d",&a);
		useBGR = a!=0;
	}

	string plyFile = "sample2.ply";
	if(argc>3)
	{
		plyFile = string(argv[3]);
	}

	bool useICP = false;
	if(argc>4)
	{
		sscanf(argv[4],"%d",&a);
		useICP = a!=0;
	}

	bool savePly = true;
	if(argc>5)
	{
		sscanf(argv[5],"%d",&a);
		savePly = a!=0;
	}

	//  pcl::PointCloud<pcl::PointXYZRGBA> cloud, cloud2;
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud2 (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud3 (new pcl::PointCloud<pcl::PointXYZRGBA>);

	// Fill in the cloud data

	cloud2->width    = 1000;
	cloud2->height   = 1;
	cloud2->is_dense = false;
	cloud2->points.resize (cloud2->width * cloud2->height);

	//ifstream file ("C:\\Users\\Eric\\Documents\\Visual Studio 2013\\Projects\\KinectExplorer-WPF\\bin\\Debug\\KinectDepth2.txt", ios::in|ios::binary|ios::ate);
	ifstream file ("..\\data\\KinectDepth2.txt", ios::in|ios::binary|ios::ate);

	if (file.is_open())
	{
		file.seekg (0, ios::beg);
		for(int  i=0; i <iters; i++)
		{
			if(i==0)
			{
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ShowCloud(cloud,i);
				*cloud3+=*cloud;

			//	FilterCloud(cloud3);
				//MakePolygons(cloud);
			}
			else if(i%2==1)
			{
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ShowCloud(cloud2,i);
				if(useICP)
				{
					pcl::IterativeClosestPoint<pcl::PointXYZRGBA, pcl::PointXYZRGBA> icp;

					icp.setInputCloud (cloud2);
					icp.setInputTarget(cloud);
					icp.setMaximumIterations (2);
					icp.setMaxCorrespondenceDistance (1);

					cout<<"Trying to align!"<<endl;
					icp.align(*cloud2);
					Eigen::Matrix4f transformation = icp.getFinalTransformation ();

					cout << "has converged:" << icp.hasConverged() << " score: " << icp.getFitnessScore() << std::endl;

					cout << transformation << endl;
					cout<<"Size afer icp: "<<cloud2->size()<<" "<<cloud3->size()<<endl;
				}

				*cloud3+=*cloud2;
			}
			else if(i%2==0)
			{
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ShowCloud(cloud,i);

				if(useICP)
				{
					pcl::IterativeClosestPoint<pcl::PointXYZRGBA, pcl::PointXYZRGBA> icp;

					icp.setInputCloud (cloud);
					icp.setInputTarget(cloud2);
					icp.setMaximumIterations (2);
					icp.setMaxCorrespondenceDistance (1);

					cout<<"Trying to align!"<<endl;
					icp.align(*cloud);
					Eigen::Matrix4f transformation = icp.getFinalTransformation ();

					cout << "has converged:" << icp.hasConverged() << " score: " << icp.getFitnessScore() << std::endl;

					cout << transformation << endl;
					cout<<"Size afer icp: "<<cloud->size()<<" "<<cloud3->size()<<endl;
				}

				*cloud3+=*cloud;
			}
		}

		cout<<"FINAL CLOUD!"<<endl;
		ShowCloud(cloud3,-1);
		cout<<"Saving to ply file..."<<endl;
		if(savePly)
			SaveToPly(cloud3, plyFile);
		//MakePolygons(cloud3);
	}
	else cout << "Unable to open file";

	std::cout<<"DONE!\n";
	/*
	   pcl::io::savePCDFileASCII ("test_pcd.pcd", cloud);
	   std::cerr << "Saved " << cloud.points.size () << " data points to test_pcd.pcd." << std::endl;

	   for (size_t i = 0; i < cloud.points.size (); ++i)
	   std::cerr << "    " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
	   */
	return (0);
}

<commit_msg>changed Kinect2Mesh<commit_after>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl/io/vtk_lib_io.h>
#include <pcl/impl/point_types.hpp>
#include <pcl/registration/icp.h>
#include <pcl/visualization/cloud_viewer.h>
#include <fstream>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/organized_fast_mesh.h>
#include <sstream>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/filters/voxel_grid.h>
//#include <pcl/PCLPointCloud2.h>//1.7 only

using namespace std;

void ShowCloud (pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, int index)
{
	stringstream title;
       	title << "Cloud "<<index;
	pcl::visualization::CloudViewer viewer (title.str());
	viewer.showCloud (cloud);
	while (!viewer.wasStopped ())
	{
	}
}

void ReadCloud (pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, ifstream& file, int index, bool useBGR)
{
	char dsize[4];
	file.read (dsize, 4);
	cout<<"READ: "<<(int)(dsize[0])<<" "<<(int)(dsize[1])<<" "<<(int)(dsize[2])<<" "<<(int)(dsize[3])<<endl;
	ifstream::pos_type size = (unsigned char)dsize[0];
	size = size<<8;
	size += (unsigned char)dsize[1];
	size = size<<8;
	size += (unsigned char)dsize[2];
	size = size<<8;
	size += (unsigned char)dsize[3];
	cout<<"Got Size: "<<size<<" "<<endl;
	char* memblock = new char [10*size];
	file.read (memblock, 10*size);
	unsigned char* umem = reinterpret_cast<unsigned char*>(memblock);

	cloud->width    = size;
	cloud->height   = 1;
	cloud->is_dense = false;
	cloud->points.resize (cloud->width * cloud->height);
	for (size_t i = 0; i < cloud->points.size (); ++i)
	{
			cloud->points[i].x = (signed short)(((umem[i*10+0])<<8) + umem[i*10+1]);
			cloud->points[i].y = (signed short)(((umem[i*10+2])<<8) + umem[i*10+3]);
			cloud->points[i].z = -(signed short)(((umem[i*10+4])<<8) + umem[i*10+5]);
			cloud->points[i].x/=1000;
			cloud->points[i].y/=1000;
			cloud->points[i].z/=1000;

			if(i<5 || i+5>=cloud->points.size())
			{
				cout<<"Point: "<<i<<" "<<cloud->points[i].x<<" "<<cloud->points[i].y<<" "<<cloud->points[i].z<<endl;
			}
		if(!useBGR)
		{

			cloud->points[i].b = memblock[i*10+6];
			cloud->points[i].g = memblock[i*10+7];
			cloud->points[i].r = memblock[i*10+8];
			cloud->points[i].a = memblock[i*10+9];
		}
		else
		{
			if(index%3==0)
			{
				cloud->points[i].b = 255;
				cloud->points[i].g = 0;
				cloud->points[i].r = 0;
				cloud->points[i].a = 0;
			}
			else if (index%3==1)
			{
				cloud->points[i].b = 0;
				cloud->points[i].g = 255;
				cloud->points[i].r = 0;
				cloud->points[i].a = 0;

			}
			else
			{
				cloud->points[i].b = 0;
				cloud->points[i].g = 0;
				cloud->points[i].r = 255;
				cloud->points[i].a = 0;
			}
		}
	}

	cout<<"Set cloud"<<endl;

	delete[] memblock;
}

void SaveToPly(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, string name)
{
	pcl::PLYWriter plyWriter;
	plyWriter.write(name, *cloud);
}

void MakePolygons(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud)
{
	pcl::OrganizedFastMesh<pcl::PointXYZRGBA> ofm;
	ofm.setInputCloud(cloud);
	pcl::PolygonMesh polymesh;
	ofm.reconstruct(polymesh);
	cout<<"Done constructing mesh"<<endl;

	//pcl::io::savePolygonFileSTL("sample2.stl",polymesh);
/*
	pcl::PLYWriter plyWriter;
	plyWriter.writeASCII("sample.ply",cloud);*/
	/*
	// Normal estimation*
	pcl::NormalEstimation<pcl::PointXYZRGBA, pcl::Normal> n;
	pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
	pcl::search::KdTree<pcl::PointXYZRGBA>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGBA>);
	tree->setInputCloud (cloud);
	n.setInputCloud (cloud);n.setSearchMethod (tree);
	n.setKSearch (20);
	n.compute (*normals);
	// normals should not contain the point normals + surface curvatures

	// Concatenate the XYZ and normal fields*
	pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);
	pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
	// cloud_with_normals = cloud + normals

	// Create search tree*
	pcl::search::KdTree<pcl::PointNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointNormal>);
	tree2->setInputCloud (cloud_with_normals);

	// Initialize objects
	pcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3;
	pcl::PolygonMesh triangles;

	// Set the maximum distance between connected points (maximum edge length)
	gp3.setSearchRadius (0.025);

	// Set typical values for the parameters
	gp3.setMu (2.5);
	gp3.setMaximumNearestNeighbors (100);
	gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
	gp3.setMinimumAngle(M_PI/18); // 10 degrees
	gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
	gp3.setNormalConsistency(false);

	// Get result
	gp3.setInputCloud (cloud_with_normals);
	gp3.setSearchMethod (tree2);
	gp3.reconstruct (triangles);

	// Additional vertex information
	std::vector<int> parts = gp3.getPartIDs();
	std::vector<int> states = gp3.getPointStates();*/
}

void FilterCloud(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud)
{
	sensor_msgs::PointCloud2::Ptr msg (new sensor_msgs::PointCloud2);
	sensor_msgs::PointCloud2::Ptr cloud_filtered (new sensor_msgs::PointCloud2);
	//pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::toROSMsg (*cloud, *msg);

	std::cerr << "PointCloud before filtering: " << cloud->width * cloud->height
		<< endl;

	// Create the filtering object
	pcl::VoxelGrid<sensor_msgs::PointCloud2> sor;
	sor.setInputCloud (msg);
	sor.setLeafSize (10.0f, 10.0f, 10.0f);
	sor.filter (*cloud_filtered);

	std::cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height
		<< endl;
}

int main (int argc, char** argv)
{
	cout<<"Usage: [# iterations], [Use rgb], [ply file name], [use ICP]"<<endl;

	int iters = 3;
	if(argc>1)
	{
		sscanf(argv[1],"%d",&iters);
		cout<<"Iters: "<<iters<<endl;
	}

	bool useBGR = 1;
	int a;
	if(argc>2)
	{
		sscanf(argv[2],"%d",&a);
		useBGR = a!=0;
	}

	string plyFile = "sample2.ply";
	if(argc>3)
	{
		plyFile = string(argv[3]);
	}

	bool useICP = false;
	if(argc>4)
	{
		sscanf(argv[4],"%d",&a);
		useICP = a!=0;
	}

	bool savePly = true;
	if(argc>5)
	{
		sscanf(argv[5],"%d",&a);
		savePly = a!=0;
	}

	//  pcl::PointCloud<pcl::PointXYZRGBA> cloud, cloud2;
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud2 (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud3 (new pcl::PointCloud<pcl::PointXYZRGBA>);

	// Fill in the cloud data

	cloud2->width    = 1000;
	cloud2->height   = 1;
	cloud2->is_dense = false;
	cloud2->points.resize (cloud2->width * cloud2->height);

	//ifstream file ("C:\\Users\\Eric\\Documents\\Visual Studio 2013\\Projects\\KinectExplorer-WPF\\bin\\Debug\\KinectDepth2.txt", ios::in|ios::binary|ios::ate);
	ifstream file ("..\\data\\KinectDepth2.txt", ios::in|ios::binary|ios::ate);

	if (file.is_open())
	{
		file.seekg (0, ios::beg);
		for(int  i=0; i <iters; i++)
		{
			if(i==0)
			{
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ShowCloud(cloud,i);
				*cloud3+=*cloud;

			//	FilterCloud(cloud3);
				//MakePolygons(cloud);
			}
			else if(i%2==1)
			{
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ShowCloud(cloud2,i);
				if(useICP)
				{
					pcl::IterativeClosestPoint<pcl::PointXYZRGBA, pcl::PointXYZRGBA> icp;

					icp.setInputCloud (cloud2);
					icp.setInputTarget(cloud);
					icp.setMaximumIterations (2);
					icp.setMaxCorrespondenceDistance (1);

					cout<<"Trying to align!"<<endl;
					icp.align(*cloud2);
					Eigen::Matrix4f transformation = icp.getFinalTransformation ();

					cout << "has converged:" << icp.hasConverged() << " score: " << icp.getFitnessScore() << std::endl;

					cout << transformation << endl;
					cout<<"Size afer icp: "<<cloud2->size()<<" "<<cloud3->size()<<endl;
				}

				*cloud3+=*cloud2;
			}
			else if(i%2==0)
			{
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ShowCloud(cloud,i);

				if(useICP)
				{
					pcl::IterativeClosestPoint<pcl::PointXYZRGBA, pcl::PointXYZRGBA> icp;

					icp.setInputCloud (cloud);
					icp.setInputTarget(cloud2);
					icp.setMaximumIterations (2);
					icp.setMaxCorrespondenceDistance (1);

					cout<<"Trying to align!"<<endl;
					icp.align(*cloud);
					Eigen::Matrix4f transformation = icp.getFinalTransformation ();

					cout << "has converged:" << icp.hasConverged() << " score: " << icp.getFitnessScore() << std::endl;

					cout << transformation << endl;
					cout<<"Size afer icp: "<<cloud->size()<<" "<<cloud3->size()<<endl;
				}

				*cloud3+=*cloud;
			}
		}

		cout<<"FINAL CLOUD!"<<endl;
		ShowCloud(cloud3,-1);
		cout<<"Saving to ply file..."<<endl;
		if(savePly)
			SaveToPly(cloud3, plyFile);
		//MakePolygons(cloud3);
	}
	else cout << "Unable to open file";

	std::cout<<"DONE!\n";
	/*
	   pcl::io::savePCDFileASCII ("test_pcd.pcd", cloud);
	   std::cerr << "Saved " << cloud.points.size () << " data points to test_pcd.pcd." << std::endl;

	   for (size_t i = 0; i < cloud.points.size (); ++i)
	   std::cerr << "    " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
	   */
	return (0);
}

<|endoftext|>


<commit_before>/*
 * LPConverter.cpp
 *
 *  Created on: Nov 13, 2014
 *      Author: lukas
 */

#include "LPConverter.h"

#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <vector>

namespace ls2
{

LPConverter::LPConverter()
{
}

LPConverter::~LPConverter()
{
}

void LPConverter::convertToLP(const std::string &inputFile, const char delimiter, int k, const std::string &outputFile)
{
    DoubleMat inputPointsMatrix;
    file2DoubleMat(inputFile, delimiter).swap(inputPointsMatrix);
    DoubleMat costs;
    calculateLPCosts(inputPointsMatrix).swap(costs);

    std::ofstream os;
    os.open(outputFile.c_str());

    if (os.fail())
    {
        throw std::invalid_argument("File " + outputFile + " cannot be opened or created!");
    }
    if (!os.is_open())
    {
        throw std::invalid_argument("File " + outputFile + " cannot be opened or created!");
    }

    std::cout << "Writing results to " << outputFile.c_str() << "..." << std::endl;
    writeLPToFile(os, costs, k);

    os.close();
}

DoubleMat LPConverter::calculateLPCosts(const DoubleMat& inputPoints)
{
    int n = inputPoints.size();

    std::cout <<  "N: " << n << std::endl;

    DoubleMat costs(n, std::vector<double>(n, 0));

    for (int i = 0; i < n; i++)
    {
	    for (int j = 0; j < n; j++)
	    {
		    costs[i][j] = squaredEuclideanDistance(inputPoints[i], inputPoints[j]);
	    }
    }

    return costs;
}

void LPConverter::writeLPToFile(std::ofstream& os, const DoubleMat& costs, int k)
{
    int n = costs[0].size();

    // header
    os << "Minimize" << std::endl;
    os << "kmedian_2approximation:" << std::endl;

    // target function: sum c_ij*x_ij
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            os << std::fixed << costs[i][j] << "xi" << i << "j" << j;

            if ( (i == n-1) && (j == n-1) )
            {
                break;
            }

            os << " + ";
        }
    }
    os << std::endl;

    // restrictions header
    os << "Subject to" << std::endl;

    // restrictions: each city connected to at least one facility: foreach j in C sum x_ij >= 1
    for (int j = 0; j < n; j++)
    {
        os << "City_" << j << "_connected: ";
        for (int i = 0; i < n; i++)
        {
            os << "xi" << i << "" << "j" << j;

            if (i != n-1)
            {
                os << " + ";
            }
            else
            {
                os << " >= 1";
            }
        }
        os << std::endl;
    }

    // restrictions: connected facilities must be open: foreach i in F, j in C y_i - x_ij >= 0
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            os << "Facility_" << i << "_open_rsp_city_" << j << ": " << "yi" <<  i << " - " << "xi" << i << "j" << j << " >= 0" << std::endl;
        }
    }

    // restrictions: exactly k facilities are opened: sum -y_i >= -k
    os << "Exactly_k_facilities_opened: ";
    for (int i = 0; i < n; i++)
    {
        os << "-yi" << i << " ";
    }
    os << " >= " << "-" << k << std::endl;

    // relaxed ILP-restrictions i.e. non-negativity: foreach i in F, j in C x_ij >= 0
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            os << "xi" << i << "j" << j << " >= 0" << std::endl;
        }
    }
    // foreach i in F y_i >= 0
    for (int i = 0; i < n; i++)
    {
        os << "yi" << i << " >= 0" << std::endl;
    }

    // footer
    os << "End" << std::endl;
}

DoubleMat LPConverter::file2DoubleMat(const std::string &file, const char delimiter)
{
	std::ifstream is(file.c_str());

	if (is.fail())
	{
		throw std::invalid_argument("File " + file + " does not exist or cannot be opened!");
	}

	if (!is.is_open())
	{
		throw std::invalid_argument("File " + file + " does not exist or cannot be opened!");
	}

	DoubleMat doubleMat(0, std::vector<double>(0, 0));
	doubleMat.clear();

	std::string line;
	while (std::getline(is, line))
	{
		DoubleVec row(0);

		std::stringstream linestream(line);
		std::string value;
		while (std::getline(linestream, value, delimiter))
		{
			row.push_back(string2double(value));
		}
		doubleMat.push_back(row);
	}

	is.close();

	return doubleMat;
}

double LPConverter::string2double(const std::string &s)
{
	std::istringstream i(s);
	double x;

	if (!(i >> x))
		return 0;
	return x;
}

double LPConverter::squaredEuclideanDistance(const DoubleVec& v1, const DoubleVec& v2)
{
    if (v1.size() != v2.size())
    {
        throw std::invalid_argument("Euclidean distance can only be calculated for vectors of equal dimension!");
    }

    int dim = v1.size();
    double distance = 0.0;

    for (int i = 0; i < dim; i++)
    {
        distance += ( (v1[i] - v2[i]) * (v1[i] - v2[i]));
    }

    return distance;
}

} /* namespace ls2 */
<commit_msg>Added the option to generate restrictions without labels.<commit_after>/*
 * LPConverter.cpp
 *
 *  Created on: Nov 13, 2014
 *      Author: lukas
 */

#include "LPConverter.h"

#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <vector>

namespace ls2
{

LPConverter::LPConverter()
{
}

LPConverter::~LPConverter()
{
}

void LPConverter::convertToLP(const std::string &inputFile, const char delimiter, int k, const std::string &outputFile)
{
    DoubleMat inputPointsMatrix;
    file2DoubleMat(inputFile, delimiter).swap(inputPointsMatrix);
    DoubleMat costs;
    calculateLPCosts(inputPointsMatrix).swap(costs);

    std::ofstream os;
    os.open(outputFile.c_str());

    if (os.fail())
    {
        throw std::invalid_argument("File " + outputFile + " cannot be opened or created!");
    }
    if (!os.is_open())
    {
        throw std::invalid_argument("File " + outputFile + " cannot be opened or created!");
    }

    std::cout << "Writing results to " << outputFile.c_str() << "..." << std::endl;
    writeLPToFile(os, costs, k);

    os.close();
}

DoubleMat LPConverter::calculateLPCosts(const DoubleMat& inputPoints)
{
    int n = inputPoints.size();

    std::cout <<  "N: " << n << std::endl;

    DoubleMat costs(n, std::vector<double>(n, 0));

    for (int i = 0; i < n; i++)
    {
	    for (int j = 0; j < n; j++)
	    {
		    costs[i][j] = squaredEuclideanDistance(inputPoints[i], inputPoints[j]);
	    }
    }

    return costs;
}

void LPConverter::writeLPToFile(std::ofstream& os, const DoubleMat& costs, int k)
{
    int n = costs[0].size();

    // header
    os << "Minimize" << std::endl;
    os << "kmedian_2approximation:" << std::endl;

    // target function: sum c_ij*x_ij
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            os << std::fixed << costs[i][j] << "xi" << i << "j" << j;

            if ( (i == n-1) && (j == n-1) )
            {
                break;
            }

            os << " + ";
        }
    }
    os << std::endl;

    // restrictions header
    os << "Subject to" << std::endl;

    // restrictions: each city connected to at least one facility: foreach j in C sum x_ij >= 1
    for (int j = 0; j < n; j++)
    {
        //os << "City_" << j << "_connected: ";
        for (int i = 0; i < n; i++)
        {
            os << "xi" << i << "" << "j" << j;

            if (i != n-1)
            {
                os << " + ";
            }
            else
            {
                os << " >= 1";
            }
        }
        os << std::endl;
    }

    // restrictions: connected facilities must be open: foreach i in F, j in C y_i - x_ij >= 0
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            //os << "Facility_" << i << "_open_rsp_city_" << j << ": ";
            os << "yi" <<  i << " - " << "xi" << i << "j" << j << " >= 0" << std::endl;
        }
    }

    // restrictions: exactly k facilities are opened: sum -y_i >= -k
    //os << "Exactly_k_facilities_opened: ";
    for (int i = 0; i < n; i++)
    {
        os << "-yi" << i << " ";
    }
    os << " >= " << "-" << k << std::endl;

    // relaxed ILP-restrictions i.e. non-negativity: foreach i in F, j in C x_ij >= 0
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            os << "xi" << i << "j" << j << " >= 0" << std::endl;
        }
    }
    // foreach i in F y_i >= 0
    for (int i = 0; i < n; i++)
    {
        os << "yi" << i << " >= 0" << std::endl;
    }

    // footer
    os << "End" << std::endl;
}

DoubleMat LPConverter::file2DoubleMat(const std::string &file, const char delimiter)
{
	std::ifstream is(file.c_str());

	if (is.fail())
	{
		throw std::invalid_argument("File " + file + " does not exist or cannot be opened!");
	}

	if (!is.is_open())
	{
		throw std::invalid_argument("File " + file + " does not exist or cannot be opened!");
	}

	DoubleMat doubleMat(0, std::vector<double>(0, 0));
	doubleMat.clear();

	std::string line;
	while (std::getline(is, line))
	{
		DoubleVec row(0);

		std::stringstream linestream(line);
		std::string value;
		while (std::getline(linestream, value, delimiter))
		{
			row.push_back(string2double(value));
		}
		doubleMat.push_back(row);
	}

	is.close();

	return doubleMat;
}

double LPConverter::string2double(const std::string &s)
{
	std::istringstream i(s);
	double x;

	if (!(i >> x))
		return 0;
	return x;
}

double LPConverter::squaredEuclideanDistance(const DoubleVec& v1, const DoubleVec& v2)
{
    if (v1.size() != v2.size())
    {
        throw std::invalid_argument("Euclidean distance can only be calculated for vectors of equal dimension!");
    }

    int dim = v1.size();
    double distance = 0.0;

    for (int i = 0; i < dim; i++)
    {
        distance += ( (v1[i] - v2[i]) * (v1[i] - v2[i]));
    }

    return distance;
}

} /* namespace ls2 */
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <stdio.h>
#include "fnord-base/stdtypes.h"
#include "fnord-base/exception.h"
#include "fnord-base/test/unittest.h"
#include "fnord-msg/msg.h"
#include "src/schemas.cc"
#include "logjoin/LogJoinTarget.cc"
#include "JoinedSession.pb.h"

using namespace fnord;
using namespace cm;

UNIT_TEST(LogJoinTest);

typedef HashMap<String, HashMap<String, String>> StringMap;

LogJoinTarget mkTestTarget() {
  LogJoinTarget trgt(joinedSessionsSchema(), false);

  trgt.setNormalize([] (Language l, const String& q) { return q; });

  trgt.setGetField([] (const DocID& doc, const String& field) {
    return None<String>();
  });

  return trgt;
}

void printBuf(const Buffer& buf) {
  msg::MessageObject msg;
  msg::MessageDecoder::decode(buf, joinedSessionsSchema(), &msg);
  fnord::iputs("joined session: $0", msg::MessagePrinter::print(msg, joinedSessionsSchema()));
}

// query with click
// multiple queries
// report items in multiple batches (logenplaetze, normal, etc)
// cart // gmv matching
// field expansion // joining

TEST_CASE(LogJoinTest, SimpleQuery, [] () {
  auto t = 1432311555 * kMicrosPerSecond;
  auto trgt = mkTestTarget();
  TrackedSession sess;
  sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
    { "is", "p~101~p1,p~102~p2" },
    { "qstr~de", "blah" }
  });

  auto buf = trgt.trackedSessionToJoinedSession(sess);
  auto joined = msg::decode<JoinedSession>(buf);
  EXPECT_EQ(joined.num_cart_items(), 0);
  EXPECT_EQ(joined.cart_value_eurcents(), 0);
  EXPECT_EQ(joined.num_order_items(), 0);
  EXPECT_EQ(joined.gmv_eurcents(), 0);
  EXPECT_EQ(joined.first_seen_time(), 1432311555);

  EXPECT_EQ(joined.search_queries().size(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).query_string(), "blah");
  EXPECT_EQ(joined.search_queries().Get(0).query_string_normalized(), "blah");
  EXPECT_EQ(
    ProtoLanguage_Name(joined.search_queries().Get(0).language()),
    "LANGUAGE_DE");
  EXPECT_EQ(
    ProtoPageType_Name(joined.search_queries().Get(0).page_type()),
    "PAGETYPE_SEARCH_PAGE");
  //DaWanda Hack
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 2);

  EXPECT_EQ(joined.search_queries().Get(0).result_items().size(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).position(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).item_id(), "p~101");
  EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(0).clicked());

  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).position(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).item_id(), "p~102");
  EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(1).clicked());
});

TEST_CASE(LogJoinTest, ItemOrder, [] () {
  auto t = 1432311555 * kMicrosPerSecond;
  auto trgt = mkTestTarget();
  TrackedSession sess;
  sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
    { "q_cat", "1" },
    { "pg", "1" },
    { "is", "p~105~p5,p~106~p6" }
  });

  sess.insertLogline(t + 10 * kMicrosPerSecond, "v", "E2", URI::ParamList {
    { "i", "p~105"}
  });

  sess.insertLogline(t + 60 * kMicrosPerSecond, "c", "E1", URI::ParamList {
    { "s", "1"},
    { "is", "p~105~2~550~eur" },
  });

  auto buf = trgt.trackedSessionToJoinedSession(sess);
  auto joined = msg::decode<JoinedSession>(buf);
  EXPECT_EQ(joined.num_cart_items(), 1);
  EXPECT_EQ(joined.cart_value_eurcents(), 1100);
  EXPECT_EQ(joined.num_order_items(), 1);
  EXPECT_EQ(joined.gmv_eurcents(), 1100);
  EXPECT_EQ(joined.first_seen_time(), 1432311555);
  EXPECT_EQ(joined.first_last_time(), 1432311615);

  EXPECT_EQ(joined.cart_items().size(), 1);
  EXPECT_EQ(joined.cart_items().Get(0).time(), 1432311615);
  EXPECT_EQ(joined.cart_items().Get(0).item_id(), "p~105");
  EXPECT_EQ(joined.cart_items().Get(0).quantity(), 2);
  EXPECT_EQ(joined.cart_items().Get(0).price_cents(), 550);
  EXPECT_EQ(
    ProtoCurrency_Name(joined.cart_items().Get(0).currency()),
    "CURRENCY_EUR");
  EXPECT_EQ(joined.cart_items().Get(0).checkout_step(), 1);

  EXPECT_EQ(joined.search_queries().size(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 1100);
  EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 1100);
  EXPECT_EQ(joined.search_queries().Get(0).page(), 1);
  EXPECT_EQ(
    ProtoLanguage_Name(joined.search_queries().Get(0).language()),
    "LANGUAGE_UNKNOWN_LANGUAGE");
  EXPECT_EQ(
    ProtoPageType_Name(joined.search_queries().Get(0).page_type()),
    "PAGETYPE_CATALOG_PAGE");
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 0);

  EXPECT_EQ(joined.search_queries().Get(0).result_items().size(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).position(), 5);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).item_id(), "p~105");
  EXPECT_TRUE(joined.search_queries().Get(0).result_items().Get(0).clicked());

  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).position(), 6);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).item_id(), "p~106");
  EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(1).clicked());

  EXPECT_EQ(joined.item_visits().size(), 1);
  EXPECT_EQ(joined.item_visits().Get(0).time(), 1432311565);
  EXPECT_EQ(joined.item_visits().Get(0).item_id(), "p~105");
});

/*

TEST_CASE(LogJoinTest, Test1, [] () {
  auto loglines_txt = FileUtil::read("src/test_loglines.txt");
  auto loglines = StringUtil::split(loglines_txt.toString(), "\n");

  for (const auto& logline : loglines) {
    if (logline.length() == 0) {
      continue;
    }

    URI::ParamList params;
    URI::parseQueryString(logline, &params);

    String time;
    String evtype;
    String evid;
    for (auto p = params.begin(); p != params.end(); ) {
      switch (p->first[0]) {

        default:
          ++p;
          continue;

        case 't':
          time = p->second;
          break;

        case 'e':
          evtype = p->second;
          break;

        case 'c':
          Vector<String> cid = StringUtil::split(p->second, "~");
          evid = cid.at(1);
          break;
      }

      p = params.erase(p);
    }

    tracked_session.insertLogline(
      DateTime((uint64_t) std::stoull(time) * 1000000),
      evtype,
      evid,
      params);
  }

  auto joined_sessions_schema = joinedSessionsSchema();
  LogJoinTarget logjoin_target(joined_sessions_schema, false);

  StringMap fields;
  fields["p~62797695"]["category1"] = "4";

  auto getField = [fields] (const DocID& docid, const String& feature) -> Option<String> {

    auto it = fields.find(docid.docid);
    if (it != fields.end()) {
      auto field = it->second;
      auto it_ = field.find(feature);
      if (it_ != field.end()) {
        return Some(String(it_->second));
      }
    }

    return None<String>();
  };

  auto normalize = [] (Language lang, const String& query) -> String {
    return query;
  };

  logjoin_target.setGetField(getField);
  logjoin_target.setNormalize(normalize);
  Buffer session = logjoin_target.trackedSessionToJoinedSession(
    tracked_session);

  JoinedSession joined_session;
  joined_session.ParseFromString(session.toString());
});

*/
<commit_msg>LogJoinTest: multiple query batches and ad click<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <stdio.h>
#include "fnord-base/stdtypes.h"
#include "fnord-base/exception.h"
#include "fnord-base/test/unittest.h"
#include "fnord-msg/msg.h"
#include "src/schemas.cc"
#include "logjoin/LogJoinTarget.cc"
#include "JoinedSession.pb.h"

using namespace fnord;
using namespace cm;

UNIT_TEST(LogJoinTest);

typedef HashMap<String, HashMap<String, String>> StringMap;

LogJoinTarget mkTestTarget() {
  LogJoinTarget trgt(joinedSessionsSchema(), false);

  trgt.setNormalize([] (Language l, const String& q) { return q; });

  trgt.setGetField([] (const DocID& doc, const String& field) {
    return None<String>();
  });

  return trgt;
}

void printBuf(const Buffer& buf) {
  msg::MessageObject msg;
  msg::MessageDecoder::decode(buf, joinedSessionsSchema(), &msg);
  fnord::iputs("joined session: $0", msg::MessagePrinter::print(msg, joinedSessionsSchema()));
}

// multiple queries
// field expansion // joining

/*
 * Simple Search
 */
TEST_CASE(LogJoinTest, SimpleQuery, [] () {
  auto t = 1432311555 * kMicrosPerSecond;
  auto trgt = mkTestTarget();
  TrackedSession sess;
  sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
    { "is", "p~101~p1,p~102~p2" },
    { "qstr~de", "blah" }
  });

  auto buf = trgt.trackedSessionToJoinedSession(sess);
  auto joined = msg::decode<JoinedSession>(buf);
  EXPECT_EQ(joined.num_cart_items(), 0);
  EXPECT_EQ(joined.cart_value_eurcents(), 0);
  EXPECT_EQ(joined.num_order_items(), 0);
  EXPECT_EQ(joined.gmv_eurcents(), 0);
  EXPECT_EQ(joined.first_seen_time(), 1432311555);

  EXPECT_EQ(joined.search_queries().size(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).query_string(), "blah");
  EXPECT_EQ(joined.search_queries().Get(0).query_string_normalized(), "blah");
  EXPECT_EQ(
    ProtoLanguage_Name(joined.search_queries().Get(0).language()),
    "LANGUAGE_DE");
  EXPECT_EQ(
    ProtoPageType_Name(joined.search_queries().Get(0).page_type()),
    "PAGETYPE_SEARCH_PAGE");
  //DaWanda Hack
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 2);

  EXPECT_EQ(joined.search_queries().Get(0).result_items().size(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).position(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).item_id(), "p~101");
  EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(0).clicked());

  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).position(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).item_id(), "p~102");
  EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(1).clicked());
});

/*
 * Cart Item (checkout_step 1) and GMV
 */
TEST_CASE(LogJoinTest, ItemOrder, [] () {
  auto t = 1432311555 * kMicrosPerSecond;
  auto trgt = mkTestTarget();
  TrackedSession sess;
  sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
    { "q_cat", "1" },
    { "pg", "1" },
    { "is", "p~105~p5,p~106~p6" }
  });

  sess.insertLogline(t + 10 * kMicrosPerSecond, "v", "E2", URI::ParamList {
    { "i", "p~105"}
  });

  sess.insertLogline(t + 60 * kMicrosPerSecond, "c", "E1", URI::ParamList {
    { "s", "1"},
    { "is", "p~105~2~550~eur" },
  });

  auto buf = trgt.trackedSessionToJoinedSession(sess);
  auto joined = msg::decode<JoinedSession>(buf);
  EXPECT_EQ(joined.num_cart_items(), 1);
  EXPECT_EQ(joined.cart_value_eurcents(), 1100);
  EXPECT_EQ(joined.num_order_items(), 1);
  EXPECT_EQ(joined.gmv_eurcents(), 1100);
  EXPECT_EQ(joined.first_seen_time(), 1432311555);
  EXPECT_EQ(joined.first_last_time(), 1432311615);

  EXPECT_EQ(joined.cart_items().size(), 1);
  EXPECT_EQ(joined.cart_items().Get(0).time(), 1432311615);
  EXPECT_EQ(joined.cart_items().Get(0).item_id(), "p~105");
  EXPECT_EQ(joined.cart_items().Get(0).quantity(), 2);
  EXPECT_EQ(joined.cart_items().Get(0).price_cents(), 550);
  EXPECT_EQ(
    ProtoCurrency_Name(joined.cart_items().Get(0).currency()),
    "CURRENCY_EUR");
  EXPECT_EQ(joined.cart_items().Get(0).checkout_step(), 1);

  EXPECT_EQ(joined.search_queries().size(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 1100);
  EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 1100);
  EXPECT_EQ(joined.search_queries().Get(0).page(), 1);
  EXPECT_EQ(
    ProtoLanguage_Name(joined.search_queries().Get(0).language()),
    "LANGUAGE_UNKNOWN_LANGUAGE");
  EXPECT_EQ(
    ProtoPageType_Name(joined.search_queries().Get(0).page_type()),
    "PAGETYPE_CATALOG_PAGE");
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 0);

  EXPECT_EQ(joined.search_queries().Get(0).result_items().size(), 2);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).position(), 5);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).item_id(), "p~105");
  EXPECT_TRUE(joined.search_queries().Get(0).result_items().Get(0).clicked());

  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).position(), 6);
  EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).item_id(), "p~106");
  EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(1).clicked());

  EXPECT_EQ(joined.item_visits().size(), 1);
  EXPECT_EQ(joined.item_visits().Get(0).time(), 1432311565);
  EXPECT_EQ(joined.item_visits().Get(0).item_id(), "p~105");
});

/*
 * Multiple Query Batches and Ad click
 */
TEST_CASE(LogJoinTest, MultipleQueryBatches, [] () {
  auto t = 1432311555 * kMicrosPerSecond;
  auto trgt = mkTestTarget();
  TrackedSession sess;
  sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
    { "q_cat", "1" },
    { "pg", "1" },
    { "is", "p~105~p5,p~106~p6,p~107~p7,p~108~p8" }
  });

  sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
    { "q_cat", "1" },
    { "pg", "1" },
    { "is", "p~101~p1,p~102~p2,p~103~p3,p~104~p4" }
  });

  sess.insertLogline(t + 10 * kMicrosPerSecond, "v", "E2", URI::ParamList {
    { "i", "p~101"}
  });

  auto buf = trgt.trackedSessionToJoinedSession(sess);
  auto joined = msg::decode<JoinedSession>(buf);

  EXPECT_EQ(joined.num_cart_items(), 0);
  EXPECT_EQ(joined.cart_value_eurcents(), 0);
  EXPECT_EQ(joined.num_order_items(), 0);
  EXPECT_EQ(joined.gmv_eurcents(), 0);
  EXPECT_EQ(joined.first_seen_time(), 1432311555);
  EXPECT_EQ(joined.first_last_time(), 1432311565);

  EXPECT_EQ(joined.search_queries().size(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 8);
  EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 4);
  EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 1);
  EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 0);
  EXPECT_EQ(joined.search_queries().Get(0).page(), 1);
  EXPECT_EQ(
    ProtoLanguage_Name(joined.search_queries().Get(0).language()),
    "LANGUAGE_UNKNOWN_LANGUAGE");
  EXPECT_EQ(
    ProtoPageType_Name(joined.search_queries().Get(0).page_type()),
    "PAGETYPE_CATALOG_PAGE");
});

/*

TEST_CASE(LogJoinTest, Test1, [] () {
  auto loglines_txt = FileUtil::read("src/test_loglines.txt");
  auto loglines = StringUtil::split(loglines_txt.toString(), "\n");

  for (const auto& logline : loglines) {
    if (logline.length() == 0) {
      continue;
    }

    URI::ParamList params;
    URI::parseQueryString(logline, &params);

    String time;
    String evtype;
    String evid;
    for (auto p = params.begin(); p != params.end(); ) {
      switch (p->first[0]) {

        default:
          ++p;
          continue;

        case 't':
          time = p->second;
          break;

        case 'e':
          evtype = p->second;
          break;

        case 'c':
          Vector<String> cid = StringUtil::split(p->second, "~");
          evid = cid.at(1);
          break;
      }

      p = params.erase(p);
    }

    tracked_session.insertLogline(
      DateTime((uint64_t) std::stoull(time) * 1000000),
      evtype,
      evid,
      params);
  }

  auto joined_sessions_schema = joinedSessionsSchema();
  LogJoinTarget logjoin_target(joined_sessions_schema, false);

  StringMap fields;
  fields["p~62797695"]["category1"] = "4";

  auto getField = [fields] (const DocID& docid, const String& feature) -> Option<String> {

    auto it = fields.find(docid.docid);
    if (it != fields.end()) {
      auto field = it->second;
      auto it_ = field.find(feature);
      if (it_ != field.end()) {
        return Some(String(it_->second));
      }
    }

    return None<String>();
  };

  auto normalize = [] (Language lang, const String& query) -> String {
    return query;
  };

  logjoin_target.setGetField(getField);
  logjoin_target.setNormalize(normalize);
  Buffer session = logjoin_target.trackedSessionToJoinedSession(
    tracked_session);

  JoinedSession joined_session;
  joined_session.ParseFromString(session.toString());
});

*/
<|endoftext|>


<commit_before>/*
 *
 *  Copyright 2008-2012 NVIDIA Corporation
 *
 *  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 <thrust/random/normal_distribution.h>
#include <thrust/random/uniform_real_distribution.h>
#include <thrust/detail/cstdint.h>
#include <thrust/detail/integer_traits.h>
#include <cmath>

namespace thrust
{

namespace random
{

template<typename RealType>
  normal_distribution<RealType>
    ::normal_distribution(RealType a, RealType b)
      :super_t(),m_param(a,b)
{
} // end normal_distribution::normal_distribution()

template<typename RealType>
  normal_distribution<RealType>
    ::normal_distribution(const param_type &parm)
      :super_t(),m_param(parm)
{
} // end normal_distribution::normal_distribution()

template<typename RealType>
  void normal_distribution<RealType>
    ::reset(void)
{
  super_t::reset();
} // end normal_distribution::reset()

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename normal_distribution<RealType>::result_type
      normal_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng)
{
  return operator()(urng, m_param);
} // end normal_distribution::operator()()

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename normal_distribution<RealType>::result_type
      normal_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng,
                     const param_type &parm)
{
  return super_t::sample(urng, parm.first, parm.second);
} // end normal_distribution::operator()()

template<typename RealType>
  typename normal_distribution<RealType>::param_type
    normal_distribution<RealType>
      ::param(void) const
{
  return m_param;
} // end normal_distribution::param()

template<typename RealType>
  void normal_distribution<RealType>
    ::param(const param_type &parm)
{
  m_param = parm;
} // end normal_distribution::param()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::min THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
  // XXX we should use numeric_limits, but, CUDA
  return -INFINITY;
} // end normal_distribution::min()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::max THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
  // XXX we should use numeric_limits, but, CUDA
  return INFINITY;
} // end normal_distribution::max()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::mean(void) const
{
  return m_param.first;
} // end normal_distribution::mean()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::stddev(void) const
{
  return m_param.second;
} // end normal_distribution::stddev()

template<typename RealType>
  bool normal_distribution<RealType>
    ::equal(const normal_distribution &rhs) const
{
  return m_param == rhs.param();
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_ostream<CharT,Traits>&
      normal_distribution<RealType>
        ::stream_out(std::basic_ostream<CharT,Traits> &os) const
{
  typedef std::basic_ostream<CharT,Traits> ostream_type;
  typedef typename ostream_type::ios_base  ios_base;

  // save old flags and fill character
  const typename ios_base::fmtflags flags = os.flags();
  const CharT fill = os.fill();

  const CharT space = os.widen(' ');
  os.flags(ios_base::dec | ios_base::fixed | ios_base::left);
  os.fill(space);

  os << mean() << space << stddev();

  // restore old flags and fill character
  os.flags(flags);
  os.fill(fill);
  return os;
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_istream<CharT,Traits>&
      normal_distribution<RealType>
        ::stream_in(std::basic_istream<CharT,Traits> &is)
{
  typedef std::basic_istream<CharT,Traits> istream_type;
  typedef typename istream_type::ios_base  ios_base;

  // save old flags
  const typename ios_base::fmtflags flags = is.flags();

  is.flags(ios_base::skipws);

  is >> m_param.first >> m_param.second;

  // restore old flags
  is.flags(flags);
  return is;
}

template<typename RealType>
bool operator==(const normal_distribution<RealType> &lhs,
                const normal_distribution<RealType> &rhs)
{
  return thrust::random::detail::random_core_access::equal(lhs,rhs);
}

template<typename RealType>
bool operator!=(const normal_distribution<RealType> &lhs,
                const normal_distribution<RealType> &rhs)
{
  return !(lhs == rhs);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits> &os,
           const normal_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_out(os,d);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits> &is,
           normal_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_in(is,d);
}

} // end random

} // end thrust

<commit_msg>The macro INFINITY is not portable, so use a type punning trick to derive a literal for fp inf.<commit_after>/*
 *
 *  Copyright 2008-2012 NVIDIA Corporation
 *
 *  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 <thrust/random/normal_distribution.h>
#include <thrust/random/uniform_real_distribution.h>
#include <thrust/detail/cstdint.h>
#include <thrust/detail/integer_traits.h>

// for floating point infinity
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC
#include <math_constants.h>
#else
#include <limits>
#endif

namespace thrust
{

namespace random
{

template<typename RealType>
  normal_distribution<RealType>
    ::normal_distribution(RealType a, RealType b)
      :super_t(),m_param(a,b)
{
} // end normal_distribution::normal_distribution()

template<typename RealType>
  normal_distribution<RealType>
    ::normal_distribution(const param_type &parm)
      :super_t(),m_param(parm)
{
} // end normal_distribution::normal_distribution()

template<typename RealType>
  void normal_distribution<RealType>
    ::reset(void)
{
  super_t::reset();
} // end normal_distribution::reset()

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename normal_distribution<RealType>::result_type
      normal_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng)
{
  return operator()(urng, m_param);
} // end normal_distribution::operator()()

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename normal_distribution<RealType>::result_type
      normal_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng,
                     const param_type &parm)
{
  return super_t::sample(urng, parm.first, parm.second);
} // end normal_distribution::operator()()

template<typename RealType>
  typename normal_distribution<RealType>::param_type
    normal_distribution<RealType>
      ::param(void) const
{
  return m_param;
} // end normal_distribution::param()

template<typename RealType>
  void normal_distribution<RealType>
    ::param(const param_type &parm)
{
  m_param = parm;
} // end normal_distribution::param()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::min THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
  return -this->max();
} // end normal_distribution::min()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::max THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
  // XXX this solution is pretty terrible
  // we can't use numeric_traits<RealType>::max because nvcc will
  // complain that it is a __host__ function
  union
  {
    thrust::detail::uint32_t inf_as_int;
    float result;
  } hack;

  hack.inf_as_int = 0x7f800000u;

  return hack.result;
} // end normal_distribution::max()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::mean(void) const
{
  return m_param.first;
} // end normal_distribution::mean()

template<typename RealType>
  typename normal_distribution<RealType>::result_type
    normal_distribution<RealType>
      ::stddev(void) const
{
  return m_param.second;
} // end normal_distribution::stddev()

template<typename RealType>
  bool normal_distribution<RealType>
    ::equal(const normal_distribution &rhs) const
{
  return m_param == rhs.param();
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_ostream<CharT,Traits>&
      normal_distribution<RealType>
        ::stream_out(std::basic_ostream<CharT,Traits> &os) const
{
  typedef std::basic_ostream<CharT,Traits> ostream_type;
  typedef typename ostream_type::ios_base  ios_base;

  // save old flags and fill character
  const typename ios_base::fmtflags flags = os.flags();
  const CharT fill = os.fill();

  const CharT space = os.widen(' ');
  os.flags(ios_base::dec | ios_base::fixed | ios_base::left);
  os.fill(space);

  os << mean() << space << stddev();

  // restore old flags and fill character
  os.flags(flags);
  os.fill(fill);
  return os;
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_istream<CharT,Traits>&
      normal_distribution<RealType>
        ::stream_in(std::basic_istream<CharT,Traits> &is)
{
  typedef std::basic_istream<CharT,Traits> istream_type;
  typedef typename istream_type::ios_base  ios_base;

  // save old flags
  const typename ios_base::fmtflags flags = is.flags();

  is.flags(ios_base::skipws);

  is >> m_param.first >> m_param.second;

  // restore old flags
  is.flags(flags);
  return is;
}

template<typename RealType>
bool operator==(const normal_distribution<RealType> &lhs,
                const normal_distribution<RealType> &rhs)
{
  return thrust::random::detail::random_core_access::equal(lhs,rhs);
}

template<typename RealType>
bool operator!=(const normal_distribution<RealType> &lhs,
                const normal_distribution<RealType> &rhs)
{
  return !(lhs == rhs);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits> &os,
           const normal_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_out(os,d);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits> &is,
           normal_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_in(is,d);
}

} // end random

} // end thrust

<|endoftext|>