<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "objectmanager.h"

#include "selectionmanager.h"
#include "newobjectcommand.h"
#include "deleteobjectcommand.h"
#include "propertychangedcommand.h"
#include "historymanager.h"

#include <core/debughelper.h>
#include <engine/gameproject.h>
#include <engine/gameobject.h>
#include <engine/scene.h>
#include <engine/game.h>
#include <engine/component.h>

#include <KDE/KLocalizedString>
#include <KDE/KMimeType>
#include <KDE/KDirWatch>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QStringBuilder>

using namespace GluonCreator;

template<> GLUON_CREATOR_VISIBILITY ObjectManager* GluonCore::Singleton<ObjectManager>::m_instance = 0;

QString
ObjectManager::humanifyClassName( const QString& fixThis, bool justRemoveNamespace ) const
{
    QString fixedString;
    const QString classname = fixThis.right( fixThis.length() - fixThis.lastIndexOf( ':' ) - 1 );
    if( justRemoveNamespace )
        return classname;
    const int length = classname.size();
    for( int i = 0; i < length; ++i )
    {
        const QChar current = classname.at( i );
        if( i == 0 )
        {
            // Always upper-case the first word, whether it is or not...
            fixedString = current.toUpper();
        }
        else
        {
            if( current.isUpper() )
            {
                fixedString = fixedString % ' ' % current;
            }
            else
            {
                fixedString = fixedString % current;
            }
        }
    }
    return fixedString;
}

GluonEngine::Asset* ObjectManager::createNewAsset( const QString& fileName )
{
    DEBUG_BLOCK
    KMimeType::Ptr type = KMimeType::findByFileContent( fileName );
    DEBUG_TEXT( QString( "Creating asset for file %1 of mimetype %2" ).arg( fileName ).arg( type->name() ) );

    GluonCore::GluonObject* newasset = GluonCore::GluonObjectFactory::instance()->instantiateObjectByMimetype( type->name() );
    if( newasset )
    {
        GluonEngine::Asset* newChild = static_cast<GluonEngine::Asset*>( newasset );
        setupAsset( newChild, fileName );
        return newChild;
    }

    return 0;
}

GluonEngine::Asset* ObjectManager::createNewAsset( const QString& className, const QString& fileName )
{
    DEBUG_BLOCK
    GluonCore::GluonObject* newChild = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( className );
    GluonEngine::Asset* newAsset = qobject_cast< GluonEngine::Asset* >( newChild );
    if( newAsset )
    {
        setupAsset( newAsset, fileName );
        return newAsset;
    }

    return 0;
}

void ObjectManager::setupAsset( GluonEngine::Asset* newAsset, const QString& fileName )
{
    GluonEngine::Game::instance()->gameProject()->addChild( newAsset );
    newAsset->setGameProject( GluonEngine::Game::instance()->gameProject() );

    QFileInfo info( fileName );
    newAsset->setName( info.fileName() );

    if( !QDir::current().exists( "Assets" ) )
        QDir::current().mkdir( "Assets" );

    QUrl newLocation( QString( "Assets/%1" ).arg( newAsset->fullyQualifiedFileName() ) );

    QFile( fileName ).copy( newLocation.toLocalFile() );

    newAsset->setFile( newLocation );
    newAsset->load();

    QString path( newAsset->absolutePath() );
    m_assets.insert( path, newAsset );
    KDirWatch::self()->addFile( path );

    HistoryManager::instance()->addCommand( new NewObjectCommand( newAsset ) );
}

void ObjectManager::deleteGameObject( GluonEngine::GameObject* object )
{
    HistoryManager::instance()->addCommand( new DeleteObjectCommand( object, object->parentGameObject() ) );
}

void ObjectManager::changeProperty( GluonCore::GluonObject* object, QString& property, QVariant& oldValue, QVariant& newValue )
{
    HistoryManager::instance()->addCommand( new PropertyChangedCommand( object, property, oldValue, newValue ) );
}

GluonEngine::Component* ObjectManager::createNewComponent( const QString& type, GluonEngine::GameObject* parent )
{
    DEBUG_BLOCK
    GluonCore::GluonObject* newObj = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( type );
    if( newObj )
    {
        newObj->setName( humanifyClassName( newObj->metaObject()->className(), true ) );

        GluonEngine::Component* comp = qobject_cast<GluonEngine::Component*>( newObj );
        parent->addComponent( comp );

        // Initialize the component
        comp->initialize();

        emit newComponent( comp );

        HistoryManager::instance()->addCommand( new NewObjectCommand( comp ) );

        return comp;
    }
    return 0;
}

GluonEngine::GameObject* ObjectManager::createNewGameObject()
{
    DEBUG_FUNC_NAME
    GluonEngine::GameObject* newObj = new GluonEngine::GameObject();
    newObj->setName( humanifyClassName( newObj->metaObject()->className(), false ) );
    DEBUG_TEXT( QString( "Creating object: %1" ).arg( newObj->name() ) );

    SelectionManager::SelectionList selection = SelectionManager::instance()->selection();
    if( selection.size() > 0 )
    {
        GluonEngine::GameObject* obj = qobject_cast<GluonEngine::GameObject*>( selection.at( 0 ) );
        if( obj )
        {
            DEBUG_TEXT( QString( "Item %1 selected in Scene tree - assign new object as child" ).arg( obj->fullyQualifiedName() ) );
            obj->addChild( newObj );
        }
    }

    if( newObj->parentGameObject() == 0 )
    {
        DEBUG_TEXT( QString( "No parent game object yet - assign as child to Scene root" ) );
        GluonEngine::Game::instance()->currentScene()->sceneContents()->addChild( newObj );
    }

    emit newGameObject( newObj );

    HistoryManager::instance()->addCommand( new NewObjectCommand( newObj ) );

    return newObj;
}

GluonEngine::Scene* ObjectManager::createNewScene()
{
    GluonEngine::Scene* newScn = new GluonEngine::Scene();
    newScn->setName( i18n( "NewScene" ) );
    newScn->setGameProject( GluonEngine::Game::instance()->gameProject() );
    GluonEngine::Game::instance()->gameProject()->addChild( newScn );

    emit newScene( newScn );

    HistoryManager::instance()->addCommand( new NewObjectCommand( newScn ) );

    return newScn;
}

void ObjectManager::startAssetsWatch()
{
    DEBUG_FUNC_NAME
    QObjectList assets = GluonEngine::Game::instance()->gameProject()->children();
    foreach( QObject* child, assets )
    {
        GluonEngine::Asset* asset = qobject_cast<GluonEngine::Asset*>( child );
        if( asset )
        {
            QString path( asset->absolutePath() );
            DEBUG_TEXT( QString( "Watching %1 for changes." ).arg( path ) );
            KDirWatch::self()->addFile( path );
            m_assets.insert( path, asset );
        }
    }
}

void ObjectManager::assetDirty( const QString& file)
{
    GluonEngine::Asset* asset = m_assets.value(file);
    if( asset )
    {
        asset->reload();
    }
}

void ObjectManager::assetDeleted( const QString& file)
{
    m_assets.remove(file);
    KDirWatch::self()->removeFile( file );
}

void ObjectManager::assetDeleted( GluonEngine::Asset* asset )
{
    assetDeleted( asset->absolutePath() );
}

ObjectManager::ObjectManager()
{
    m_objectId = 0;
    m_sceneId = 0;

    connect( KDirWatch::self(), SIGNAL( dirty( const QString& ) ), this, SLOT( assetDirty( const QString& ) ) );
}

ObjectManager::~ObjectManager()
{

}

//#include "objectmanager.moc"
<commit_msg>Connect to the created() signal of KDirWatch too; redraw everything after an asset reload.<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "objectmanager.h"

#include "selectionmanager.h"
#include "newobjectcommand.h"
#include "deleteobjectcommand.h"
#include "propertychangedcommand.h"
#include "historymanager.h"

#include <core/debughelper.h>
#include <engine/gameproject.h>
#include <engine/gameobject.h>
#include <engine/scene.h>
#include <engine/game.h>
#include <engine/component.h>

#include <KDE/KLocalizedString>
#include <KDE/KMimeType>
#include <KDE/KDirWatch>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QStringBuilder>

using namespace GluonCreator;

template<> GLUON_CREATOR_VISIBILITY ObjectManager* GluonCore::Singleton<ObjectManager>::m_instance = 0;

QString
ObjectManager::humanifyClassName( const QString& fixThis, bool justRemoveNamespace ) const
{
    QString fixedString;
    const QString classname = fixThis.right( fixThis.length() - fixThis.lastIndexOf( ':' ) - 1 );
    if( justRemoveNamespace )
        return classname;
    const int length = classname.size();
    for( int i = 0; i < length; ++i )
    {
        const QChar current = classname.at( i );
        if( i == 0 )
        {
            // Always upper-case the first word, whether it is or not...
            fixedString = current.toUpper();
        }
        else
        {
            if( current.isUpper() )
            {
                fixedString = fixedString % ' ' % current;
            }
            else
            {
                fixedString = fixedString % current;
            }
        }
    }
    return fixedString;
}

GluonEngine::Asset* ObjectManager::createNewAsset( const QString& fileName )
{
    DEBUG_BLOCK
    KMimeType::Ptr type = KMimeType::findByFileContent( fileName );
    DEBUG_TEXT( QString( "Creating asset for file %1 of mimetype %2" ).arg( fileName ).arg( type->name() ) );

    GluonCore::GluonObject* newasset = GluonCore::GluonObjectFactory::instance()->instantiateObjectByMimetype( type->name() );
    if( newasset )
    {
        GluonEngine::Asset* newChild = static_cast<GluonEngine::Asset*>( newasset );
        setupAsset( newChild, fileName );
        return newChild;
    }

    return 0;
}

GluonEngine::Asset* ObjectManager::createNewAsset( const QString& className, const QString& fileName )
{
    DEBUG_BLOCK
    GluonCore::GluonObject* newChild = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( className );
    GluonEngine::Asset* newAsset = qobject_cast< GluonEngine::Asset* >( newChild );
    if( newAsset )
    {
        setupAsset( newAsset, fileName );
        return newAsset;
    }

    return 0;
}

void ObjectManager::setupAsset( GluonEngine::Asset* newAsset, const QString& fileName )
{
    GluonEngine::Game::instance()->gameProject()->addChild( newAsset );
    newAsset->setGameProject( GluonEngine::Game::instance()->gameProject() );

    QFileInfo info( fileName );
    newAsset->setName( info.fileName() );

    if( !QDir::current().exists( "Assets" ) )
        QDir::current().mkdir( "Assets" );

    QUrl newLocation( QString( "Assets/%1" ).arg( newAsset->fullyQualifiedFileName() ) );

    QFile( fileName ).copy( newLocation.toLocalFile() );

    newAsset->setFile( newLocation );
    newAsset->load();

    QString path( newAsset->absolutePath() );
    m_assets.insert( path, newAsset );
    KDirWatch::self()->addFile( path );

    HistoryManager::instance()->addCommand( new NewObjectCommand( newAsset ) );
}

void ObjectManager::deleteGameObject( GluonEngine::GameObject* object )
{
    HistoryManager::instance()->addCommand( new DeleteObjectCommand( object, object->parentGameObject() ) );
}

void ObjectManager::changeProperty( GluonCore::GluonObject* object, QString& property, QVariant& oldValue, QVariant& newValue )
{
    HistoryManager::instance()->addCommand( new PropertyChangedCommand( object, property, oldValue, newValue ) );
}

GluonEngine::Component* ObjectManager::createNewComponent( const QString& type, GluonEngine::GameObject* parent )
{
    DEBUG_BLOCK
    GluonCore::GluonObject* newObj = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( type );
    if( newObj )
    {
        newObj->setName( humanifyClassName( newObj->metaObject()->className(), true ) );

        GluonEngine::Component* comp = qobject_cast<GluonEngine::Component*>( newObj );
        parent->addComponent( comp );

        // Initialize the component
        comp->initialize();

        emit newComponent( comp );

        HistoryManager::instance()->addCommand( new NewObjectCommand( comp ) );

        return comp;
    }
    return 0;
}

GluonEngine::GameObject* ObjectManager::createNewGameObject()
{
    DEBUG_FUNC_NAME
    GluonEngine::GameObject* newObj = new GluonEngine::GameObject();
    newObj->setName( humanifyClassName( newObj->metaObject()->className(), false ) );
    DEBUG_TEXT( QString( "Creating object: %1" ).arg( newObj->name() ) );

    SelectionManager::SelectionList selection = SelectionManager::instance()->selection();
    if( selection.size() > 0 )
    {
        GluonEngine::GameObject* obj = qobject_cast<GluonEngine::GameObject*>( selection.at( 0 ) );
        if( obj )
        {
            DEBUG_TEXT( QString( "Item %1 selected in Scene tree - assign new object as child" ).arg( obj->fullyQualifiedName() ) );
            obj->addChild( newObj );
        }
    }

    if( newObj->parentGameObject() == 0 )
    {
        DEBUG_TEXT( QString( "No parent game object yet - assign as child to Scene root" ) );
        GluonEngine::Game::instance()->currentScene()->sceneContents()->addChild( newObj );
    }

    emit newGameObject( newObj );

    HistoryManager::instance()->addCommand( new NewObjectCommand( newObj ) );

    return newObj;
}

GluonEngine::Scene* ObjectManager::createNewScene()
{
    GluonEngine::Scene* newScn = new GluonEngine::Scene();
    newScn->setName( i18n( "NewScene" ) );
    newScn->setGameProject( GluonEngine::Game::instance()->gameProject() );
    GluonEngine::Game::instance()->gameProject()->addChild( newScn );

    emit newScene( newScn );

    HistoryManager::instance()->addCommand( new NewObjectCommand( newScn ) );

    return newScn;
}

void ObjectManager::startAssetsWatch()
{
    DEBUG_FUNC_NAME
    QObjectList assets = GluonEngine::Game::instance()->gameProject()->children();
    foreach( QObject* child, assets )
    {
        GluonEngine::Asset* asset = qobject_cast<GluonEngine::Asset*>( child );
        if( asset )
        {
            QString path( asset->absolutePath() );
            DEBUG_TEXT( QString( "Watching %1 for changes." ).arg( path ) );
            KDirWatch::self()->addFile( path );
            m_assets.insert( path, asset );
        }
    }
}

void ObjectManager::assetDirty( const QString& file)
{
    GluonEngine::Asset* asset = m_assets.value(file);
    if( asset )
    {
        asset->reload();
        GluonEngine::Game::instance()->drawAll();
    }
}

void ObjectManager::assetDeleted( const QString& file)
{
    m_assets.remove(file);
    KDirWatch::self()->removeFile( file );
}

void ObjectManager::assetDeleted( GluonEngine::Asset* asset )
{
    assetDeleted( asset->absolutePath() );
}

ObjectManager::ObjectManager()
{
    m_objectId = 0;
    m_sceneId = 0;

    connect( KDirWatch::self(), SIGNAL( dirty( const QString& ) ), this, SLOT( assetDirty( const QString& ) ) );
    connect( KDirWatch::self(), SIGNAL( created( const QString& ) ), this, SLOT( assetDirty( const QString& ) ) );
}

ObjectManager::~ObjectManager()
{

}

//#include "objectmanager.moc"
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include<stdio.h>
#include "profiler_header.h"
#pragma comment(lib, "Pdh.lib")

namespace dsn {
    namespace tools {
        /*bool PROFILER_PDH::install()
        {
            HModule = LoadLibraryEx("Pdh.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
            if (HModule == NULL)
            {
                printf("Cannot open library\n");
                return false;
            }

            status = PdhOpenQuery(0, 0, &HQuery);
            if (status != ERROR_SUCCESS)
            {
                printf("Cannot open query\n");
                Error_Display();
                return false;
            }
            CounterHandle_Time = (HCOUNTER*)GlobalAlloc(GPTR, sizeof(HCOUNTER));

            status = PdhAddCounter(HQuery, "\\Processor Information(_Total)\\% Processor Time", 0, CounterHandle_Time);
            if (status != ERROR_SUCCESS)
            {
                printf("Add counter error\n");
                Error_Display();
                return false;
            }

            status = PdhCollectQueryData(HQuery);
            if (status != ERROR_SUCCESS)
            {
                printf("Query Collection Error\n");
                Error_Display();
                return false;
            }

            std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(shared_io_service::instance().ios));
            timer->expires_from_now(boost::posix_time::seconds(pdh_calc_interval));
            timer->async_wait(std::bind(on_timer, timer, std::placeholders::_1));

            return true;
        }

        void PROFILER_PDH::end()
        {
            status = PdhRemoveCounter(*CounterHandle_Time);
            if (status != ERROR_SUCCESS)
            {
                printf("Counter Removing Error\n");
                Error_Display();
            }

            status = PdhCloseQuery(HQuery);
            if (status != ERROR_SUCCESS)
            {
                printf("Close Abnormally\n");
                Error_Display();
            }
            FreeLibrary(HModule);
        }

        void PROFILER_PDH::profiler_CPU(std::stringstream &ss)
        {
            ss << CounterValue_CPU << "%";
        }

        void PROFILER_PDH::Error_Display()
        {
            LPVOID message;
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, HModule, status, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&message, 0, NULL);
            printf("%s", message);
            LocalFree(message);
        }

        bool PROFILER_PDH::calc()
        {
            PDH_FMT_COUNTERVALUE CounterValue;
            DWORD valuetype;

            status = PdhCollectQueryData(HQuery);
            if (status != ERROR_SUCCESS)
            {
                printf("Query Collection Error\n");
                Error_Display();
                return false;
            }

            status = PdhGetFormattedCounterValue(*CounterHandle_Time, PDH_FMT_DOUBLE, &valuetype, &CounterValue);
            if (status != ERROR_SUCCESS)
            {
                printf("CounterValue Calculation Error\n");
                Error_Display();
                return false;
            }

            CounterValue_CPU = CounterValue.doubleValue;
            return true;
        }

        void PROFILER_PDH::on_timer(std::shared_ptr<boost::asio::deadline_timer>& timer, const boost::system::error_code& ec)
        {
            if (!ec)
            {
                calc();

                std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(shared_io_service::instance().ios));
                timer->expires_from_now(boost::posix_time::seconds(pdh_calc_interval));
                timer->async_wait(std::bind(on_timer, timer, std::placeholders::_1));
            }
            else
            {
                // TODO: err handling
            }
        }

        HMODULE PROFILER_PDH::HModule;
        HQUERY PROFILER_PDH::HQuery = NULL;
        HCOUNTER* PROFILER_PDH::CounterHandle_Time = NULL;
        PDH_STATUS PROFILER_PDH::status;
        double PROFILER_PDH::CounterValue_CPU = 0;*/
    }
}<commit_msg>profiler pdh delete<commit_after><|endoftext|>


<commit_before>/*
 Arduino emulation - espressif sdk host implementation
 Copyright (c) 2018 david gauchard. All rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal with the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:

 - Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimers.

 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimers in the
   documentation and/or other materials provided with the distribution.

 - The names of its contributors may not be used to endorse or promote
   products derived from this Software without specific prior written
   permission.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 DEALINGS WITH THE SOFTWARE.
*/

#include <lwip/def.h>

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>

extern "C"
{

#include <user_interface.h>

uint8 wifi_get_opmode(void)
{
	return STATION_MODE;
}

phy_mode_t wifi_get_phy_mode(void)
{
	return PHY_MODE_11N;
}

uint8 wifi_get_channel (void)
{
	return 1;
}

uint8 wifi_station_get_current_ap_id (void)
{
	return 0;
}

station_status_t wifi_station_get_connect_status (void)
{
	return STATION_GOT_IP;
}

uint8 wifi_station_get_auto_connect (void)
{
	return 1;
}

bool wifi_station_get_config (struct station_config *config)
{
	strcpy((char*)config->ssid, "emulated-ssid");
	strcpy((char*)config->password, "emulated-ssid-password");
	config->bssid_set = 0;
	for (int i = 0; i < 6; i++)
		config->bssid[i] = i;
	config->threshold.rssi = 1;
	config->threshold.authmode = AUTH_WPA_PSK;
	config->open_and_wep_mode_disable = true;
	return true;
}

void wifi_fpm_close(void)
{
}

sint8 wifi_fpm_do_sleep (uint32 sleep_time_in_us)
{
	usleep(sleep_time_in_us);
	return 1;
}

void wifi_fpm_do_wakeup (void)
{
}

void wifi_fpm_open (void)
{
}

void wifi_fpm_set_sleep_type (sleep_type_t type)
{
	(void)type;
}

uint32_t global_ipv4_netfmt = 0; // global binding

bool wifi_get_ip_info (uint8 if_index, struct ip_info *info)
{
	struct ifaddrs * ifAddrStruct = NULL, * ifa = NULL;
	uint32_t ipv4 = lwip_htonl(0x7f000001);
	uint32_t mask = lwip_htonl(0xff000000);

	if (getifaddrs(&ifAddrStruct) != 0)
	{
		perror("getifaddrs");
		exit(EXIT_FAILURE);
	}
	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
	{
		if (   ifa->ifa_addr
		    && ifa->ifa_addr->sa_family == AF_INET // ip_info is IPv4 only
		   )
		{
			if (lwip_ntohl(*(uint32_t*)&((struct sockaddr_in*) ifa->ifa_netmask)->sin_addr) != 0xff000000)
			{
				if (ipv4 == lwip_htonl(0x7f000001))
				{
					// take the first by default
					ipv4 = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
					mask = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr;
				}
				if (host_interface && strcmp(ifa->ifa_name, host_interface) == 0)
				{
					// .. or the one specified by user on cmdline
					ipv4 = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
					mask = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr;
					break;
				}
			}
		}
	}
	if (ifAddrStruct != NULL)
		freeifaddrs(ifAddrStruct);

	(void)if_index;
	//if (if_index != STATION_IF)
	//	fprintf(stderr, "we are not AP");

	if (global_ipv4_netfmt == NO_GLOBAL_BINDING)
		global_ipv4_netfmt = ipv4;

	if (info)
	{
		info->ip.addr = ipv4;
		info->netmask.addr = mask;
		info->gw.addr = ipv4;
	}

	return true;
}

uint8 wifi_get_listen_interval (void)
{
	return 1;
}

bool wifi_get_macaddr(uint8 if_index, uint8 *macaddr)
{
	(void)if_index;
	macaddr[0] = 0xde;
	macaddr[1] = 0xba;
	macaddr[2] = 0x7a;
	macaddr[3] = 0xb1;
	macaddr[4] = 0xe0;
	macaddr[5] = 0x42;
	return true;
}

uint8 wifi_get_opmode_default (void)
{
	return STATION_MODE;
}

sleep_level_t wifi_get_sleep_level (void)
{
	return MIN_SLEEP_T;
}

sleep_type_t wifi_get_sleep_type (void)
{
	return NONE_SLEEP_T;
}

bool wifi_set_channel (uint8 channel)
{
	(void)channel;
	return true;
}

wifi_event_handler_cb_t wifi_event_handler_cb_emu = nullptr;
void wifi_set_event_handler_cb (wifi_event_handler_cb_t cb)
{
	wifi_event_handler_cb_emu = cb;
	fprintf(stderr, MOCK "TODO: wifi_set_event_handler_cb set\n");
}

bool wifi_set_ip_info (uint8 if_index, struct ip_info *info)
{
	(void)if_index;
	(void)info;
	return false;
}

bool wifi_set_listen_interval (uint8 interval)
{
	(void)interval;
	return true;
}

bool wifi_set_opmode (uint8 opmode)
{
	return opmode == STATION_MODE || opmode == STATIONAP_MODE;
}

bool wifi_set_opmode_current (uint8 opmode)
{
	return opmode == STATION_MODE || opmode == STATIONAP_MODE;
}

bool wifi_set_phy_mode (phy_mode_t mode)
{
	(void)mode;
	return true;
}

bool wifi_set_sleep_level (sleep_level_t level)
{
	(void)level;
	return true;
}

bool wifi_set_sleep_type (sleep_type_t type)
{
	(void)type;
	return true;
}

bool wifi_station_connect (void)
{
	return true;
}

bool wifi_station_dhcpc_start (void)
{
	return true;
}

bool wifi_station_dhcpc_stop (void)
{
	return true;
}

bool wifi_station_disconnect (void)
{
	return true;
}

bool wifi_station_get_config_default (struct station_config *config)
{
	return wifi_station_get_config(config);
}

char wifi_station_get_hostname_str [128];
const char* wifi_station_get_hostname (void)
{
	return strcpy(wifi_station_get_hostname_str, "esposix");
}

bool wifi_station_get_reconnect_policy ()
{
	return true;
}

sint8 wifi_station_get_rssi (void)
{
	return 5;
}

bool wifi_station_set_auto_connect (uint8 set)
{
	return set != 0;
}

bool wifi_station_set_config (struct station_config *config)
{
	(void)config;
	return true;
}

bool wifi_station_set_config_current (struct station_config *config)
{
	(void)config;
	return true;
}

bool wifi_station_set_hostname (const char *name)
{
	(void)name;
	return true;
}

bool wifi_station_set_reconnect_policy (bool set)
{
	(void)set;
	return true;
}

void system_phy_set_max_tpw (uint8 max_tpw)
{
	(void)max_tpw;
}

bool wifi_softap_dhcps_start(void)
{
	return true;
}

enum dhcp_status wifi_softap_dhcps_status(void)
{
	return DHCP_STARTED;
}

bool wifi_softap_dhcps_stop(void)
{
	return true;
}

bool wifi_softap_get_config(struct softap_config *config)
{
	strcpy((char*)config->ssid, "apssid");
	strcpy((char*)config->password, "appasswd");
	config->ssid_len = strlen("appasswd");
	config->channel = 1;
	config->authmode = AUTH_WPA2_PSK;
	config->ssid_hidden = 0;
	config->max_connection = 4;
	config->beacon_interval = 100;
	return true;
}

bool wifi_softap_get_config_default(struct softap_config *config)
{
	return wifi_softap_get_config(config);
}

uint8 wifi_softap_get_station_num(void)
{
	return 2;
}

bool wifi_softap_set_config(struct softap_config *config)
{
	(void)config;
	return true;
}

bool wifi_softap_set_config_current(struct softap_config *config)
{
	(void)config;
	return true;
}

bool wifi_softap_set_dhcps_lease(struct dhcps_lease *please)
{
	(void)please;
	return true;
}

bool wifi_softap_set_dhcps_lease_time(uint32 minute)
{
	(void)minute;
	return true;
}

bool wifi_softap_set_dhcps_offer_option(uint8 level, void* optarg)
{
	(void)level;
	(void)optarg;
	return true;
}

bool wifi_station_scan(struct scan_config *config, scan_done_cb_t cb)
{
	(void)config;
	cb(nullptr, FAIL);
	return false;
}

uint32_t core_version = 1;

///////////////////////////////////////
// not user_interface

void ets_isr_mask (int intr)
{
	(void)intr;
}

void ets_isr_unmask (int intr)
{
	(void)intr;
}

void esp_schedule (void)
{
}

void optimistic_yield (uint32_t interval_us)
{
	usleep(interval_us);
}

void dns_setserver (u8_t numdns, ip_addr_t *dnsserver)
{
	(void)numdns;
	(void)dnsserver;
}

ip_addr_t dns_getserver (u8_t numdns)
{
	(void)numdns;
	ip_addr_t addr = { 0x7f000001 };
	return addr;
}

#include <smartconfig.h>
bool smartconfig_start (sc_callback_t cb, ...)
{
	//XXXFIXME ... -> ptr
	cb(SC_STATUS_LINK, NULL);
	return true;
}

bool smartconfig_stop (void)
{
	return true;
}

} // extern "C"
<commit_msg>Fix host emulation (sdk changes) (#5802)<commit_after>/*
 Arduino emulation - espressif sdk host implementation
 Copyright (c) 2018 david gauchard. All rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal with the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:

 - Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimers.

 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimers in the
   documentation and/or other materials provided with the distribution.

 - The names of its contributors may not be used to endorse or promote
   products derived from this Software without specific prior written
   permission.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 DEALINGS WITH THE SOFTWARE.
*/

#include <lwip/def.h>

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>

extern "C"
{

#include <user_interface.h>

uint8 wifi_get_opmode(void)
{
	return STATION_MODE;
}

phy_mode_t wifi_get_phy_mode(void)
{
	return PHY_MODE_11N;
}

uint8 wifi_get_channel (void)
{
	return 1;
}

uint8 wifi_station_get_current_ap_id (void)
{
	return 0;
}

station_status_t wifi_station_get_connect_status (void)
{
	return STATION_GOT_IP;
}

uint8 wifi_station_get_auto_connect (void)
{
	return 1;
}

bool wifi_station_get_config (struct station_config *config)
{
	strcpy((char*)config->ssid, "emulated-ssid");
	strcpy((char*)config->password, "emulated-ssid-password");
	config->bssid_set = 0;
	for (int i = 0; i < 6; i++)
		config->bssid[i] = i;
	config->threshold.rssi = 1;
	config->threshold.authmode = AUTH_WPA_PSK;
#ifndef NONOSDK221
	config->open_and_wep_mode_disable = true;
#endif
	return true;
}

void wifi_fpm_close(void)
{
}

sint8 wifi_fpm_do_sleep (uint32 sleep_time_in_us)
{
	usleep(sleep_time_in_us);
	return 1;
}

void wifi_fpm_do_wakeup (void)
{
}

void wifi_fpm_open (void)
{
}

void wifi_fpm_set_sleep_type (sleep_type_t type)
{
	(void)type;
}

uint32_t global_ipv4_netfmt = 0; // global binding

bool wifi_get_ip_info (uint8 if_index, struct ip_info *info)
{
	struct ifaddrs * ifAddrStruct = NULL, * ifa = NULL;
	uint32_t ipv4 = lwip_htonl(0x7f000001);
	uint32_t mask = lwip_htonl(0xff000000);

	if (getifaddrs(&ifAddrStruct) != 0)
	{
		perror("getifaddrs");
		exit(EXIT_FAILURE);
	}
	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
	{
		if (   ifa->ifa_addr
		    && ifa->ifa_addr->sa_family == AF_INET // ip_info is IPv4 only
		   )
		{
			if (lwip_ntohl(*(uint32_t*)&((struct sockaddr_in*) ifa->ifa_netmask)->sin_addr) != 0xff000000)
			{
				if (ipv4 == lwip_htonl(0x7f000001))
				{
					// take the first by default
					ipv4 = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
					mask = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr;
				}
				if (host_interface && strcmp(ifa->ifa_name, host_interface) == 0)
				{
					// .. or the one specified by user on cmdline
					ipv4 = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
					mask = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr;
					break;
				}
			}
		}
	}
	if (ifAddrStruct != NULL)
		freeifaddrs(ifAddrStruct);

	(void)if_index;
	//if (if_index != STATION_IF)
	//	fprintf(stderr, "we are not AP");

	if (global_ipv4_netfmt == NO_GLOBAL_BINDING)
		global_ipv4_netfmt = ipv4;

	if (info)
	{
		info->ip.addr = ipv4;
		info->netmask.addr = mask;
		info->gw.addr = ipv4;
	}

	return true;
}

uint8 wifi_get_listen_interval (void)
{
	return 1;
}

bool wifi_get_macaddr(uint8 if_index, uint8 *macaddr)
{
	(void)if_index;
	macaddr[0] = 0xde;
	macaddr[1] = 0xba;
	macaddr[2] = 0x7a;
	macaddr[3] = 0xb1;
	macaddr[4] = 0xe0;
	macaddr[5] = 0x42;
	return true;
}

uint8 wifi_get_opmode_default (void)
{
	return STATION_MODE;
}

#ifndef NONOSDK221

sleep_level_t wifi_get_sleep_level (void)
{
	return MIN_SLEEP_T;
}

#endif // nonos-sdk-pre-3

sleep_type_t wifi_get_sleep_type (void)
{
	return NONE_SLEEP_T;
}

bool wifi_set_channel (uint8 channel)
{
	(void)channel;
	return true;
}

wifi_event_handler_cb_t wifi_event_handler_cb_emu = nullptr;
void wifi_set_event_handler_cb (wifi_event_handler_cb_t cb)
{
	wifi_event_handler_cb_emu = cb;
	fprintf(stderr, MOCK "TODO: wifi_set_event_handler_cb set\n");
}

bool wifi_set_ip_info (uint8 if_index, struct ip_info *info)
{
	(void)if_index;
	(void)info;
	return false;
}

bool wifi_set_listen_interval (uint8 interval)
{
	(void)interval;
	return true;
}

bool wifi_set_opmode (uint8 opmode)
{
	return opmode == STATION_MODE || opmode == STATIONAP_MODE;
}

bool wifi_set_opmode_current (uint8 opmode)
{
	return opmode == STATION_MODE || opmode == STATIONAP_MODE;
}

bool wifi_set_phy_mode (phy_mode_t mode)
{
	(void)mode;
	return true;
}

#ifndef NONOSDK221

bool wifi_set_sleep_level (sleep_level_t level)
{
	(void)level;
	return true;
}

#endif

bool wifi_set_sleep_type (sleep_type_t type)
{
	(void)type;
	return true;
}

bool wifi_station_connect (void)
{
	return true;
}

bool wifi_station_dhcpc_start (void)
{
	return true;
}

bool wifi_station_dhcpc_stop (void)
{
	return true;
}

bool wifi_station_disconnect (void)
{
	return true;
}

bool wifi_station_get_config_default (struct station_config *config)
{
	return wifi_station_get_config(config);
}

char wifi_station_get_hostname_str [128];
const char* wifi_station_get_hostname (void)
{
	return strcpy(wifi_station_get_hostname_str, "esposix");
}

bool wifi_station_get_reconnect_policy ()
{
	return true;
}

sint8 wifi_station_get_rssi (void)
{
	return 5;
}

bool wifi_station_set_auto_connect (uint8 set)
{
	return set != 0;
}

bool wifi_station_set_config (struct station_config *config)
{
	(void)config;
	return true;
}

bool wifi_station_set_config_current (struct station_config *config)
{
	(void)config;
	return true;
}

bool wifi_station_set_hostname (const char *name)
{
	(void)name;
	return true;
}

bool wifi_station_set_reconnect_policy (bool set)
{
	(void)set;
	return true;
}

void system_phy_set_max_tpw (uint8 max_tpw)
{
	(void)max_tpw;
}

bool wifi_softap_dhcps_start(void)
{
	return true;
}

enum dhcp_status wifi_softap_dhcps_status(void)
{
	return DHCP_STARTED;
}

bool wifi_softap_dhcps_stop(void)
{
	return true;
}

bool wifi_softap_get_config(struct softap_config *config)
{
	strcpy((char*)config->ssid, "apssid");
	strcpy((char*)config->password, "appasswd");
	config->ssid_len = strlen("appasswd");
	config->channel = 1;
	config->authmode = AUTH_WPA2_PSK;
	config->ssid_hidden = 0;
	config->max_connection = 4;
	config->beacon_interval = 100;
	return true;
}

bool wifi_softap_get_config_default(struct softap_config *config)
{
	return wifi_softap_get_config(config);
}

uint8 wifi_softap_get_station_num(void)
{
	return 2;
}

bool wifi_softap_set_config(struct softap_config *config)
{
	(void)config;
	return true;
}

bool wifi_softap_set_config_current(struct softap_config *config)
{
	(void)config;
	return true;
}

bool wifi_softap_set_dhcps_lease(struct dhcps_lease *please)
{
	(void)please;
	return true;
}

bool wifi_softap_set_dhcps_lease_time(uint32 minute)
{
	(void)minute;
	return true;
}

bool wifi_softap_set_dhcps_offer_option(uint8 level, void* optarg)
{
	(void)level;
	(void)optarg;
	return true;
}

bool wifi_station_scan(struct scan_config *config, scan_done_cb_t cb)
{
	(void)config;
	cb(nullptr, FAIL);
	return false;
}

uint32_t core_version = 1;

///////////////////////////////////////
// not user_interface

void ets_isr_mask (int intr)
{
	(void)intr;
}

void ets_isr_unmask (int intr)
{
	(void)intr;
}

void esp_schedule (void)
{
}

void optimistic_yield (uint32_t interval_us)
{
	usleep(interval_us);
}

void dns_setserver (u8_t numdns, ip_addr_t *dnsserver)
{
	(void)numdns;
	(void)dnsserver;
}

ip_addr_t dns_getserver (u8_t numdns)
{
	(void)numdns;
	ip_addr_t addr = { 0x7f000001 };
	return addr;
}

#include <smartconfig.h>
bool smartconfig_start (sc_callback_t cb, ...)
{
	//XXXFIXME ... -> ptr
	cb(SC_STATUS_LINK, NULL);
	return true;
}

bool smartconfig_stop (void)
{
	return true;
}

} // extern "C"
<|endoftext|>


<commit_before>#pragma once
#ifndef SIMRANK_HPP
#define SIMRANK_HPP

#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iterator>

template<typename K, typename V>
using umap = std::unordered_map<K, V>;

template<typename T>
using uset = std::unordered_set<T>;

template<typename node_t, typename float_t>
class SimRank {
public:
	SimRank(size_t K = 6, float_t C = 0.6, float_t D = 0.05);
	~SimRank();

	// Reserve space in memory for at least n nodes
	void reserve(size_t n);
	// Add an edge to the graph
	void add_edge(node_t head, node_t tail);
	// Calculate SimRank scores after adding all the edges
	void calculate_simrank(void);
	// Return the similarity score between nodes a and b
	float_t similarity(node_t a, node_t b) const;

	// Return the number of iterations
	inline size_t K(void) const { return K_; }
	// Return the decay factor
	inline float_t C(void) const { return C_; }
	// Return the delta for threshold sieving
	inline float_t D(void) const { return D_; }

	// Return the number of nodes in the graph
	inline size_t num_nodes(void) const { return node_properties_.size(); }
	// Return the number of nodes with out-degree > 0
	inline size_t num_heads(void) const { return edge_weights_.size(); }
	// Return the number of nodes with in-degree > 0
	inline size_t num_tails(void) const { return in_neighbors_.size(); }

	// Edge data accessible via edges()
	struct edge_t {
		node_t head, tail;
		float_t weight;
		inline edge_t(node_t head, node_t tail, float_t weight) : head(head), tail(tail), weight(weight) {}
	};

	class node_iterable;
	class edge_iterable;
	// Iterate over all nodes, e.g. "for (node_t x : simrank.nodes()) { ... }"
	inline const node_iterable nodes(void) const { return node_iterable(*this); }
	// Iterate over all edges, e.g. "for (SimRank::edge_t e : simrank.edges()) { ... }"
	inline const edge_iterable edges(void) const { return edge_iterable(*this); }

	// Return the out-degree of node x
	inline int out_degree(node_t x) { return node_properties_[x].out_degree; }
	// Return the in-degree of node x
	inline int in_degree(node_t x) { return node_properties_[x].in_degree; }
	// Return the set of in-neighbors of node x
	inline const uset<node_t> &in_neighbors(node_t x) { return in_neighbors_[x]; }
	// Return the weight of the edge fro head to tail (normalized after calling calculate_simrank())
	inline float_t edge_weight(node_t head, node_t tail) { return edge_weights_[head][tail]; }

private:
	struct node_prop_t {
		umap<node_t, float_t> simrank;
		float_t partial_sum;
		int in_degree, out_degree;
		inline node_prop_t(void) : simrank(), partial_sum(), in_degree(), out_degree() {}
	};

	size_t K_;
	float_t C_;
	float_t D_;

	umap<node_t, node_prop_t>           node_properties_; // {node1 -> <{node2 -> SimRank}, etc>} (node1 <= node2)
	umap<node_t, uset<node_t>>          in_neighbors_;    // {node -> {in-neighbors}}
	umap<node_t, umap<node_t, float_t>> edge_weights_;    // {head -> {tail -> weight}}

	std::vector<node_t> temp_nodes_;      // temporary node storage for calculating essential paired nodes
	std::vector<node_t> essential_nodes_; // essential paired nodes (reused in each update iteration)

	float_t *delta_; // deltas for threshold sieving

	void normalize_edges(void);
	void update_simrank_scores(node_t a, int k);

public:
	class node_iterator {
	private:
		typename umap<node_t, node_prop_t>::const_iterator pos_;
	public:
		inline node_iterator(typename umap<node_t, node_prop_t>::const_iterator pos) : pos_(pos) {}
		inline node_t operator*() { return pos_->first; }
		inline bool operator!=(const node_iterator &other) const { return pos_ != other.pos_; }
		inline const node_iterator &operator++() { ++pos_; return *this; }
	};

	class node_iterable {
	private:
		const SimRank &simrank_;
	public:
		inline node_iterable(const SimRank &s) : simrank_(s) {}
		inline const node_iterator begin(void) const { return node_iterator(simrank_.node_properties_.begin()); }
		inline const node_iterator end(void) const { return node_iterator(simrank_.node_properties_.end()); }
		inline node_iterable &operator=(const node_iterable &) { return *this; }
	};

	class edge_iterator {
		typedef typename umap<node_t, umap<node_t, float_t>>::const_iterator pos_iterator;
		typedef typename umap<node_t, float_t>::const_iterator subpos_iterator;
	private:
		pos_iterator pos_, pos_end_;
		subpos_iterator subpos_, subpos_end_;
	public:
		inline edge_iterator(pos_iterator pos, subpos_iterator subpos, pos_iterator pos_end, subpos_iterator subpos_end) :
			pos_(pos), pos_end_(pos_end), subpos_(subpos), subpos_end_(subpos_end) {}
		inline edge_t operator*() { return edge_t(pos_->first, subpos_->first, subpos_->second); }
		inline bool operator!=(const edge_iterator &other) const { return pos_ != other.pos_ || subpos_ != other.subpos_; }
		inline const edge_iterator &operator++(void) {
			++subpos_;
			if (subpos_ == pos_->second.end()) {
				++pos_;
				subpos_ = pos_ == pos_end_ ? subpos_end_ : pos_->second.begin();
			}
			return *this;
		}
	};

	class edge_iterable {
	private:
		const SimRank &simrank_;
	public:
		inline edge_iterable(const SimRank &s) : simrank_(s) {}
		inline const edge_iterator begin(void) const { return edge_iterator(simrank_.edge_weights_.begin(),
			simrank_.edge_weights_.begin()->second.begin(),
			simrank_.edge_weights_.end(),
			simrank_.edge_weights_.begin()->second.end()); }
		inline const edge_iterator end(void) const { return edge_iterator(simrank_.edge_weights_.end(),
			simrank_.edge_weights_.begin()->second.end(),
			simrank_.edge_weights_.end(),
			simrank_.edge_weights_.begin()->second.end()); }
		inline edge_iterable &operator=(const edge_iterable &) { return *this; }
	};
};

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::SimRank(size_t K, float_t C, float_t D) : K_(K), C_(C), D_(D),
	node_properties_(), in_neighbors_(), edge_weights_(), temp_nodes_(), essential_nodes_() {
	delta_ = new float_t[K];
}

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::~SimRank() {
	delete [] delta_;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::reserve(size_t n) {
	node_properties_.reserve(n);
	edge_weights_.reserve(n);
	in_neighbors_.reserve(n);
	temp_nodes_.reserve(n);
	essential_nodes_.reserve(n);
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::add_edge(node_t head, node_t tail) {
	node_properties_[head].out_degree++;
	node_properties_[tail].in_degree++;
	in_neighbors_[tail].insert(head);
	edge_weights_[head][tail]++;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::calculate_simrank() {
	normalize_edges();
	// Calculate deltas for threshold sieving
	for (int m = 0; m < K_; m++) {
		delta_[m] = (float_t)(D_ / (K_ * pow(C_, K_ - m + 1)));
	}
	// Initialize similarity scores
	for (auto const &a_aps_p : node_properties_) {
		node_t a = a_aps_p.first;
		node_properties_[a].simrank.clear();
	}
	// Main loop: update scores for K iterations
	for (int k = 0; k < K_; k++) {
		for (auto const &a_aps_p : node_properties_) {
			node_t a = a_aps_p.first;
			int a_od = a_aps_p.second.out_degree;
			if (a_od == 0 && k < K_ - 1) { continue; }
			update_simrank_scores(a, k);
		}
	}
}

template<typename node_t, typename float_t>
float_t SimRank<node_t, float_t>::similarity(node_t a, node_t b) const {
	// similarity(a, a) == 1
	if (a == b) { return 1; }
	// similarity(a, b) == similarity(b, a), so standardize on a < b
	if (a > b) { std::swap(a, b); }
	auto a_props = node_properties_.at(a);
	auto a_b_simrank = a_props.simrank.find(b);
	if (a_b_simrank == a_props.simrank.end()) { return 0; }
	return a_b_simrank->second;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::normalize_edges() {
	// Divide each edge from a to b by the in-degree of b
	for (auto &a_bws_p : edge_weights_) {
		node_t a = a_bws_p.first;
		auto &bws = a_bws_p.second;
		for (auto &b_w_p : bws) {
			node_t b = b_w_p.first;
			float_t w = b_w_p.second;
			edge_weights_[a][b] = w / node_properties_[b].in_degree;
		}
	}
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::update_simrank_scores(node_t a, int k) {
	// Calculate partial sums for node a's in-neighbors
	for (auto &u_ups_p : node_properties_) {
		node_t u = u_ups_p.first;
		float_t partial_sum_u = 0;
		for (node_t i : in_neighbors_[a]) {
			partial_sum_u += similarity(i, u) * edge_weights_[i][a];
		}
		node_properties_[u].partial_sum = partial_sum_u;
	}
	// Calculate essential paired nodes for node a
	essential_nodes_.clear();
	// Construct set of temporary nodes
	temp_nodes_.clear();
	for (auto const &v_vps_p : node_properties_) {
		node_t v = v_vps_p.first;
		for (node_t u : in_neighbors_[a]) {
			if (similarity(u, v) > 0) {
				temp_nodes_.push_back(v);
				break;
			}
		}
	}
	// Construct set of essential paired nodes
	for (auto const &b_bps_p : node_properties_) {
		node_t b = b_bps_p.first;
		for (node_t v : temp_nodes_) {
			if (in_neighbors_[b].find(v) != in_neighbors_[b].end()) {
				essential_nodes_.push_back(b);
				break;
			}
		}
	}
	// Main loop: account for node b's in-neighbors
	for (node_t b : essential_nodes_) {
		float_t score_a_b = 0;
		for (node_t j : in_neighbors_[b]) {
			score_a_b += node_properties_[j].partial_sum * edge_weights_[j][b];
		}
		score_a_b *= C_;
		if (score_a_b > delta_[k] || similarity(a, b) > 0) {
			node_properties_[a].simrank[b] = score_a_b;
		}
	}
}

#endif
<commit_msg>Allow iteration over in- and out-neighbors<commit_after>#pragma once
#ifndef SIMRANK_HPP
#define SIMRANK_HPP

#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iterator>

template<typename K, typename V>
using umap = std::unordered_map<K, V>;

template<typename T>
using uset = std::unordered_set<T>;

template<typename node_t, typename float_t>
class SimRank {
public:
	SimRank(size_t K = 6, float_t C = 0.6, float_t D = 0.05);
	~SimRank();

	// Reserve space in memory for at least n nodes
	void reserve(size_t n);
	// Add an edge to the graph
	void add_edge(node_t head, node_t tail);
	// Calculate SimRank scores after adding all the edges
	void calculate_simrank(void);
	// Return the similarity score between nodes a and b
	float_t similarity(node_t a, node_t b) const;

	// Return the number of iterations
	inline size_t K(void) const { return K_; }
	// Return the decay factor
	inline float_t C(void) const { return C_; }
	// Return the delta for threshold sieving
	inline float_t D(void) const { return D_; }

	// Return the number of nodes in the graph
	inline size_t num_nodes(void) const { return node_properties_.size(); }
	// Return the number of nodes with out-degree > 0
	inline size_t num_heads(void) const { return edge_weights_.size(); }
	// Return the number of nodes with in-degree > 0
	inline size_t num_tails(void) const { return in_neighbors_.size(); }

	// Edge data accessible via edges()
	struct edge_t {
		node_t head, tail;
		float_t weight;
		inline edge_t(node_t head, node_t tail, float_t weight) : head(head), tail(tail), weight(weight) {}
	};

	class node_iterable;
	class edge_iterable;
	// Iterate over all nodes, e.g. "for (node_t x : simrank.nodes()) { ... }"
	inline const node_iterable nodes(void) const { return node_iterable(*this); }
	// Iterate over all edges, e.g. "for (SimRank::edge_t e : simrank.edges()) { ... }"
	inline const edge_iterable edges(void) const { return edge_iterable(*this); }

	// Return the out-degree of node x (the sum of the outgoing edges' weights)
	inline int out_degree(node_t x) { return node_properties_[x].out_degree; }
	// Return the in-degree of node x (the sum of the incoming edges' weights)
	inline int in_degree(node_t x) { return node_properties_[x].in_degree; }

	class out_iterable;
	class in_iterable;
	// Iterate over the out-neighbors of node x, e.g. "for (node_t y : simrank.out_neighbors(x)) { ... }"
	inline const out_iterable out_neighbors(node_t x) { return out_iterable(edge_weights_[x]); }
	// Iterate over the in-neighbors of node x, e.g. "for (node_t y : simrank.in_neighbors(x)) { ... }"
	inline const in_iterable in_neighbors(node_t x) { return in_iterable(in_neighbors_[x]); }

	// Return the weight of the edge from a to b (normalized after calling calculate_simrank())
	inline float_t edge_weight(node_t a, node_t b) { return edge_weights_[a][b]; }

private:
	struct node_prop_t {
		umap<node_t, float_t> simrank;
		float_t partial_sum;
		int in_degree, out_degree;
		inline node_prop_t(void) : simrank(), partial_sum(), in_degree(), out_degree() {}
	};

	size_t K_;
	float_t C_;
	float_t D_;

	umap<node_t, node_prop_t>           node_properties_; // {node1 -> <{node2 -> SimRank}, etc>} (node1 <= node2)
	umap<node_t, uset<node_t>>          in_neighbors_;    // {node -> {in-neighbors}}
	umap<node_t, umap<node_t, float_t>> edge_weights_;    // {head -> {tail -> weight}}

	std::vector<node_t> temp_nodes_;      // temporary node storage for calculating essential paired nodes
	std::vector<node_t> essential_nodes_; // essential paired nodes (reused in each update iteration)

	float_t *delta_; // deltas for threshold sieving

	void normalize_edges(void);
	void update_simrank_scores(node_t a, int k);

public:
	class node_iterator {
	private:
		typename umap<node_t, node_prop_t>::const_iterator pos_;
	public:
		inline node_iterator(typename umap<node_t, node_prop_t>::const_iterator pos) : pos_(pos) {}
		inline node_t operator*() { return pos_->first; }
		inline bool operator!=(const node_iterator &other) const { return pos_ != other.pos_; }
		inline const node_iterator &operator++() { ++pos_; return *this; }
	};

	class node_iterable {
	private:
		const SimRank &simrank_;
	public:
		inline node_iterable(const SimRank &s) : simrank_(s) {}
		inline const node_iterator begin(void) const { return node_iterator(simrank_.node_properties_.begin()); }
		inline const node_iterator end(void) const { return node_iterator(simrank_.node_properties_.end()); }
		inline node_iterable &operator=(const node_iterable &) { return *this; }
	};

	class edge_iterator {
		typedef typename umap<node_t, umap<node_t, float_t>>::const_iterator pos_iterator;
		typedef typename umap<node_t, float_t>::const_iterator subpos_iterator;
	private:
		pos_iterator pos_, pos_end_;
		subpos_iterator subpos_, subpos_end_;
	public:
		inline edge_iterator(pos_iterator pos, subpos_iterator subpos, pos_iterator pos_end, subpos_iterator subpos_end) :
			pos_(pos), pos_end_(pos_end), subpos_(subpos), subpos_end_(subpos_end) {}
		inline edge_t operator*() { return edge_t(pos_->first, subpos_->first, subpos_->second); }
		inline bool operator!=(const edge_iterator &other) const { return pos_ != other.pos_ || subpos_ != other.subpos_; }
		inline const edge_iterator &operator++(void) {
			++subpos_;
			if (subpos_ == pos_->second.end()) {
				++pos_;
				subpos_ = pos_ == pos_end_ ? subpos_end_ : pos_->second.begin();
			}
			return *this;
		}
	};

	class edge_iterable {
	private:
		const SimRank &simrank_;
	public:
		inline edge_iterable(const SimRank &s) : simrank_(s) {}
		inline const edge_iterator begin(void) const { return edge_iterator(simrank_.edge_weights_.begin(),
			simrank_.edge_weights_.begin()->second.begin(),
			simrank_.edge_weights_.end(),
			simrank_.edge_weights_.begin()->second.end()); }
		inline const edge_iterator end(void) const { return edge_iterator(simrank_.edge_weights_.end(),
			simrank_.edge_weights_.begin()->second.end(),
			simrank_.edge_weights_.end(),
			simrank_.edge_weights_.begin()->second.end()); }
		inline edge_iterable &operator=(const edge_iterable &) { return *this; }
	};

	class out_iterator {
	private:
		typename umap<node_t, float_t>::const_iterator pos_;
	public:
		inline out_iterator(typename umap<node_t, float_t>::const_iterator pos) : pos_(pos) {}
		inline node_t operator*() { return pos_->first; }
		inline bool operator!=(const out_iterator &other) const { return pos_ != other.pos_; }
		inline const out_iterator &operator++() { ++pos_; return *this; }
	};

	class out_iterable {
	private:
		const umap<node_t, float_t> &collection_;
	public:
		inline out_iterable(const umap<node_t, float_t> &c) : collection_(c) {}
		inline const out_iterator begin(void) const { return out_iterator(collection_.begin()); }
		inline const out_iterator end(void) const { return out_iterator(collection_.end()); }
		inline out_iterable &operator=(const out_iterable &) { return *this; }
	};

	class in_iterator {
	private:
		typename uset<node_t>::const_iterator pos_;
	public:
		inline in_iterator(typename uset<node_t>::const_iterator pos) : pos_(pos) {}
		inline node_t operator*() { return *pos_; }
		inline bool operator!=(const in_iterator &other) const { return pos_ != other.pos_; }
		inline const in_iterator &operator++() { ++pos_; return *this; }
	};

	class in_iterable {
	private:
		const uset<node_t> &collection_;
	public:
		inline in_iterable(const uset<node_t> &c) : collection_(c) {}
		inline const in_iterator begin(void) const { return in_iterator(collection_.begin()); }
		inline const in_iterator end(void) const { return in_iterator(collection_.end()); }
		inline in_iterable &operator=(const in_iterable &) { return *this; }
	};
};

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::SimRank(size_t K, float_t C, float_t D) : K_(K), C_(C), D_(D),
	node_properties_(), in_neighbors_(), edge_weights_(), temp_nodes_(), essential_nodes_() {
	delta_ = new float_t[K];
}

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::~SimRank() {
	delete [] delta_;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::reserve(size_t n) {
	node_properties_.reserve(n);
	edge_weights_.reserve(n);
	in_neighbors_.reserve(n);
	temp_nodes_.reserve(n);
	essential_nodes_.reserve(n);
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::add_edge(node_t head, node_t tail) {
	node_properties_[head].out_degree++;
	node_properties_[tail].in_degree++;
	in_neighbors_[tail].insert(head);
	edge_weights_[head][tail]++;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::calculate_simrank() {
	normalize_edges();
	// Calculate deltas for threshold sieving
	for (int m = 0; m < K_; m++) {
		delta_[m] = (float_t)(D_ / (K_ * pow(C_, K_ - m + 1)));
	}
	// Initialize similarity scores
	for (auto const &a_aps_p : node_properties_) {
		node_t a = a_aps_p.first;
		node_properties_[a].simrank.clear();
	}
	// Main loop: update scores for K iterations
	for (int k = 0; k < K_; k++) {
		for (auto const &a_aps_p : node_properties_) {
			node_t a = a_aps_p.first;
			int a_od = a_aps_p.second.out_degree;
			if (a_od == 0 && k < K_ - 1) { continue; }
			update_simrank_scores(a, k);
		}
	}
}

template<typename node_t, typename float_t>
float_t SimRank<node_t, float_t>::similarity(node_t a, node_t b) const {
	// similarity(a, a) == 1
	if (a == b) { return 1; }
	// similarity(a, b) == similarity(b, a), so standardize on a < b
	if (a > b) { std::swap(a, b); }
	auto a_props = node_properties_.at(a);
	auto a_b_simrank = a_props.simrank.find(b);
	if (a_b_simrank == a_props.simrank.end()) { return 0; }
	return a_b_simrank->second;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::normalize_edges() {
	// Divide each edge from a to b by the in-degree of b
	for (auto &a_bws_p : edge_weights_) {
		node_t a = a_bws_p.first;
		auto &bws = a_bws_p.second;
		for (auto &b_w_p : bws) {
			node_t b = b_w_p.first;
			float_t w = b_w_p.second;
			edge_weights_[a][b] = w / node_properties_[b].in_degree;
		}
	}
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::update_simrank_scores(node_t a, int k) {
	// Calculate partial sums for node a's in-neighbors
	for (auto &u_ups_p : node_properties_) {
		node_t u = u_ups_p.first;
		float_t partial_sum_u = 0;
		for (node_t i : in_neighbors_[a]) {
			partial_sum_u += similarity(i, u) * edge_weights_[i][a];
		}
		node_properties_[u].partial_sum = partial_sum_u;
	}
	// Calculate essential paired nodes for node a
	essential_nodes_.clear();
	// Construct set of temporary nodes
	temp_nodes_.clear();
	for (auto const &v_vps_p : node_properties_) {
		node_t v = v_vps_p.first;
		for (node_t u : in_neighbors_[a]) {
			if (similarity(u, v) > 0) {
				temp_nodes_.push_back(v);
				break;
			}
		}
	}
	// Construct set of essential paired nodes
	for (auto const &b_bps_p : node_properties_) {
		node_t b = b_bps_p.first;
		for (node_t v : temp_nodes_) {
			if (in_neighbors_[b].find(v) != in_neighbors_[b].end()) {
				essential_nodes_.push_back(b);
				break;
			}
		}
	}
	// Main loop: account for node b's in-neighbors
	for (node_t b : essential_nodes_) {
		float_t score_a_b = 0;
		for (node_t j : in_neighbors_[b]) {
			score_a_b += node_properties_[j].partial_sum * edge_weights_[j][b];
		}
		score_a_b *= C_;
		if (score_a_b > delta_[k] || similarity(a, b) > 0) {
			node_properties_[a].simrank[b] = score_a_b;
		}
	}
}

#endif
<|endoftext|>


<commit_before>#include "TMath.h"
#include <TGeoGlobalMagField.h>

#include "AliMFTCATrack.h"
#include "AliMFTCACell.h"
#include "AliMFTTrackExtrap.h"

#include "AliLog.h"

ClassImp(AliMFTCATrack)

//___________________________________________________________________________

AliMFTCATrack::AliMFTCATrack() :
TObject(),
fGID(-1),
fNcells(0),
fStartLayer(-1),
fCellGIDarray(),
fMCflag(0),
fVertX(0.),
fVertY(0.),
fVertZ(0.),
fTheta(0.),
fPhi(0.),
fChiSqX(0.),
fChiSqY(0.),
fMCindex(-1),
fChargeSign(0.),
fPt(0.)
{

  fCells = new TClonesArray("AliMFTCACell", fNDetMax);

}

//___________________________________________________________________________

AliMFTCATrack::AliMFTCATrack(const AliMFTCATrack &track) :
TObject(track),
fGID(track.fGID),
fNcells(track.fNcells),
fStartLayer(track.fStartLayer),
fMCflag(track.fMCflag),
fVertX(track.fVertX),
fVertY(track.fVertY),
fVertZ(track.fVertZ),
fTheta(track.fTheta),
fPhi(track.fPhi),
fChiSqX(track.fChiSqX),
fChiSqY(track.fChiSqY),
fMCindex(track.fMCindex),
fChargeSign(track.fChargeSign),
fPt(track.fPt)
{

  // copy constructor

  fCells = new TClonesArray("AliMFTCACell", fNDetMax);

  for (Int_t icell = 0; icell < track.fNcells; icell++)
  fCellGIDarray[icell] = track.fCellGIDarray[icell];

}

//___________________________________________________________________________

AliMFTCATrack& AliMFTCATrack::operator=(const AliMFTCATrack& track)
{

  // assignment operator

  // check assignement to self
  if (this == &track) return *this;

  TObject::operator=(track);

  fGID = track.fGID;
  fNcells = track.fNcells;
  fStartLayer = track.fStartLayer;
  fCells = new TClonesArray("AliMFTCACell", fNDetMax);
  for (Int_t icell = 0; icell < track.fNcells; icell++)
  fCellGIDarray[icell] = track.fCellGIDarray[icell];
  fMCflag = track.fMCflag;
  fVertX = track.fVertX;
  fVertY = track.fVertY;
  fVertZ = track.fVertZ;
  fTheta = track.fTheta;
  fPhi = track.fPhi;
  fChiSqX = track.fChiSqX;
  fChiSqY = track.fChiSqY;
  fMCindex = track.fMCindex;
  fChargeSign = track.fChargeSign;
  fPt = track.fPt;

}

//___________________________________________________________________________

void AliMFTCATrack::Clear(Option_t *) {

}
//___________________________________________________________________________

/// Estimate the charge sign
void  AliMFTCATrack::EvalSignedPt(){
	const Int_t nMaxh = 100;
	Double_t xTr[nMaxh], yTr[nMaxh], zTr[nMaxh];
	Double_t r[nMaxh], u[nMaxh] , v[nMaxh];

	AliMFTCACell *celltr;
	Int_t nptr = 0;

	for (Int_t iCell = 0; iCell < GetNcells(); iCell++) {
		celltr = (AliMFTCACell*)fCells->At(iCell);
		// extract hit x,y,z
		if (nptr == 0) {
			xTr[nptr] = celltr->GetHit2()[0];
			yTr[nptr] = celltr->GetHit2()[1];
			zTr[nptr] = celltr->GetHit2()[2];
			nptr++;
			xTr[nptr] = celltr->GetHit1()[0];
			yTr[nptr] = celltr->GetHit1()[1];
			zTr[nptr] = celltr->GetHit1()[2];
			nptr++;
		} else {
			xTr[nptr] = celltr->GetHit1()[0];
			yTr[nptr] = celltr->GetHit1()[1];
			zTr[nptr] = celltr->GetHit1()[2];
			nptr++;
		}
	} // END : cells loop
	for (Int_t i = 0; i< nptr; i++) {
		AliInfo(Form("x,y,z = %f %f %f",xTr[i],yTr[i],zTr[i]));
	}
//	Double_t distL = 0., q2=0.;
//	Double_t sagitta = AliMFTTrackExtrap::Sagitta(nptr, xTr, yTr, distL,q2);
//	AliInfo(Form("sagitta = %f",sagitta));;
//	AliInfo(Form("distL = %f",distL));;
//
//	AliInfo(Form("q2 = %f => pt = %f ",q2, 0.01/q2/2.*0.3*b[2]/10.));
//
//	//fPt = 0.3*TMath::Abs(b[2]/10.)*distL*distL/8./sagitta;
//	fPt = 0.3*TMath::Abs(b[2]/10.)*AliMFTTrackExtrap::CircleRegression(nptr, xTr, yTr)*TMath::Sign(1.,sagitta);
// //fPt =0.01/q2/2.*0.3*b[2]/10.;

	for (Int_t iptr = 0; iptr < nptr; iptr++) {

		r[iptr] = TMath::Sqrt(yTr[iptr]*yTr[iptr]+xTr[iptr]*xTr[iptr]);
		u[iptr] = xTr[iptr]/r[iptr]/r[iptr];
		v[iptr] = yTr[iptr]/r[iptr]/r[iptr];

		AliInfo(Form("u,v,r = %f %f %f ",u[iptr],v[iptr],r[iptr]));

	}
	Double_t fdump, slopeX_Z, slopeY_Z;
	AliMFTTrackExtrap::LinearRegression(nptr, xTr,zTr, fdump, slopeX_Z);
	AliMFTTrackExtrap::LinearRegression(nptr, yTr,zTr, fdump, slopeY_Z);

	Double_t phi = TMath::ATan2(slopeY_Z,slopeX_Z);
	Double_t xS,x0;
	Double_t chi2 = AliMFTTrackExtrap::LinearRegression(nptr, u,v, x0, xS);
	Double_t rx = -xS/(2.*x0);
	Double_t ry =  1./(2.*x0);
	Double_t rr = TMath::Sqrt(rx*rx+ry*ry);
	AliInfo(Form("chi2 = %f",chi2));;
	AliInfo(Form("Rx,Ry = %f %f",rx,ry));;
	AliInfo(Form("R = %f",rr));;
	AliInfo(Form("Phi = %f",phi));;

		Double_t zmean = 0.5 * (AliMFTConstants::DefaultPlaneZ(0) + AliMFTConstants::DefaultPlaneZ(9));
		const Double_t x[3] = {0.,0.,zmean};
		Double_t b[3] = {0.,0.,0.};
		TGeoGlobalMagField::Instance()->Field(x,b);
		AliInfo(Form("Field = %e %e %e",b[0],b[1],b[2]));

	fPt = 0.3*TMath::Abs(b[2]/10.)*rr/100.*TMath::Sign(1.,b[2]*rx*(-phi));

	AliInfo(Form("pt = %f",fPt));;

}

//___________________________________________________________________________

void AliMFTCATrack::AddCell(AliMFTCACell *cell) {

  if (fNcells >= fNDetMax) { printf("Max number of cells in this track!\n"); return; }
  new ((*fCells)[fNcells]) AliMFTCACell(*cell);
  fCellGIDarray[fNcells] = cell->GetGID();
  fNcells++;

}

//___________________________________________________________________________

Double_t AliMFTCATrack::AddCellToChiSq(AliMFTCACell *cell) {

  const Int_t nMaxh = 100;
  Double_t xTr[nMaxh], yTr[nMaxh], zTr[nMaxh];
  Double_t a, ae, b, be, x0, xS, y0, yS, chisqx, chisqy;
  Double_t xTrErrDet = 0.0025/TMath::Sqrt(12.);
  Double_t yTrErrDet = 0.0025/TMath::Sqrt(12.);
  Double_t xTrErrMS = 0.00055; // estimated at p = 5.5 GeV/c
  Double_t yTrErrMS = 0.00055; // estimated at p = 5.5 GeV/c
  Double_t xTrErr[nMaxh], yTrErr[nMaxh];
  for (Int_t i = 0; i < nMaxh; i++) {
    xTrErr[i] = TMath::Sqrt(xTrErrDet*xTrErrDet+xTrErrMS*xTrErrMS);
    yTrErr[i] = TMath::Sqrt(yTrErrDet*yTrErrDet+yTrErrMS*yTrErrMS);
  }
  Int_t cellGID, ndof, nptr = 0;

  AliMFTCACell *celltr;

  for (Int_t iCell = 0; iCell < GetNcells(); iCell++) {
    celltr = (AliMFTCACell*)fCells->At(iCell);
    // extract hit x,y,z
    if (nptr == 0) {
      xTr[nptr] = celltr->GetHit2()[0];
      yTr[nptr] = celltr->GetHit2()[1];
      zTr[nptr] = celltr->GetHit2()[2];
      nptr++;
      xTr[nptr] = celltr->GetHit1()[0];
      yTr[nptr] = celltr->GetHit1()[1];
      zTr[nptr] = celltr->GetHit1()[2];
      nptr++;
    } else {
      xTr[nptr] = celltr->GetHit1()[0];
      yTr[nptr] = celltr->GetHit1()[1];
      zTr[nptr] = celltr->GetHit1()[2];
      nptr++;
    }
  } // END : cells loop
    // the new cell
  xTr[nptr] = cell->GetHit1()[0];
  yTr[nptr] = cell->GetHit1()[1];
  zTr[nptr] = cell->GetHit1()[2];
  nptr++;
  // linear regression
//  if (LinFit(nptr,zTr,xTr,xTrErr,a,ae,b,be)) {
//    x0 = b; xS = a;
//    if (LinFit(nptr,zTr,yTr,yTrErr,a,ae,b,be)) {
//      y0 = b; yS = a;
//      chisqx = 0.;
//      chisqy = 0.;
//      for (Int_t iptr = 0; iptr < nptr; iptr++) {
//        //printf("%d  %f  %f  %f  \n",iptr,xTr[iptr],yTr[iptr],zTr[iptr]);
//        chisqx += (xTr[iptr]-(xS*zTr[iptr]+x0))*(xTr[iptr]-(xS*zTr[iptr]+x0))/(xTrErr[iptr]*xTrErr[iptr]);
//        chisqy += (yTr[iptr]-(yS*zTr[iptr]+y0))*(yTr[iptr]-(yS*zTr[iptr]+y0))/(yTrErr[iptr]*yTrErr[iptr]);
//      }
//    }
//  }
  ndof = 2*nptr-4;

  return (chisqx+chisqy)/(Double_t)ndof;

}
<commit_msg>Adding division per zero protection<commit_after>#include "TMath.h"
#include <TGeoGlobalMagField.h>

#include "AliMFTCATrack.h"
#include "AliMFTCACell.h"
#include "AliMFTTrackExtrap.h"

#include "AliLog.h"

ClassImp(AliMFTCATrack)

//___________________________________________________________________________

AliMFTCATrack::AliMFTCATrack() :
TObject(),
fGID(-1),
fNcells(0),
fStartLayer(-1),
fCellGIDarray(),
fMCflag(0),
fVertX(0.),
fVertY(0.),
fVertZ(0.),
fTheta(0.),
fPhi(0.),
fChiSqX(0.),
fChiSqY(0.),
fMCindex(-1),
fChargeSign(0.),
fPt(0.)
{

  fCells = new TClonesArray("AliMFTCACell", fNDetMax);

}

//___________________________________________________________________________

AliMFTCATrack::AliMFTCATrack(const AliMFTCATrack &track) :
TObject(track),
fGID(track.fGID),
fNcells(track.fNcells),
fStartLayer(track.fStartLayer),
fMCflag(track.fMCflag),
fVertX(track.fVertX),
fVertY(track.fVertY),
fVertZ(track.fVertZ),
fTheta(track.fTheta),
fPhi(track.fPhi),
fChiSqX(track.fChiSqX),
fChiSqY(track.fChiSqY),
fMCindex(track.fMCindex),
fChargeSign(track.fChargeSign),
fPt(track.fPt)
{

  // copy constructor

  fCells = new TClonesArray("AliMFTCACell", fNDetMax);

  for (Int_t icell = 0; icell < track.fNcells; icell++)
  fCellGIDarray[icell] = track.fCellGIDarray[icell];

}

//___________________________________________________________________________

AliMFTCATrack& AliMFTCATrack::operator=(const AliMFTCATrack& track)
{

  // assignment operator

  // check assignement to self
  if (this == &track) return *this;

  TObject::operator=(track);

  fGID = track.fGID;
  fNcells = track.fNcells;
  fStartLayer = track.fStartLayer;
  fCells = new TClonesArray("AliMFTCACell", fNDetMax);
  for (Int_t icell = 0; icell < track.fNcells; icell++)
  fCellGIDarray[icell] = track.fCellGIDarray[icell];
  fMCflag = track.fMCflag;
  fVertX = track.fVertX;
  fVertY = track.fVertY;
  fVertZ = track.fVertZ;
  fTheta = track.fTheta;
  fPhi = track.fPhi;
  fChiSqX = track.fChiSqX;
  fChiSqY = track.fChiSqY;
  fMCindex = track.fMCindex;
  fChargeSign = track.fChargeSign;
  fPt = track.fPt;

}

//___________________________________________________________________________

void AliMFTCATrack::Clear(Option_t *) {

}
//___________________________________________________________________________

/// Estimate the charge sign
void  AliMFTCATrack::EvalSignedPt(){
	const Int_t nMaxh = 100;
	Double_t xTr[nMaxh], yTr[nMaxh], zTr[nMaxh];
	Double_t r[nMaxh], u[nMaxh] , v[nMaxh];

	AliMFTCACell *celltr;
	Int_t nptr = 0;

	for (Int_t iCell = 0; iCell < GetNcells(); iCell++) {
		celltr = (AliMFTCACell*)fCells->At(iCell);
		// extract hit x,y,z
		if (nptr == 0) {
			xTr[nptr] = celltr->GetHit2()[0];
			yTr[nptr] = celltr->GetHit2()[1];
			zTr[nptr] = celltr->GetHit2()[2];
			nptr++;
			xTr[nptr] = celltr->GetHit1()[0];
			yTr[nptr] = celltr->GetHit1()[1];
			zTr[nptr] = celltr->GetHit1()[2];
			nptr++;
		} else {
			xTr[nptr] = celltr->GetHit1()[0];
			yTr[nptr] = celltr->GetHit1()[1];
			zTr[nptr] = celltr->GetHit1()[2];
			nptr++;
		}
	} // END : cells loop
	for (Int_t i = 0; i< nptr; i++) {
		AliInfo(Form("x,y,z = %f %f %f",xTr[i],yTr[i],zTr[i]));
	}
//	Double_t distL = 0., q2=0.;
//	Double_t sagitta = AliMFTTrackExtrap::Sagitta(nptr, xTr, yTr, distL,q2);
//	AliInfo(Form("sagitta = %f",sagitta));;
//	AliInfo(Form("distL = %f",distL));;
//
//	AliInfo(Form("q2 = %f => pt = %f ",q2, 0.01/q2/2.*0.3*b[2]/10.));
//
//	//fPt = 0.3*TMath::Abs(b[2]/10.)*distL*distL/8./sagitta;
//	fPt = 0.3*TMath::Abs(b[2]/10.)*AliMFTTrackExtrap::CircleRegression(nptr, xTr, yTr)*TMath::Sign(1.,sagitta);
// //fPt =0.01/q2/2.*0.3*b[2]/10.;

	for (Int_t iptr = 0; iptr < nptr; iptr++) {

		r[iptr] = TMath::Sqrt(yTr[iptr]*yTr[iptr]+xTr[iptr]*xTr[iptr]);
		u[iptr] = xTr[iptr]/r[iptr]/r[iptr];
		v[iptr] = yTr[iptr]/r[iptr]/r[iptr];

		AliInfo(Form("u,v,r = %f %f %f ",u[iptr],v[iptr],r[iptr]));

	}
	Double_t fdump, slopeX_Z, slopeY_Z;
	AliMFTTrackExtrap::LinearRegression(nptr, xTr,zTr, fdump, slopeX_Z);
	AliMFTTrackExtrap::LinearRegression(nptr, yTr,zTr, fdump, slopeY_Z);

	Double_t phi = TMath::ATan2(slopeY_Z,slopeX_Z);
	Double_t xS,x0;
	Double_t chi2 = AliMFTTrackExtrap::LinearRegression(nptr, u,v, x0, xS);
  AliInfo(Form("chi2 = %f x0, xS %f %f",chi2,x0,xS));;

  if (TMath::Abs(x0)<1.e-10) {
    fPt = 1.e6;
    return;
  }

	Double_t rx = -xS/(2.*x0);
	Double_t ry =  1./(2.*x0);
	Double_t rr = TMath::Sqrt(rx*rx+ry*ry);
	AliInfo(Form("Rx,Ry = %f %f",rx,ry));;
	AliInfo(Form("R = %f",rr));;
	AliInfo(Form("Phi = %f",phi));;

		Double_t zmean = 0.5 * (AliMFTConstants::DefaultPlaneZ(0) + AliMFTConstants::DefaultPlaneZ(9));
		const Double_t x[3] = {0.,0.,zmean};
		Double_t b[3] = {0.,0.,0.};
		TGeoGlobalMagField::Instance()->Field(x,b);
		AliInfo(Form("Field = %e %e %e",b[0],b[1],b[2]));

	fPt = 0.3*TMath::Abs(b[2]/10.)*rr/100.*TMath::Sign(1.,b[2]*rx*(-phi));

	AliInfo(Form("pt = %f",fPt));;

}

//___________________________________________________________________________

void AliMFTCATrack::AddCell(AliMFTCACell *cell) {

  if (fNcells >= fNDetMax) { printf("Max number of cells in this track!\n"); return; }
  new ((*fCells)[fNcells]) AliMFTCACell(*cell);
  fCellGIDarray[fNcells] = cell->GetGID();
  fNcells++;

}

//___________________________________________________________________________

Double_t AliMFTCATrack::AddCellToChiSq(AliMFTCACell *cell) {

  const Int_t nMaxh = 100;
  Double_t xTr[nMaxh], yTr[nMaxh], zTr[nMaxh];
  Double_t a, ae, b, be, x0, xS, y0, yS, chisqx, chisqy;
  Double_t xTrErrDet = 0.0025/TMath::Sqrt(12.);
  Double_t yTrErrDet = 0.0025/TMath::Sqrt(12.);
  Double_t xTrErrMS = 0.00055; // estimated at p = 5.5 GeV/c
  Double_t yTrErrMS = 0.00055; // estimated at p = 5.5 GeV/c
  Double_t xTrErr[nMaxh], yTrErr[nMaxh];
  for (Int_t i = 0; i < nMaxh; i++) {
    xTrErr[i] = TMath::Sqrt(xTrErrDet*xTrErrDet+xTrErrMS*xTrErrMS);
    yTrErr[i] = TMath::Sqrt(yTrErrDet*yTrErrDet+yTrErrMS*yTrErrMS);
  }
  Int_t cellGID, ndof, nptr = 0;

  AliMFTCACell *celltr;

  for (Int_t iCell = 0; iCell < GetNcells(); iCell++) {
    celltr = (AliMFTCACell*)fCells->At(iCell);
    // extract hit x,y,z
    if (nptr == 0) {
      xTr[nptr] = celltr->GetHit2()[0];
      yTr[nptr] = celltr->GetHit2()[1];
      zTr[nptr] = celltr->GetHit2()[2];
      nptr++;
      xTr[nptr] = celltr->GetHit1()[0];
      yTr[nptr] = celltr->GetHit1()[1];
      zTr[nptr] = celltr->GetHit1()[2];
      nptr++;
    } else {
      xTr[nptr] = celltr->GetHit1()[0];
      yTr[nptr] = celltr->GetHit1()[1];
      zTr[nptr] = celltr->GetHit1()[2];
      nptr++;
    }
  } // END : cells loop
    // the new cell
  xTr[nptr] = cell->GetHit1()[0];
  yTr[nptr] = cell->GetHit1()[1];
  zTr[nptr] = cell->GetHit1()[2];
  nptr++;
  // linear regression
//  if (LinFit(nptr,zTr,xTr,xTrErr,a,ae,b,be)) {
//    x0 = b; xS = a;
//    if (LinFit(nptr,zTr,yTr,yTrErr,a,ae,b,be)) {
//      y0 = b; yS = a;
//      chisqx = 0.;
//      chisqy = 0.;
//      for (Int_t iptr = 0; iptr < nptr; iptr++) {
//        //printf("%d  %f  %f  %f  \n",iptr,xTr[iptr],yTr[iptr],zTr[iptr]);
//        chisqx += (xTr[iptr]-(xS*zTr[iptr]+x0))*(xTr[iptr]-(xS*zTr[iptr]+x0))/(xTrErr[iptr]*xTrErr[iptr]);
//        chisqy += (yTr[iptr]-(yS*zTr[iptr]+y0))*(yTr[iptr]-(yS*zTr[iptr]+y0))/(yTrErr[iptr]*yTrErr[iptr]);
//      }
//    }
//  }
  ndof = 2*nptr-4;

  return (chisqx+chisqy)/(Double_t)ndof;

}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkExtractSelectedGraph.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkExtractSelectedGraph.h"

#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkDataArray.h"
#include "vtkEventForwarderCommand.h"
#include "vtkGraph.h"
#include "vtkGraphIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"

#include <vtksys/stl/map>
using vtksys_stl::map;

vtkCxxRevisionMacro(vtkExtractSelectedGraph, "1.1");
vtkStandardNewMacro(vtkExtractSelectedGraph);

vtkExtractSelectedGraph::vtkExtractSelectedGraph()
{
  this->SetNumberOfInputPorts(2);

  // Set default input array
  this->SetInputArrayToProcess(0, 1, 0, vtkDataObject::FIELD_ASSOCIATION_NONE, "selection");
}

vtkExtractSelectedGraph::~vtkExtractSelectedGraph()
{
}

int vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)
{
  if (port == 0)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph");
    return 1;
    }
  else if (port == 1)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
    return 1;
    }
  return 0;
}

void vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)
{
  this->SetInputConnection(1, in);
}

void vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

int vtkExtractSelectedGraph::RequestData(
  vtkInformation* vtkNotUsed(request),
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  //cerr << "in subgraph filter" << endl;
  vtkGraph* input = vtkGraph::GetData(inputVector[0]);
  vtkSelection* selection = vtkSelection::GetData(inputVector[1]);

  int content = selection->GetProperties()->Get(selection->CONTENT_TYPE());
  if (content != vtkSelection::INDICES)
    {
    vtkErrorMacro("Selection must be of type INDICES.");
    return 0;
    }
  vtkAbstractArray* arr = selection->GetSelectionList();
  if (arr == NULL)
    {
    vtkErrorMacro("Selection list not found.");
    return 0;
    }
  vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);
  if (selectArr == NULL)
    {
    vtkErrorMacro("Selection list must be of type vtkIdTypeArray.");
    return 0;
    }
  vtkIdType selectSize = selectArr->GetNumberOfTuples();

  vtkGraph* output = vtkGraph::GetData(outputVector);

  output->SetDirected(input->GetDirected());
  output->GetFieldData()->PassData(input->GetFieldData());

  // Copy selected vertices
  double pt[3];
  vtkPoints* inputPoints = input->GetPoints();
  vtkPoints* outputPoints = vtkPoints::New();
  vtkPointData* inputVertexData = input->GetVertexData();
  vtkPointData* outputVertexData = output->GetVertexData();
  outputVertexData->CopyAllocate(inputVertexData);
  map<vtkIdType, vtkIdType> idMap;
  for (vtkIdType i = 0; i < selectSize; i++)
    {
    vtkIdType inputVertex = selectArr->GetValue(i);
    //cerr << "selected vertex " << inputVertex << endl;
    vtkIdType outputVertex = output->AddVertex();
    outputVertexData->CopyData(inputVertexData, inputVertex, outputVertex);
    idMap[inputVertex] = outputVertex;
    inputPoints->GetPoint(inputVertex, pt);
    outputPoints->InsertNextPoint(pt);
    }
  output->SetPoints(outputPoints);
  outputPoints->Delete();

  // Copy selected edges
  vtkCellData* inputEdgeData = input->GetEdgeData();
  vtkCellData* outputEdgeData = output->GetEdgeData();
  outputEdgeData->CopyAllocate(inputEdgeData);
  for (vtkIdType i = 0; i < selectSize; i++)
    {
    vtkIdType inputVertex = selectArr->GetValue(i);
    vtkIdType outputVertex = idMap[inputVertex];
    vtkIdType nedges;
    const vtkIdType* edges;
    input->GetOutEdges(inputVertex, nedges, edges);
    for (vtkIdType j = 0; j < nedges; j++)
      {
      vtkIdType inputEdge = edges[j];
      vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);
      if (idMap.count(oppInputVertex) > 0)
        {
        vtkIdType oppOutputVertex = idMap[oppInputVertex];
        vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);
        outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
        }
      }
    }

  for (vtkIdType i = 0; i < output->GetNumberOfVertices(); i++)
    {
    output->GetPoint(i, pt);
    //cerr << "subgraph point " << i << " " << pt[0] << "," << pt[1] << "," << pt[2] << endl;
    }

  // Clean up
  output->Squeeze();

  return 1;
}

<commit_msg>ENH: Changed to take vtkAbstractGraph as input instead of vtkGraph.  This allows vtkTree input.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkExtractSelectedGraph.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkExtractSelectedGraph.h"

#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkDataArray.h"
#include "vtkEventForwarderCommand.h"
#include "vtkGraph.h"
#include "vtkGraphIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"

#include <vtksys/stl/map>
using vtksys_stl::map;

vtkCxxRevisionMacro(vtkExtractSelectedGraph, "1.2");
vtkStandardNewMacro(vtkExtractSelectedGraph);

vtkExtractSelectedGraph::vtkExtractSelectedGraph()
{
  this->SetNumberOfInputPorts(2);

  // Set default input array
  this->SetInputArrayToProcess(0, 1, 0, vtkDataObject::FIELD_ASSOCIATION_NONE, "selection");
}

vtkExtractSelectedGraph::~vtkExtractSelectedGraph()
{
}

int vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)
{
  if (port == 0)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkAbstractGraph");
    return 1;
    }
  else if (port == 1)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
    return 1;
    }
  return 0;
}

void vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)
{
  this->SetInputConnection(1, in);
}

void vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

int vtkExtractSelectedGraph::RequestData(
  vtkInformation* vtkNotUsed(request),
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  //cerr << "in subgraph filter" << endl;
  vtkAbstractGraph* input = vtkAbstractGraph::GetData(inputVector[0]);
  vtkSelection* selection = vtkSelection::GetData(inputVector[1]);

  int content = selection->GetProperties()->Get(selection->CONTENT_TYPE());
  if (content != vtkSelection::INDICES)
    {
    vtkErrorMacro("Selection must be of type INDICES.");
    return 0;
    }
  vtkAbstractArray* arr = selection->GetSelectionList();
  if (arr == NULL)
    {
    vtkErrorMacro("Selection list not found.");
    return 0;
    }
  vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);
  if (selectArr == NULL)
    {
    vtkErrorMacro("Selection list must be of type vtkIdTypeArray.");
    return 0;
    }
  vtkIdType selectSize = selectArr->GetNumberOfTuples();

  vtkGraph* output = vtkGraph::GetData(outputVector);

  output->SetDirected(input->GetDirected());
  output->GetFieldData()->PassData(input->GetFieldData());

  // Copy selected vertices
  double pt[3];
  vtkPoints* inputPoints = input->GetPoints();
  vtkPoints* outputPoints = vtkPoints::New();
  vtkPointData* inputVertexData = input->GetVertexData();
  vtkPointData* outputVertexData = output->GetVertexData();
  outputVertexData->CopyAllocate(inputVertexData);
  map<vtkIdType, vtkIdType> idMap;
  for (vtkIdType i = 0; i < selectSize; i++)
    {
    vtkIdType inputVertex = selectArr->GetValue(i);
    //cerr << "selected vertex " << inputVertex << endl;
    vtkIdType outputVertex = output->AddVertex();
    outputVertexData->CopyData(inputVertexData, inputVertex, outputVertex);
    idMap[inputVertex] = outputVertex;
    inputPoints->GetPoint(inputVertex, pt);
    outputPoints->InsertNextPoint(pt);
    }
  output->SetPoints(outputPoints);
  outputPoints->Delete();

  // Copy selected edges
  vtkCellData* inputEdgeData = input->GetEdgeData();
  vtkCellData* outputEdgeData = output->GetEdgeData();
  outputEdgeData->CopyAllocate(inputEdgeData);
  vtkGraphIdList* edgeList = vtkGraphIdList::New();
  for (vtkIdType i = 0; i < selectSize; i++)
    {
    vtkIdType inputVertex = selectArr->GetValue(i);
    vtkIdType outputVertex = idMap[inputVertex];
    input->GetOutEdges(inputVertex, edgeList);
    //vtkIdType nedges;
    //const vtkIdType* edges;
    //input->GetOutEdges(inputVertex, nedges, edges);
    //for (vtkIdType j = 0; j < nedges; j++)
    for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)
      {
      //vtkIdType inputEdge = edges[j];
      vtkIdType inputEdge = edgeList->GetId(j);
      vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);
      if (idMap.count(oppInputVertex) > 0)
        {
        vtkIdType oppOutputVertex = idMap[oppInputVertex];
        vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);
        outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
        }
      }
    }
  edgeList->Delete();

  for (vtkIdType i = 0; i < output->GetNumberOfVertices(); i++)
    {
    output->GetPoint(i, pt);
    //cerr << "subgraph point " << i << " " << pt[0] << "," << pt[1] << "," << pt[2] << endl;
    }

  // Clean up
  output->Squeeze();

  return 1;
}

<|endoftext|>


<commit_before>// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Renderer/ContextParameters.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <Nazara/Renderer/Debug.hpp>

namespace Nz
{
	// Version majeure d'OpenGL, initialisé par OpenGL::Initialize()
	UInt8 ContextParameters::defaultMajorVersion;

	 // Version majeure d'OpenGL, initialisé par OpenGL::Initialize()
	UInt8 ContextParameters::defaultMinorVersion;

	// Contexte de partage par défaut, initialisé par OpenGL::Initialize()
	const Context* ContextParameters::defaultShareContext = nullptr;

	// Si possible, garder la compatibilité avec les fonctionnalités dépréciées
	bool ContextParameters::defaultCompatibilityProfile = false;

	// Mode debug d'OpenGL par défaut
	#if NAZARA_RENDERER_OPENGL_DEBUG || defined(NAZARA_DEBUG)
	bool ContextParameters::defaultDebugMode = true;
	#else
	bool ContextParameters::defaultDebugMode = false;
	#endif

	// Active le double-buffering sur les contextes
	bool ContextParameters::defaultDoubleBuffered = false;

	// Active le partage des ressources entre contextes (Via le defaultShareContext)
	bool ContextParameters::defaultShared = true;
}
<commit_msg>Update ContextParameters.cpp (#119)<commit_after>// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Renderer/ContextParameters.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <Nazara/Renderer/Debug.hpp>

namespace Nz
{
	// Major version of OpenGL, initialised by OpenGL::Initialize()
	UInt8 ContextParameters::defaultMajorVersion;

	 // Minor version of OpenGL, initialised by OpenGL::Initialize()
	UInt8 ContextParameters::defaultMinorVersion;

	// Context of default sharing, initialised by OpenGL::Initialize()
	const Context* ContextParameters::defaultShareContext = nullptr;

	// If it's possible, keep the compatibility with deprecated functionalities
	bool ContextParameters::defaultCompatibilityProfile = false;

	// Default debug mode of OpenGL
	#if NAZARA_RENDERER_OPENGL_DEBUG || defined(NAZARA_DEBUG)
	bool ContextParameters::defaultDebugMode = true;
	#else
	bool ContextParameters::defaultDebugMode = false;
	#endif

	// Enables double-buffering on contexts Active le double-buffering sur les contextes
	bool ContextParameters::defaultDoubleBuffered = false;

	// Enables ressource sharing on contexts (via defaultShareContext)
	bool ContextParameters::defaultShared = true;
}
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "WindowlessGlxApplication.h"

#include <Utility/Assert.h>
#include <Utility/Debug.h>

#include "Context.h"

#define None 0L // redef Xlib nonsense

namespace Magnum { namespace Platform {

WindowlessGlxApplication::WindowlessGlxApplication(const Arguments&) {
    createContext(new Configuration);
}

WindowlessGlxApplication::WindowlessGlxApplication(const Arguments&, Configuration* configuration) {
    if(configuration) createContext(configuration);
}

void WindowlessGlxApplication::createContext(Configuration* configuration) {
    CORRADE_ASSERT(!c, "WindowlessGlxApplication::createContext(): context already created", );

    display = XOpenDisplay(nullptr);

    /* Check version */
    int major, minor;
    glXQueryVersion(display, &major, &minor);
    if(major == 1 && minor < 4) {
        Error() << "WindowlessGlxApplication: GLX version 1.4 or greater is required.";
        std::exit(1);
    }

    /* Choose config */
    int configCount = 0;
    static const int fbAttributes[] = { None };
    GLXFBConfig* configs = glXChooseFBConfig(display, DefaultScreen(display), fbAttributes, &configCount);
    if(!configCount) {
        Error() << "WindowlessGlxApplication: no supported framebuffer configuration found.";
        std::exit(1);
    }

    GLint contextAttributes[] = {
        #ifdef MAGNUM_TARGET_GLES
        GLX_CONTEXT_MAJOR_VERSION_ARB, 2,
        GLX_CONTEXT_MINOR_VERSION_ARB, 0,
        GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES2_PROFILE_BIT_EXT,
        #endif
        0
    };

    /** @todo Use some extension wrangler for this, not GLEW, as it apparently needs context to create context, yo dawg wtf. */
    PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
    context = glXCreateContextAttribsARB(display, configs[0], nullptr, True, contextAttributes);
    if(!context) {
        Error() << "WindowlessGlxApplication: cannot create context.";
        std::exit(1);
    }

    /* Create pbuffer */
    int pbufferAttributes[] = {
        GLX_PBUFFER_WIDTH,  32,
        GLX_PBUFFER_HEIGHT, 32,
        None
    };
    pbuffer = glXCreatePbuffer(display, configs[0], pbufferAttributes);

    XFree(configs);

    /* Set OpenGL context as current */
    if(!glXMakeContextCurrent(display, pbuffer, pbuffer, context)) {
        Error() << "WindowlessGlxApplication: cannot make context current";
        std::exit(1);
    }

    /* Initialize extension wrangler */
    ExtensionWrangler::initialize(ExtensionWrangler::ExperimentalFeatures::Enable);

    c = new Context;
    delete configuration;
}

WindowlessGlxApplication::~WindowlessGlxApplication() {
    glXMakeCurrent(display, None, nullptr);
    glXDestroyContext(display, context);
}

WindowlessGlxApplication::Configuration::Configuration() = default;
WindowlessGlxApplication::Configuration::~Configuration() = default;

}}
<commit_msg>Platform: fix WindowlessGlxApplication context creation and destruction.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "WindowlessGlxApplication.h"

#include <Utility/Assert.h>
#include <Utility/Debug.h>

#include "Context.h"

#define None 0L // redef Xlib nonsense

namespace Magnum { namespace Platform {

WindowlessGlxApplication::WindowlessGlxApplication(const Arguments&): c(nullptr) {
    createContext(new Configuration);
}

WindowlessGlxApplication::WindowlessGlxApplication(const Arguments&, Configuration* configuration): c(nullptr) {
    if(configuration) createContext(configuration);
}

void WindowlessGlxApplication::createContext(Configuration* configuration) {
    CORRADE_ASSERT(!c, "WindowlessGlxApplication::createContext(): context already created", );

    display = XOpenDisplay(nullptr);

    /* Check version */
    int major, minor;
    glXQueryVersion(display, &major, &minor);
    if(major == 1 && minor < 4) {
        Error() << "WindowlessGlxApplication: GLX version 1.4 or greater is required.";
        std::exit(1);
    }

    /* Choose config */
    int configCount = 0;
    static const int fbAttributes[] = { None };
    GLXFBConfig* configs = glXChooseFBConfig(display, DefaultScreen(display), fbAttributes, &configCount);
    if(!configCount) {
        Error() << "WindowlessGlxApplication: no supported framebuffer configuration found.";
        std::exit(1);
    }

    GLint contextAttributes[] = {
        #ifdef MAGNUM_TARGET_GLES
        GLX_CONTEXT_MAJOR_VERSION_ARB, 2,
        GLX_CONTEXT_MINOR_VERSION_ARB, 0,
        GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES2_PROFILE_BIT_EXT,
        #endif
        0
    };

    /** @todo Use some extension wrangler for this, not GLEW, as it apparently needs context to create context, yo dawg wtf. */
    PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
    context = glXCreateContextAttribsARB(display, configs[0], nullptr, True, contextAttributes);
    if(!context) {
        Error() << "WindowlessGlxApplication: cannot create context.";
        std::exit(1);
    }

    /* Create pbuffer */
    int pbufferAttributes[] = {
        GLX_PBUFFER_WIDTH,  32,
        GLX_PBUFFER_HEIGHT, 32,
        None
    };
    pbuffer = glXCreatePbuffer(display, configs[0], pbufferAttributes);

    XFree(configs);

    /* Set OpenGL context as current */
    if(!glXMakeContextCurrent(display, pbuffer, pbuffer, context)) {
        Error() << "WindowlessGlxApplication: cannot make context current";
        std::exit(1);
    }

    /* Initialize extension wrangler */
    ExtensionWrangler::initialize(ExtensionWrangler::ExperimentalFeatures::Enable);

    c = new Context;
    delete configuration;
}

WindowlessGlxApplication::~WindowlessGlxApplication() {
    delete c;

    glXMakeCurrent(display, None, nullptr);
    glXDestroyContext(display, context);
}

WindowlessGlxApplication::Configuration::Configuration() = default;
WindowlessGlxApplication::Configuration::~Configuration() = default;

}}
<|endoftext|>