<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "dll_test.hpp"

#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/neural/activation_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/avgp_layer.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("unit/conv/sgd/9", "[conv][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, 28, 28, 5, 5, 5, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<5 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>, dll::scale_pre<255>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    FT_CHECK(25, 6e-2);
    TEST_CHECK(0.3);
}

TEST_CASE("unit/conv/sgd/10", "[unit][conv][dbn][mnist][sgd]") {
    //Note: This is a reduced lenet version
    //Note: The activation layers are here to ensure compilation
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, 28, 28, 8, 5, 5, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::RELU>>::layer_t,
            dll::mp_layer_3d_desc<8, 24, 24, 1, 2, 2>::layer_t,
            dll::conv_desc<8, 12, 12, 10, 5, 5, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::RELU>>::layer_t,
            dll::mp_layer_3d_desc<10, 8, 8, 1, 2, 2>::layer_t,
            dll::dense_desc<10 * 4 * 4, 500, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::RELU>>::layer_t,
            dll::dense_desc<500, 10, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::SOFTMAX>>::layer_t
        >, dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<25>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->l2_weight_cost   = 0.0005;
    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    FT_CHECK(25, 6e-2);
    TEST_CHECK(0.2);
}
<commit_msg>Stabilize lenet tests<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "dll_test.hpp"

#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/neural/activation_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/avgp_layer.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("unit/conv/sgd/9", "[conv][dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, 28, 28, 5, 5, 5, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<5 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>, dll::scale_pre<255>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    FT_CHECK(25, 6e-2);
    TEST_CHECK(0.3);
}

TEST_CASE("unit/conv/sgd/10", "[unit][conv][dbn][mnist][sgd]") {
    //Note: This is a reduced lenet version
    //Note: The activation layers are here to ensure compilation
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::RELU>>::layer_t,
            dll::mp_layer_3d_desc<6, 24, 24, 1, 2, 2>::layer_t,
            dll::conv_desc<6, 12, 12, 8, 5, 5, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::RELU>>::layer_t,
            dll::mp_layer_3d_desc<8, 8, 8, 1, 2, 2>::layer_t,
            dll::dense_desc<8 * 4 * 4, 500, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::RELU>>::layer_t,
            dll::dense_desc<500, 10, dll::activation<dll::function::IDENTITY>>::layer_t,
            dll::activation_layer_desc<dll::activation<dll::function::SOFTMAX>>::layer_t
        >, dll::shuffle, dll::momentum, dll::weight_decay<>, dll::trainer<dll::sgd_trainer>, dll::batch_size<25>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->l2_weight_cost   = 0.0005;
    dbn->initial_momentum = 0.9;
    dbn->final_momentum   = 0.9;
    dbn->learning_rate    = 0.01;

    FT_CHECK(25, 6e-2);
    TEST_CHECK(0.22);
}
<|endoftext|>


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

#include "bridgeimpl.hxx"

using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::bridge;

namespace remotebridges_factory {

    OBridge::OBridge( remote_Context *pContext ) :
        OComponentHelper( m_mutex ),
        m_pContext( pContext )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );

        remote_DisposingListener::acquire = thisAcquire;
        remote_DisposingListener::release = thisRelease;
        remote_DisposingListener::disposing = thisDisposing;

        m_pContext->aBase.acquire( (uno_Context*)m_pContext );
        m_pContext->addDisposingListener( m_pContext, ( remote_DisposingListener * ) this );
    }

    OBridge::~OBridge()
    {
        if( m_pContext )
        {
            m_pContext->aBase.release( (uno_Context * ) m_pContext );
        }
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    ::com::sun::star::uno::Any OBridge::queryInterface( const ::com::sun::star::uno::Type & aType ) throw(RuntimeException)
    {
        Any a = ::cppu::queryInterface(
            aType ,
            SAL_STATIC_CAST( XBridge * , this ),
            SAL_STATIC_CAST( XTypeProvider * ,  this ) );
        if( a.hasValue() )
        {
            return a;
        }

        return OComponentHelper::queryInterface( aType );
    }

    void OBridge::disposing()
    {
        if( m_pContext )
        {
            m_pContext->removeDisposingListener( m_pContext , ( remote_DisposingListener * )this);

            uno_Environment *pEnvRemote = 0;
            if( m_pContext->m_pConnection )
            {
                sal_Int32 nIndex = 0;
                OUString sProtocol = OUString( m_pContext->m_pProtocol ).getToken( 0 , ',' , nIndex );
                uno_getEnvironment( &pEnvRemote , sProtocol.pData , m_pContext );
                OSL_ASSERT( pEnvRemote );
            }
            else
            {
                // within disposing from the context, no further dispose necessary !
            }

            if( pEnvRemote )
            {
                pEnvRemote->dispose( pEnvRemote );
                pEnvRemote->release( pEnvRemote );
                pEnvRemote = 0;
            }

            m_pContext->aBase.release( (uno_Context*)m_pContext );
            m_pContext = 0;
        }
    }

    Reference< XInterface > OBridge::getInstance( const ::rtl::OUString& sInstanceName )
            throw(::com::sun::star::uno::RuntimeException)
    {
        Reference < XInterface > rReturn;

        remote_Context *pContext = 0;
        {
            MutexGuard guard( m_mutex );
            if( m_pContext && m_pContext->getRemoteInstance )
            {
                pContext = m_pContext;
                pContext->aBase.acquire( (uno_Context*)pContext );
            }
        }
        if( pContext )
        {
            sal_Int32 nIndex;
            OUString sProtocol = OUString( m_pContext->m_pProtocol ).getToken( 0 , ',' , nIndex );

            // get the appropriate remote environment
            uno_Environment *pEnvRemote = 0;
            uno_getEnvironment( &pEnvRemote , sProtocol.pData , pContext );

            if( ! pEnvRemote )
            {
                pContext->aBase.release( (uno_Context*) pContext );
                throw RuntimeException(
                    OUString( RTL_CONSTASCII_USTRINGPARAM( "RemoteBridge: bridge already disposed" ) ),
                    Reference< XInterface > () );
            }

            Type type = getCppuType( (Reference < XInterface > * ) 0 );

            remote_Interface *pRemoteI = 0;
            uno_Any exception;
            uno_Any *pException = &exception;

            pContext->getRemoteInstance(
                pEnvRemote,
                &pRemoteI,
                sInstanceName.pData,
                type.getTypeLibType(),
                &pException );
            pContext->aBase.release( (uno_Context*) pContext );
            pContext = 0;

            uno_Environment *pEnvCpp =0;
            OUString sCppuName( RTL_CONSTASCII_USTRINGPARAM( CPPU_CURRENT_LANGUAGE_BINDING_NAME ) );
            uno_getEnvironment( &pEnvCpp ,
                                sCppuName.pData ,
                                0 );
            Mapping map( pEnvRemote , pEnvCpp );

            pEnvCpp->release( pEnvCpp );
            pEnvRemote->release( pEnvRemote );

            if( pException )
            {
                typelib_CompoundTypeDescription * pCompType = 0 ;
                getCppuType( (Exception*)0 ).getDescription( (typelib_TypeDescription **) &pCompType );

                if( ! ((typelib_TypeDescription *)pCompType)->bComplete )
                {
                    typelib_typedescription_complete( (typelib_TypeDescription**) &pCompType );
                }
                XInterface *pXInterface = (XInterface *) map.mapInterface(
                    *(remote_Interface**) ( ((char*)pException->pData)+pCompType->pMemberOffsets[1] ),
                    getCppuType( (Reference< XInterface > *)0 ) );
                RuntimeException myException(
                    *((rtl_uString **)pException->pData),
                    Reference< XInterface > ( pXInterface , SAL_NO_ACQUIRE) );
                uno_any_destruct( pException , 0 );

                throw myException;
            }
            else if( pRemoteI )
            {
                // got an interface !
                XInterface * pCppI = ( XInterface * ) map.mapInterface( pRemoteI, type );
                rReturn = Reference<XInterface > ( pCppI, SAL_NO_ACQUIRE );
                pRemoteI->release( pRemoteI );
            }
        }
        else
        {
            throw RuntimeException(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "RemoteBridge: bridge already disposed." ) ),
                Reference< XInterface > () );
        }

        return rReturn;
    }

    ::rtl::OUString SAL_CALL OBridge::getName(  )
                throw(::com::sun::star::uno::RuntimeException)

    {
        return OUString( m_pContext->m_pName );
    }

    ::rtl::OUString OBridge::getDescription(  )
            throw(::com::sun::star::uno::RuntimeException)
    {
        return OUString( m_pContext->m_pDescription  );
    }

        // XTypeProvider
    Sequence< Type > SAL_CALL OBridge::getTypes(void) throw( RuntimeException )
    {
        static OTypeCollection *pCollection = 0;
        if( ! pCollection )
        {
            MutexGuard guard( Mutex::getGlobalMutex() );
            if( ! pCollection )
            {
                static OTypeCollection collection(
                    getCppuType( (Reference< XTypeProvider> * )0),
                    getCppuType( (Reference< XBridge > * ) 0 ),
                    OComponentHelper::getTypes() );
                pCollection = &collection;
            }
        }

        return (*pCollection).getTypes();
    }

    Sequence< sal_Int8 > SAL_CALL OBridge::getImplementationId(  ) throw( RuntimeException)
    {
        static OImplementationId *pId = 0;
        if( ! pId )
        {
            MutexGuard guard( Mutex::getGlobalMutex() );
            if( ! pId )
            {
                static OImplementationId id( sal_False );
                pId = &id;
            }
        }
        return (*pId).getImplementationId();
    }

    //----------------------
    // static methods
    //----------------------
    void OBridge::thisAcquire( remote_DisposingListener *p )
    {
        OBridge *m = (OBridge * ) p;
        m->acquire();
    }

    void OBridge::thisRelease( remote_DisposingListener *p )
    {
        OBridge *m = (OBridge * ) p;
        m->release();
    }

    void OBridge::thisDisposing( remote_DisposingListener * p, rtl_uString * )
    {
        OBridge *m  = (OBridge * ) p;
        m->dispose();
    }
}
<commit_msg>INTEGRATION: CWS pj65 (1.8.8); FILE MERGED 2006/10/31 13:25:38 pjanik 1.8.8.1: #i71027#: prevent warnings on Mac OS X with gcc 4.0.1.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bridgeimpl.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-21 17:42:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "bridgeimpl.hxx"

using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::bridge;

namespace remotebridges_factory {

    OBridge::OBridge( remote_Context *pContext ) :
        OComponentHelper( m_mutex ),
        m_pContext( pContext )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );

        remote_DisposingListener::acquire = thisAcquire;
        remote_DisposingListener::release = thisRelease;
        remote_DisposingListener::disposing = thisDisposing;

        m_pContext->aBase.acquire( (uno_Context*)m_pContext );
        m_pContext->addDisposingListener( m_pContext, ( remote_DisposingListener * ) this );
    }

    OBridge::~OBridge()
    {
        if( m_pContext )
        {
            m_pContext->aBase.release( (uno_Context * ) m_pContext );
        }
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    ::com::sun::star::uno::Any OBridge::queryInterface( const ::com::sun::star::uno::Type & aType ) throw(RuntimeException)
    {
        Any a = ::cppu::queryInterface(
            aType ,
            SAL_STATIC_CAST( XBridge * , this ),
            SAL_STATIC_CAST( XTypeProvider * ,  this ) );
        if( a.hasValue() )
        {
            return a;
        }

        return OComponentHelper::queryInterface( aType );
    }

    void OBridge::disposing()
    {
        if( m_pContext )
        {
            m_pContext->removeDisposingListener( m_pContext , ( remote_DisposingListener * )this);

            uno_Environment *pEnvRemote = 0;
            if( m_pContext->m_pConnection )
            {
                sal_Int32 nIndex = 0;
                OUString sProtocol = OUString( m_pContext->m_pProtocol ).getToken( 0 , ',' , nIndex );
                uno_getEnvironment( &pEnvRemote , sProtocol.pData , m_pContext );
                OSL_ASSERT( pEnvRemote );
            }
            else
            {
                // within disposing from the context, no further dispose necessary !
            }

            if( pEnvRemote )
            {
                pEnvRemote->dispose( pEnvRemote );
                pEnvRemote->release( pEnvRemote );
                pEnvRemote = 0;
            }

            m_pContext->aBase.release( (uno_Context*)m_pContext );
            m_pContext = 0;
        }
    }

    Reference< XInterface > OBridge::getInstance( const ::rtl::OUString& sInstanceName )
            throw(::com::sun::star::uno::RuntimeException)
    {
        Reference < XInterface > rReturn;

        remote_Context *pContext = 0;
        {
            MutexGuard guard( m_mutex );
            if( m_pContext && m_pContext->getRemoteInstance )
            {
                pContext = m_pContext;
                pContext->aBase.acquire( (uno_Context*)pContext );
            }
        }
        if( pContext )
        {
            sal_Int32 nIndex = 0;
            OUString sProtocol = OUString( m_pContext->m_pProtocol ).getToken( 0 , ',' , nIndex );

            // get the appropriate remote environment
            uno_Environment *pEnvRemote = 0;
            uno_getEnvironment( &pEnvRemote , sProtocol.pData , pContext );

            if( ! pEnvRemote )
            {
                pContext->aBase.release( (uno_Context*) pContext );
                throw RuntimeException(
                    OUString( RTL_CONSTASCII_USTRINGPARAM( "RemoteBridge: bridge already disposed" ) ),
                    Reference< XInterface > () );
            }

            Type type = getCppuType( (Reference < XInterface > * ) 0 );

            remote_Interface *pRemoteI = 0;
            uno_Any exception;
            uno_Any *pException = &exception;

            pContext->getRemoteInstance(
                pEnvRemote,
                &pRemoteI,
                sInstanceName.pData,
                type.getTypeLibType(),
                &pException );
            pContext->aBase.release( (uno_Context*) pContext );
            pContext = 0;

            uno_Environment *pEnvCpp =0;
            OUString sCppuName( RTL_CONSTASCII_USTRINGPARAM( CPPU_CURRENT_LANGUAGE_BINDING_NAME ) );
            uno_getEnvironment( &pEnvCpp ,
                                sCppuName.pData ,
                                0 );
            Mapping map( pEnvRemote , pEnvCpp );

            pEnvCpp->release( pEnvCpp );
            pEnvRemote->release( pEnvRemote );

            if( pException )
            {
                typelib_CompoundTypeDescription * pCompType = 0 ;
                getCppuType( (Exception*)0 ).getDescription( (typelib_TypeDescription **) &pCompType );

                if( ! ((typelib_TypeDescription *)pCompType)->bComplete )
                {
                    typelib_typedescription_complete( (typelib_TypeDescription**) &pCompType );
                }
                XInterface *pXInterface = (XInterface *) map.mapInterface(
                    *(remote_Interface**) ( ((char*)pException->pData)+pCompType->pMemberOffsets[1] ),
                    getCppuType( (Reference< XInterface > *)0 ) );
                RuntimeException myException(
                    *((rtl_uString **)pException->pData),
                    Reference< XInterface > ( pXInterface , SAL_NO_ACQUIRE) );
                uno_any_destruct( pException , 0 );

                throw myException;
            }
            else if( pRemoteI )
            {
                // got an interface !
                XInterface * pCppI = ( XInterface * ) map.mapInterface( pRemoteI, type );
                rReturn = Reference<XInterface > ( pCppI, SAL_NO_ACQUIRE );
                pRemoteI->release( pRemoteI );
            }
        }
        else
        {
            throw RuntimeException(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "RemoteBridge: bridge already disposed." ) ),
                Reference< XInterface > () );
        }

        return rReturn;
    }

    ::rtl::OUString SAL_CALL OBridge::getName(  )
                throw(::com::sun::star::uno::RuntimeException)

    {
        return OUString( m_pContext->m_pName );
    }

    ::rtl::OUString OBridge::getDescription(  )
            throw(::com::sun::star::uno::RuntimeException)
    {
        return OUString( m_pContext->m_pDescription  );
    }

        // XTypeProvider
    Sequence< Type > SAL_CALL OBridge::getTypes(void) throw( RuntimeException )
    {
        static OTypeCollection *pCollection = 0;
        if( ! pCollection )
        {
            MutexGuard guard( Mutex::getGlobalMutex() );
            if( ! pCollection )
            {
                static OTypeCollection collection(
                    getCppuType( (Reference< XTypeProvider> * )0),
                    getCppuType( (Reference< XBridge > * ) 0 ),
                    OComponentHelper::getTypes() );
                pCollection = &collection;
            }
        }

        return (*pCollection).getTypes();
    }

    Sequence< sal_Int8 > SAL_CALL OBridge::getImplementationId(  ) throw( RuntimeException)
    {
        static OImplementationId *pId = 0;
        if( ! pId )
        {
            MutexGuard guard( Mutex::getGlobalMutex() );
            if( ! pId )
            {
                static OImplementationId id( sal_False );
                pId = &id;
            }
        }
        return (*pId).getImplementationId();
    }

    //----------------------
    // static methods
    //----------------------
    void OBridge::thisAcquire( remote_DisposingListener *p )
    {
        OBridge *m = (OBridge * ) p;
        m->acquire();
    }

    void OBridge::thisRelease( remote_DisposingListener *p )
    {
        OBridge *m = (OBridge * ) p;
        m->release();
    }

    void OBridge::thisDisposing( remote_DisposingListener * p, rtl_uString * )
    {
        OBridge *m  = (OBridge * ) p;
        m->dispose();
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ScrollHelper.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef RPTUI_SCROLLHELPER_HXX
#define RPTUI_SCROLLHELPER_HXX

#include <vcl/scrbar.hxx>
#include <com/sun/star/report/XSection.hpp>
#include <comphelper/propmultiplex.hxx>
#include "ReportDefines.hxx"
#include <svtools/colorcfg.hxx>
#include <svx/svdedtv.hxx>
#include "cppuhelper/basemutex.hxx"
#include <rtl/ref.hxx>
#include <boost/shared_ptr.hpp>
#include <vcl/dockwin.hxx>
#include <MarkedSection.hxx>

class SdrView;
namespace rptui
{
    class OSectionsWindow;
    class ODesignView;
    class OReportWindow;
    class OSectionView;
    class OReportSection;
    class OReportModel;

    /** This class defines the scrollable area of the report design. It includes
        the h-ruler and the sections, and end marker. Not the start marker.
    */
    typedef Window OScrollWindowHelper_BASE;
    class OScrollWindowHelper :     public ::cppu::BaseMutex
                                ,   public OScrollWindowHelper_BASE/*TabPage*/
                                ,   public ::comphelper::OPropertyChangeListener
                                    , public IMarkedSection
    {
    private:
        ScrollBar           m_aHScroll;
        ScrollBar           m_aVScroll;
        ScrollBarBox        m_aCornerWin;       // window in the bottom right corner
        Size                m_aTotalPixelSize;
        Point               m_aPixOffset;       // offset to virtual window (pixel)
        ODesignView*        m_pParent;
        OReportWindow*      m_pChild;
        ::rtl::Reference<comphelper::OPropertyChangeMultiplexer >
                            m_pReportDefintionMultiPlexer; // listener for property changes

        DECL_LINK( ScrollHdl, ScrollBar*);
        Size ResizeScrollBars();
        void ImplInitSettings();
        void impl_initScrollBar( ScrollBar& _rScrollBar ) const;
        void impl_scrollContent( long nDeltaX, long nDeltaY );

        OScrollWindowHelper(OScrollWindowHelper&);
        void operator =(OScrollWindowHelper&);
    protected:
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
        // window
        virtual void            Resize();
        virtual long            Notify( NotifyEvent& rNEvt );
        // OPropertyChangeListener
        virtual void            _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& _rEvent) throw( ::com::sun::star::uno::RuntimeException);
    public:
        OScrollWindowHelper( ODesignView* _pReportDesignView);
        virtual ~OScrollWindowHelper();

        /** late ctor
        */
        void                    initialize();

        inline Point            getScrollOffset() const { return Point(m_aHScroll.GetThumbPos(),m_aVScroll.GetThumbPos())/*m_aScrollOffset*/; }
        inline OReportWindow*   getReportWindow() const { return m_pChild; }
        void                    setTotalSize(sal_Int32 _nWidth ,sal_Int32 _nHeight);
        inline Size             getTotalSize() const { return m_aTotalPixelSize; }
        inline ScrollBar*       GetHScroll() { return &m_aHScroll; }
        inline ScrollBar*       GetVScroll() { return &m_aVScroll; }

        // forwards
        void                    SetMode( DlgEdMode _eMode );
        void                    SetInsertObj( USHORT eObj,const ::rtl::OUString& _sShapeType = ::rtl::OUString());
        rtl::OUString           GetInsertObjString() const;
        void                    setGridSnap(BOOL bOn);
        void                    setDragStripes(BOOL bOn);
        BOOL                    isDragStripes() const;
        /** copies the current selection in this section
        */
        void Copy();

        /** returns if paste is allowed
        *
        * \return <TRUE/> if paste is allowed
        */
        BOOL IsPasteAllowed();

        /** paste a new control in this section
        */
        void Paste();

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll();

        /** returns <TRUE/> when a object is marked
        */
        BOOL HasSelection();

        /** removes the section at the given position.
        *
        * \param _nPosition Zero based.
        */
        void                    removeSection(USHORT _nPosition);

        /** adds a new section at position _nPosition.
            If the section is <NULL/> nothing happens.
            If the position is grater than the current elements, the section will be appended.
        */
        void                    addSection(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection
                                    ,const ::rtl::OUString& _sColorEntry
                                    ,USHORT _nPosition = USHRT_MAX);

        USHORT                  getSectionCount() const;

        /** turns the grid on or off
        *
        * \param _bVisible
        */
        void                    toggleGrid(sal_Bool _bVisible);

        /** unmark all objects on the views without the given one.
        *
        * @param _pSectionView The view where the objects should not be unmarked.
        */
        void                    unmarkAllObjects(OSectionView* _pSectionView);

        /** shows or hides the ruler.
        */
        void                    showRuler(sal_Bool _bShow);

        /** calculate the max width of the markers
        *
        * @param _bWithEnd  if <TRUE/> the end marker will be used for calculation as well otherwise not.
        * \return the max width
        */
        sal_Int32               getMaxMarkerWidth(sal_Bool _bWithEnd) const;

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool                handleKeyEvent(const KeyEvent& _rEvent);

        /** the the section as marked or not marked
            @param  _pSectionView   the section where to set the marked flag
            @param  _bMark  the marked flag
        */
        void                    setMarked(OSectionView* _pSectionView,sal_Bool _bMark);
        void                    setMarked(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection,sal_Bool _bMark);
        void                    setMarked(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> >& _xShape,sal_Bool _bMark);

        // IMarkedSection
        ::boost::shared_ptr<OReportSection> getMarkedSection(NearSectionAccess nsa = CURRENT) const;
        virtual void markSection(const sal_uInt16 _nPos);

        /** fills the positions of all collapsed sections.
        *
        * \param _rCollapsedPositions Out parameter which holds afterwards all positions of the collapsed sections.
        */
        void fillCollapsedSections(::std::vector<sal_uInt16>& _rCollapsedPositions) const;

        /** collpase all sections given by their position
        *
        * \param _aCollpasedSections The position of the sections which should be collapsed.
        */
        void collapseSections(const com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _aCollpasedSections);

        /** align all marked objects in all sections
        *
        * \param eHor
        * \param eVert
        * \param bBoundRects
        */
        void alignMarkedObjects(sal_Int32 _nControlModification, bool _bAlignAtSection, bool bBoundRects = false);

        sal_uInt32 getMarkedObjectCount() const;

        /** fills the vector with all selected control models
            /param  _rSelection The vector will be filled and will not be cleared before.
        */
        void fillControlModelSelection(::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rSelection) const;
    };
}
#endif // RPTUI_SCROLLHELPER_HXX
<commit_msg>INTEGRATION: CWS dba31a (1.5.28); FILE MERGED 2008/07/07 06:38:25 oj 1.5.28.4: #i80200# method to select different types 2008/06/26 14:26:32 oj 1.5.28.3: #i77916# impl zooming in report builder 2008/06/24 12:07:02 oj 1.5.28.2: RESYNC: (1.5-1.6); FILE MERGED 2008/06/13 11:40:19 oj 1.5.28.1: #i88506# impl hyphenation<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ScrollHelper.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef RPTUI_SCROLLHELPER_HXX
#define RPTUI_SCROLLHELPER_HXX

#include <vcl/scrbar.hxx>
#include <com/sun/star/report/XSection.hpp>
#include <comphelper/propmultiplex.hxx>
#include "ReportDefines.hxx"
#include <svtools/colorcfg.hxx>
#include <svx/svdedtv.hxx>
#include "cppuhelper/basemutex.hxx"
#include <rtl/ref.hxx>
#include <boost/shared_ptr.hpp>
#include <vcl/dockwin.hxx>
#include <MarkedSection.hxx>
#include "ReportWindow.hxx"

class SdrView;
namespace rptui
{
    class ODesignView;
    class OReportWindow;
    class OSectionView;
    class OReportSection;
    class OReportModel;

    /** This class defines the scrollable area of the report design. It includes
        the h-ruler and the sections, and end marker. Not the start marker.
    */
    typedef Window OScrollWindowHelper_BASE;
    class OScrollWindowHelper :     public ::cppu::BaseMutex
                                ,   public OScrollWindowHelper_BASE/*TabPage*/
                                ,   public ::comphelper::OPropertyChangeListener
                                    , public IMarkedSection
    {
    private:
        ScrollBar           m_aHScroll;
        ScrollBar           m_aVScroll;
        ScrollBarBox        m_aCornerWin;       // window in the bottom right corner
        Size                m_aTotalPixelSize;
        Point               m_aPixOffset;       // offset to virtual window (pixel)
        ODesignView*        m_pParent;
        OReportWindow       m_aReportWindow;
        ::rtl::Reference<comphelper::OPropertyChangeMultiplexer >
                            m_pReportDefintionMultiPlexer; // listener for property changes

        DECL_LINK( ScrollHdl, ScrollBar*);
        Size ResizeScrollBars();
        void ImplInitSettings();
        void impl_initScrollBar( ScrollBar& _rScrollBar ) const;
        void impl_scrollContent( long nDeltaX, long nDeltaY );

        OScrollWindowHelper(OScrollWindowHelper&);
        void operator =(OScrollWindowHelper&);
    protected:
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
        // window
        virtual void            Resize();
        virtual long            Notify( NotifyEvent& rNEvt );
        // OPropertyChangeListener
        virtual void            _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& _rEvent) throw( ::com::sun::star::uno::RuntimeException);
    public:
        OScrollWindowHelper( ODesignView* _pReportDesignView);
        virtual ~OScrollWindowHelper();

        /** late ctor
        */
        void                    initialize();

        inline Point            getScrollOffset() const { return Point(m_aHScroll.GetThumbPos(),m_aVScroll.GetThumbPos())/*m_aScrollOffset*/; }
        inline const OReportWindow& getReportWindow() const { return m_aReportWindow; }
        void                    setTotalSize(sal_Int32 _nWidth ,sal_Int32 _nHeight);
        inline Size             getTotalSize() const { return m_aTotalPixelSize; }
        inline ScrollBar*       GetHScroll() { return &m_aHScroll; }
        inline ScrollBar*       GetVScroll() { return &m_aVScroll; }

        // forwards
        void                    SetMode( DlgEdMode _eMode );
        void                    SetInsertObj( USHORT eObj,const ::rtl::OUString& _sShapeType = ::rtl::OUString());
        rtl::OUString           GetInsertObjString() const;
        void                    setGridSnap(BOOL bOn);
        void                    setDragStripes(BOOL bOn);
        BOOL                    isDragStripes() const;
        /** copies the current selection in this section
        */
        void Copy();

        /** returns if paste is allowed
        *
        * \return <TRUE/> if paste is allowed
        */
        BOOL IsPasteAllowed();

        /** paste a new control in this section
        */
        void Paste();

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll(const sal_uInt16 _nObjectType);

        /** returns <TRUE/> when a object is marked
        */
        BOOL HasSelection();

        /** removes the section at the given position.
        *
        * \param _nPosition Zero based.
        */
        void                    removeSection(USHORT _nPosition);

        /** adds a new section at position _nPosition.
            If the section is <NULL/> nothing happens.
            If the position is grater than the current elements, the section will be appended.
        */
        void                    addSection(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection
                                    ,const ::rtl::OUString& _sColorEntry
                                    ,USHORT _nPosition = USHRT_MAX);

        USHORT                  getSectionCount() const;

        /** turns the grid on or off
        *
        * \param _bVisible
        */
        void                    toggleGrid(sal_Bool _bVisible);

        /** unmark all objects on the views without the given one.
        *
        * @param _pSectionView The view where the objects should not be unmarked.
        */
        void                    unmarkAllObjects(OSectionView* _pSectionView);

        /** shows or hides the ruler.
        */
        void                    showRuler(sal_Bool _bShow);

        /** calculate the max width of the markers
        *
        * @param _bWithEnd  if <TRUE/> the end marker will be used for calculation as well otherwise not.
        * \return the max width
        */
        sal_Int32               getMaxMarkerWidth(sal_Bool _bWithEnd) const;

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool                handleKeyEvent(const KeyEvent& _rEvent);

        /** the the section as marked or not marked
            @param  _pSectionView   the section where to set the marked flag
            @param  _bMark  the marked flag
        */
        void                    setMarked(OSectionView* _pSectionView,sal_Bool _bMark);
        void                    setMarked(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection,sal_Bool _bMark);
        void                    setMarked(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> >& _xShape,sal_Bool _bMark);

        // IMarkedSection
        ::boost::shared_ptr<OSectionWindow> getMarkedSection(NearSectionAccess nsa = CURRENT) const;
        virtual void markSection(const sal_uInt16 _nPos);

        /** fills the positions of all collapsed sections.
        *
        * \param _rCollapsedPositions Out parameter which holds afterwards all positions of the collapsed sections.
        */
        void fillCollapsedSections(::std::vector<sal_uInt16>& _rCollapsedPositions) const;

        /** collpase all sections given by their position
        *
        * \param _aCollpasedSections The position of the sections which should be collapsed.
        */
        void collapseSections(const com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _aCollpasedSections);

        /** align all marked objects in all sections
        *
        * \param eHor
        * \param eVert
        * \param bBoundRects
        */
        void alignMarkedObjects(sal_Int32 _nControlModification, bool _bAlignAtSection, bool bBoundRects = false);

        sal_uInt32 getMarkedObjectCount() const;

        /** zoom the ruler and view windows
        */
        void zoom(const sal_Int16 _nZoom);

        /** fills the vector with all selected control models
            /param  _rSelection The vector will be filled and will not be cleared before.
        */
        void fillControlModelSelection(::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rSelection) const;
    };
}
#endif // RPTUI_SCROLLHELPER_HXX
<|endoftext|>


<commit_before>#include "helix/parity/pmd_handler.hh"

#include "helix/compat/endian.h"
#include "helix/order_book.hh"

#include <unordered_map>
#include <stdexcept>
#include <cstring>
#include <cstdint>
#include <cassert>
#include <cstdio>
#include <memory>
#include <string>

using namespace std;

namespace helix {

namespace parity {

static side_type pmd_side(char c)
{
    switch (c) {
    case 'B': return side_type::buy;
    case 'S': return side_type::sell;
    default:  throw invalid_argument(string("invalid argument: ") + to_string(c));
    }
}

trade_sign pmd_trade_sign(side_type s)
{
    switch (s) {
    case side_type::buy:  return trade_sign::seller_initiated;
    case side_type::sell: return trade_sign::buyer_initiated;
    default:              throw invalid_argument(string("invalid argument"));
    }
}

pmd_handler::pmd_handler()
{
}

bool pmd_handler::is_rth_timestamp(uint64_t timestamp) const
{
    return true;
}

void pmd_handler::subscribe(std::string sym, size_t max_orders)
{
    helix::order_book ob{sym, 0, max_orders};
    ob.set_state(trading_state::trading);
    auto padding = PMD_INSTRUMENT_LEN - sym.size();
    if (padding > 0) {
        sym.insert(sym.size(), padding, ' ');
    }
    _symbols.insert(sym);
    _order_book_id_map.emplace(sym, std::move(ob));
}

void pmd_handler::register_callback(event_callback callback)
{
    _process_event = callback;
}

size_t pmd_handler::process_packet(const net::packet_view& packet, bool sync)
{
    auto* msg = packet.cast<pmd_message>();
    switch (msg->MessageType) {
    case 'V': return process_msg<pmd_version>(packet, sync);
    case 'S': return process_msg<pmd_second>(packet, sync);
    case 'A': return process_msg<pmd_order_added>(packet, sync);
    case 'E': return process_msg<pmd_order_executed>(packet, sync);
    case 'X': return process_msg<pmd_order_canceled>(packet, sync);
    case 'D': return process_msg<pmd_order_deleted>(packet, sync);
    case 'B': return process_msg<pmd_broken_trade>(packet, sync);
    default:  throw unknown_message_type("unknown type: " + std::string(1, msg->MessageType));
    }
}

template<typename T>
size_t pmd_handler::process_msg(const net::packet_view& packet, bool sync)
{
    process_msg(packet.cast<T>(), sync);
    return sizeof(T);
}

void pmd_handler::process_msg(const pmd_version* m, bool sync)
{
}

void pmd_handler::process_msg(const pmd_second* m, bool sync)
{
    _seconds = be32toh(m->Second);
}

void pmd_handler::process_msg(const pmd_order_added* m, bool sync)
{
    std::string symbol{m->Instrument, PMD_INSTRUMENT_LEN};
    auto it = _order_book_id_map.find(symbol);
    if (it != _order_book_id_map.end()) {
        auto& ob = it->second;
        uint64_t order_id  = be64toh(m->OrderNumber);
        uint64_t price     = be32toh(m->Price);
        uint32_t quantity  = be32toh(m->Quantity);
        auto     side      = pmd_side(m->Side);
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        order o{order_id, price, quantity, side, timestamp};
        ob.add(std::move(o));
        ob.set_timestamp(timestamp);
        _order_id_map.insert({order_id, ob});
        if (sync) {
            _process_event(make_ob_event(ob.symbol(), timestamp, &ob));
        }
    }
}

void pmd_handler::process_msg(const pmd_order_executed* m, bool sync)
{
    uint64_t order_id = be64toh(m->OrderNumber);
    auto it = _order_id_map.find(order_id);
    if (it != _order_id_map.end()) {
        auto& ob = it->second;
        uint32_t quantity  = be32toh(m->Quantity);
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        auto result = ob.execute(order_id, quantity);
        ob.set_timestamp(timestamp);
        trade t{timestamp, result.price, quantity, pmd_trade_sign(result.side)};
        if (sync) {
            _process_event(make_event(ob.symbol(), timestamp, &ob, &t, sweep_event(result)));
        }
    }
}

void pmd_handler::process_msg(const pmd_order_canceled* m, bool sync)
{
    uint64_t order_id = be64toh(m->OrderNumber);
    auto it = _order_id_map.find(order_id);
    if (it != _order_id_map.end()) {
        auto& ob = it->second;
        uint32_t quantity  = be32toh(m->CanceledQuantity);
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        ob.cancel(order_id, quantity);
        ob.set_timestamp(timestamp);
        if (sync) {
            _process_event(make_ob_event(ob.symbol(), timestamp, &ob));
        }
    }
}

void pmd_handler::process_msg(const pmd_order_deleted* m, bool sync)
{
    uint64_t order_id = be64toh(m->OrderNumber);
    auto it = _order_id_map.find(order_id);
    if (it != _order_id_map.end()) {
        auto& ob = it->second;
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        ob.remove(order_id);
        ob.set_timestamp(timestamp);
        if (sync) {
            _process_event(make_ob_event(ob.symbol(), timestamp, &ob));
        }
    }
}

void pmd_handler::process_msg(const pmd_broken_trade* m, bool sync)
{
}

event_mask pmd_handler::sweep_event(const execution& e) const
{
    if (e.remaining > 0) {
        return 0;
    }
    return ev_sweep;
}

uint64_t pmd_handler::to_timestamp(uint64_t nanoseconds) const
{
    return _seconds * 1000 + nanoseconds / 1000000;
}

}

}
<commit_msg>parity/pmd_handler: Remove redundant includes<commit_after>#include "helix/parity/pmd_handler.hh"

#include "helix/compat/endian.h"
#include "helix/order_book.hh"

using namespace std;

namespace helix {

namespace parity {

static side_type pmd_side(char c)
{
    switch (c) {
    case 'B': return side_type::buy;
    case 'S': return side_type::sell;
    default:  throw invalid_argument(string("invalid argument: ") + to_string(c));
    }
}

trade_sign pmd_trade_sign(side_type s)
{
    switch (s) {
    case side_type::buy:  return trade_sign::seller_initiated;
    case side_type::sell: return trade_sign::buyer_initiated;
    default:              throw invalid_argument(string("invalid argument"));
    }
}

pmd_handler::pmd_handler()
{
}

bool pmd_handler::is_rth_timestamp(uint64_t timestamp) const
{
    return true;
}

void pmd_handler::subscribe(std::string sym, size_t max_orders)
{
    helix::order_book ob{sym, 0, max_orders};
    ob.set_state(trading_state::trading);
    auto padding = PMD_INSTRUMENT_LEN - sym.size();
    if (padding > 0) {
        sym.insert(sym.size(), padding, ' ');
    }
    _symbols.insert(sym);
    _order_book_id_map.emplace(sym, std::move(ob));
}

void pmd_handler::register_callback(event_callback callback)
{
    _process_event = callback;
}

size_t pmd_handler::process_packet(const net::packet_view& packet, bool sync)
{
    auto* msg = packet.cast<pmd_message>();
    switch (msg->MessageType) {
    case 'V': return process_msg<pmd_version>(packet, sync);
    case 'S': return process_msg<pmd_second>(packet, sync);
    case 'A': return process_msg<pmd_order_added>(packet, sync);
    case 'E': return process_msg<pmd_order_executed>(packet, sync);
    case 'X': return process_msg<pmd_order_canceled>(packet, sync);
    case 'D': return process_msg<pmd_order_deleted>(packet, sync);
    case 'B': return process_msg<pmd_broken_trade>(packet, sync);
    default:  throw unknown_message_type("unknown type: " + std::string(1, msg->MessageType));
    }
}

template<typename T>
size_t pmd_handler::process_msg(const net::packet_view& packet, bool sync)
{
    process_msg(packet.cast<T>(), sync);
    return sizeof(T);
}

void pmd_handler::process_msg(const pmd_version* m, bool sync)
{
}

void pmd_handler::process_msg(const pmd_second* m, bool sync)
{
    _seconds = be32toh(m->Second);
}

void pmd_handler::process_msg(const pmd_order_added* m, bool sync)
{
    std::string symbol{m->Instrument, PMD_INSTRUMENT_LEN};
    auto it = _order_book_id_map.find(symbol);
    if (it != _order_book_id_map.end()) {
        auto& ob = it->second;
        uint64_t order_id  = be64toh(m->OrderNumber);
        uint64_t price     = be32toh(m->Price);
        uint32_t quantity  = be32toh(m->Quantity);
        auto     side      = pmd_side(m->Side);
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        order o{order_id, price, quantity, side, timestamp};
        ob.add(std::move(o));
        ob.set_timestamp(timestamp);
        _order_id_map.insert({order_id, ob});
        if (sync) {
            _process_event(make_ob_event(ob.symbol(), timestamp, &ob));
        }
    }
}

void pmd_handler::process_msg(const pmd_order_executed* m, bool sync)
{
    uint64_t order_id = be64toh(m->OrderNumber);
    auto it = _order_id_map.find(order_id);
    if (it != _order_id_map.end()) {
        auto& ob = it->second;
        uint32_t quantity  = be32toh(m->Quantity);
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        auto result = ob.execute(order_id, quantity);
        ob.set_timestamp(timestamp);
        trade t{timestamp, result.price, quantity, pmd_trade_sign(result.side)};
        if (sync) {
            _process_event(make_event(ob.symbol(), timestamp, &ob, &t, sweep_event(result)));
        }
    }
}

void pmd_handler::process_msg(const pmd_order_canceled* m, bool sync)
{
    uint64_t order_id = be64toh(m->OrderNumber);
    auto it = _order_id_map.find(order_id);
    if (it != _order_id_map.end()) {
        auto& ob = it->second;
        uint32_t quantity  = be32toh(m->CanceledQuantity);
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        ob.cancel(order_id, quantity);
        ob.set_timestamp(timestamp);
        if (sync) {
            _process_event(make_ob_event(ob.symbol(), timestamp, &ob));
        }
    }
}

void pmd_handler::process_msg(const pmd_order_deleted* m, bool sync)
{
    uint64_t order_id = be64toh(m->OrderNumber);
    auto it = _order_id_map.find(order_id);
    if (it != _order_id_map.end()) {
        auto& ob = it->second;
        uint64_t timestamp = to_timestamp(be32toh(m->Timestamp));
        ob.remove(order_id);
        ob.set_timestamp(timestamp);
        if (sync) {
            _process_event(make_ob_event(ob.symbol(), timestamp, &ob));
        }
    }
}

void pmd_handler::process_msg(const pmd_broken_trade* m, bool sync)
{
}

event_mask pmd_handler::sweep_event(const execution& e) const
{
    if (e.remaining > 0) {
        return 0;
    }
    return ev_sweep;
}

uint64_t pmd_handler::to_timestamp(uint64_t nanoseconds) const
{
    return _seconds * 1000 + nanoseconds / 1000000;
}

}

}
<|endoftext|>


<commit_before>#include <Element.h>
#include <FWPlatform.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Command.h>
#include <FWApplication.h>

#include <SysEvent.h>
#include <OpenGLInitEvent.h>

#include <cassert>

using namespace std;

void
Element::initialize(FWPlatform * _platform) {
  assert(_platform);
  if (_platform) {
    platform = _platform;
    internal_id = platform->getNextInternalId();
  }
}

void
Element::initializeChildren() {
  if (isInitialized()) {
    for (auto & c : getChildren()){
      c->initialize(platform);
      c->initializeChildren();
    }
  }
}

void
Element::sendCommand(const Command & command){
  assert(this != platform);
  assert(platform);
  platform->sendCommand2(command);
}

Element &
Element::addChild(const std::string & text) {
  return addChild(make_shared<TextLabel>(text));
}

LinearLayout &
Element::addHorizontalLayout() {
  auto l = make_shared<LinearLayout>(FW_HORIZONTAL);
  addChild(l);
  return *l;
}

LinearLayout &
Element::addVerticalLayout() {
  auto l = make_shared<LinearLayout>(FW_VERTICAL);
  addChild(l);
  return *l;
}

void
Element::onEvent(Event & ev) {
  if (!ev.isHandled()) {
    if (ev.isBroadcast()) {
      for (auto & c : getChildren()){
	ev.dispatch(*c);
      }
    } else if (parent) {
      ev.dispatch(*parent);
    }
  }
}

void
Element::showMessageDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
}

std::string
Element::showInputDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
  return platform->getModalResultText();
}

FWApplication &
Element::getApplication() {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<FWApplication&>(*p);
}

const FWApplication &
Element::getApplication() const {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<const FWApplication&>(*p);
}

<commit_msg>add assertions<commit_after>#include <Element.h>
#include <FWPlatform.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Command.h>
#include <FWApplication.h>

#include <cassert>

using namespace std;

void
Element::initialize(FWPlatform * _platform) {
  assert(_platform);
  if (_platform) {
    platform = _platform;
    internal_id = platform->getNextInternalId();
  }
  assert(isInitialized());
}

void
Element::initializeChildren() {
  assert(isInitialized());
  if (isInitialized()) {
    for (auto & c : getChildren()) {
      c->initialize(platform);
      c->initializeChildren();
    }
  }
}

void
Element::sendCommand(const Command & command) {
  assert(platform);
  platform->sendCommand2(command);
}

Element &
Element::addChild(const std::string & text) {
  return addChild(make_shared<TextLabel>(text));
}

LinearLayout &
Element::addHorizontalLayout() {
  auto l = make_shared<LinearLayout>(FW_HORIZONTAL);
  addChild(l);
  return *l;
}

LinearLayout &
Element::addVerticalLayout() {
  auto l = make_shared<LinearLayout>(FW_VERTICAL);
  addChild(l);
  return *l;
}

void
Element::onEvent(Event & ev) {
  if (!ev.isHandled()) {
    if (ev.isBroadcast()) {
      for (auto & c : getChildren()){
	ev.dispatch(*c);
      }
    } else if (parent) {
      ev.dispatch(*parent);
    }
  }
}

void
Element::showMessageDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
}

std::string
Element::showInputDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
  return platform->getModalResultText();
}

FWApplication &
Element::getApplication() {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<FWApplication&>(*p);
}

const FWApplication &
Element::getApplication() const {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<const FWApplication&>(*p);
}

<|endoftext|>


<commit_before>#include <Element.h>
#include <FWPlatform.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Command.h>
#include <FWApplication.h>

#include <cassert>

using namespace std;

void
Element::initialize(FWPlatform * _platform) {
  assert(_platform);
  if (_platform) {
    platform = _platform;
    internal_id = platform->getNextInternalId();
  }
  assert(isInitialized());
}

void
Element::initializeChildren() {
  assert(isInitialized());
  if (isInitialized()) {
    for (auto & c : getChildren()) {
      c->initialize(platform);
      c->initializeChildren();
    }
  }
}

void
Element::sendCommand(const Command & command) {
  assert(platform);
  platform->sendCommand2(command);
}

Element &
Element::addChild(const std::string & text) {
  return addChild(make_shared<TextLabel>(text));
}

LinearLayout &
Element::addHorizontalLayout() {
  auto l = make_shared<LinearLayout>(FW_HORIZONTAL);
  addChild(l);
  return *l;
}

LinearLayout &
Element::addVerticalLayout() {
  auto l = make_shared<LinearLayout>(FW_VERTICAL);
  addChild(l);
  return *l;
}

void
Element::onEvent(Event & ev) {
  if (!ev.isHandled()) {
    if (ev.isBroadcast()) {
      for (auto & c : getChildren()){
	ev.dispatch(*c);
      }
    } else if (parent) {
      ev.dispatch(*parent);
    }
  }
}

void
Element::showMessageDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
}

std::string
Element::showInputDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
  return platform->getModalResultText();
}

FWApplication &
Element::getApplication() {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<FWApplication&>(*p);
}

const FWApplication &
Element::getApplication() const {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<const FWApplication&>(*p);
}

<commit_msg>add style() method<commit_after>#include <Element.h>
#include <FWPlatform.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Command.h>
#include <FWApplication.h>

#include <cassert>

using namespace std;

void
Element::initialize(FWPlatform * _platform) {
  assert(_platform);
  if (_platform) {
    platform = _platform;
    internal_id = platform->getNextInternalId();
  }
  assert(isInitialized());
}

void
Element::initializeChildren() {
  assert(isInitialized());
  if (isInitialized()) {
    for (auto & c : getChildren()) {
      c->initialize(platform);
      c->initializeChildren();
    }
  }
}

void
Element::style(const std::string & key, const std::string & value) {
  Command c(Command::SET_STYLE, getInternalId());
  c.setTextValue(key);
  c.setTextValue2(value);
  sendCommand(c);
}

void
Element::sendCommand(const Command & command) {
  assert(platform);
  platform->sendCommand2(command);
}

Element &
Element::addChild(const std::string & text) {
  return addChild(make_shared<TextLabel>(text));
}

LinearLayout &
Element::addHorizontalLayout() {
  auto l = make_shared<LinearLayout>(FW_HORIZONTAL);
  addChild(l);
  return *l;
}

LinearLayout &
Element::addVerticalLayout() {
  auto l = make_shared<LinearLayout>(FW_VERTICAL);
  addChild(l);
  return *l;
}

void
Element::onEvent(Event & ev) {
  if (!ev.isHandled()) {
    if (ev.isBroadcast()) {
      for (auto & c : getChildren()){
	ev.dispatch(*c);
      }
    } else if (parent) {
      ev.dispatch(*parent);
    }
  }
}

void
Element::showMessageDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
}

std::string
Element::showInputDialog(const std::string & title, const std::string & text) {
  Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId());
  c.setTextValue(title);
  c.setTextValue2(text);
  sendCommand(c);
  return platform->getModalResultText();
}

FWApplication &
Element::getApplication() {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<FWApplication&>(*p);
}

const FWApplication &
Element::getApplication() const {
  auto p = getPlatform().getFirstChild();
  return dynamic_cast<const FWApplication&>(*p);
}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.2.8.2  2002/07/24 10:09:31  alibrary
Updating VirtualMC

Revision 1.2.8.1  2002/06/10 15:28:58  hristov
Merged with v3-08-02

Revision 1.4  2002/03/28 15:44:55  cblume
Remove const from GetIndex()

Revision 1.3  2002/03/28 14:59:07  cblume
Coding conventions

Revision 1.4  2002/03/28 15:44:55  cblume
Remove const from GetIndex()

Revision 1.3  2002/03/28 14:59:07  cblume
Coding conventions

Revision 1.2  2001/11/07 11:04:22  hristov
Minor corrections needed on Sun (arrays with undefined size created by new, inline decration removed when the body was hot in the header file)

Revision 1.1  2001/11/06 17:19:41  cblume
Add detailed geometry and simple simulator

*/

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//   The TRD particle identification class                                   //
//                                                                           //
//   Its main purposes are:                                                  //
//      - Creation and bookkeeping of the propability distributions          //
//      - Assignment of a e/pi propability to a given track based on         //
//        the LQ method                                                      //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <math.h>

#include <TROOT.h>
#include <TH1.h>
#include <TObjArray.h>
#include <TTree.h>
#include <TFile.h>
#include <TParticle.h>

#include "AliRun.h"
#include "AliTRD.h"
#include "AliTRDpidLQ.h"
#include "AliTRDcluster.h"
#include "AliTRDtrack.h"
#include "AliTRDtracker.h"
#include "AliTRDgeometry.h"

ClassImp(AliTRDpidLQ)

//_____________________________________________________________________________
AliTRDpidLQ::AliTRDpidLQ():AliTRDpid()
{
  //
  // AliTRDpidLQ default constructor
  //

  fNMom   = 0;
  fMinMom = 0;
  fMaxMom = 0;
  fWidMom = 0;

  fNLh    = 0;
  fMinLh  = 0;
  fMaxLh  = 0;

  fHist   = NULL;

  fChargeMin   = 0;
  fNClusterMin = 0;

}

//_____________________________________________________________________________
AliTRDpidLQ::AliTRDpidLQ(const char* name, const char* title)
            :AliTRDpid(name,title)
{
  //
  // AliTRDpidLQ constructor
  //

  fNMom   = 0;
  fMinMom = 0;
  fMaxMom = 0;
  fWidMom = 0;

  fNLh    = 0;
  fMinLh  = 0;
  fMaxLh  = 0;

  fHist   = NULL;

  Init();

}

//_____________________________________________________________________________
AliTRDpidLQ::AliTRDpidLQ(const AliTRDpidLQ &p)
{
  //
  // AliTRDpidLQ copy constructor
  //

  ((AliTRDpidLQ &) p).Copy(*this);

}

//_____________________________________________________________________________
AliTRDpidLQ::~AliTRDpidLQ()
{
  //
  // AliTRDpidLQ destructor
  //

  if (fHist) {
    fHist->Delete();
    delete fHist;
  }

}

//_____________________________________________________________________________
AliTRDpidLQ &AliTRDpidLQ::operator=(const AliTRDpidLQ &p)
{
  //
  // Assignment operator
  //

  if (this != &p) ((AliTRDpidLQ &) p).Copy(*this);
  return *this;

}

//_____________________________________________________________________________
void AliTRDpidLQ::Copy(TObject &p)
{
  //
  // Copy function
  //

  fHist->Copy(*((AliTRDpidLQ &) p).fHist);

  ((AliTRDpidLQ &) p).fNMom        = fNMom;
  ((AliTRDpidLQ &) p).fMinMom      = fMinMom;
  ((AliTRDpidLQ &) p).fMaxMom      = fMaxMom;
  ((AliTRDpidLQ &) p).fWidMom      = fWidMom;
  ((AliTRDpidLQ &) p).fChargeMin   = fChargeMin;
  ((AliTRDpidLQ &) p).fNClusterMin = fNClusterMin;
  ((AliTRDpidLQ &) p).fNLh         = fNLh;
  ((AliTRDpidLQ &) p).fMinLh       = fMinLh;
  ((AliTRDpidLQ &) p).fMaxLh       = fMaxLh;

  AliTRDpid::Copy(p);

}

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::Init()
{
  //
  // Initializes the PID object
  //

  fChargeMin   = 0.0;
  fNClusterMin = 10;

  fNLh         = 100;
  fMinLh       =   0.0;
  fMaxLh       = 500.0;

  return kTRUE;

}

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::AssignLikelihood(AliTRDtrack *t)
{
  //
  // Assigns the e / pi likelihood to a given track
  //

  const Int_t kNpla = AliTRDgeometry::Nplan();
  Float_t * charge = new Float_t[kNpla];
  Int_t   * nCluster = new Int_t[kNpla];

  Float_t  lhPi = 0;
  Float_t  lhEl = 0;

  Double_t pPi  = 1;
  Double_t pEl  = 1;
  Double_t pSum = 0;

  Int_t   indexEl;
  Int_t   indexPi;
  TH1F   *hTmpEl;
  TH1F   *hTmpPi;

  t->SetLikelihoodElectron(-1.);
  if (isnan(t->GetP())) return kFALSE;
  Float_t mom = t->GetP();

  // Calculate the total charge in each plane
  if (!SumCharge(t,charge,nCluster)) return kFALSE;

  indexEl = GetIndex(mom,kElectron);
  indexPi = GetIndex(mom,kPion);
  if ((indexEl > -1) && (indexPi > -1)) {
    hTmpEl = (TH1F *) fHist->UncheckedAt(indexEl);
    hTmpPi = (TH1F *) fHist->UncheckedAt(indexPi);
    for (Int_t ipla = 0; ipla < kNpla; ipla++) {
      Float_t chargePlane   = charge[ipla];
      Int_t   nClusterPlane = nCluster[ipla];
      if ((chargePlane   >   fChargeMin) &&
          (nClusterPlane > fNClusterMin)){
        Float_t chargeNorm = chargePlane / ((Float_t) nClusterPlane);
        if (chargeNorm < fMaxLh) {
          Int_t   ibinEl     = hTmpEl->FindBin(chargeNorm);
          Float_t pElPlane   = hTmpEl->GetBinContent(ibinEl);
          if (pElPlane > 0) {
            pEl  = pEl * pElPlane;
          }
          Int_t   ibinPi     = hTmpPi->FindBin(chargeNorm);
          Float_t pPiPlane   = hTmpPi->GetBinContent(ibinPi);
          if (pPiPlane > 0) {
            pPi  = pPi * pPiPlane;
          }
//           printf("          ipla = %d, nCluster = %d, charge = %f\n"
//                  ,ipla,nClusterPlane,chargeNorm);
//           printf("electron: pElPlane = %f, ibinEl = %d, pEl = %f\n"
// 	         ,pElPlane,ibinEl,pEl);
//           printf("    pion: pPiPlane = %f, ibinPi = %d, pPi = %f\n"
// 	         ,pPiPlane,ibinPi,pPi);
	}
      }
    }
  }
  else {
    delete [] charge;
    delete [] nCluster;
    return kTRUE;
  }

  pSum = pEl + pPi;
  if (pSum <= 0) {
    delete [] charge;
    delete [] nCluster;
    return kFALSE;
  }
  lhEl = pEl / pSum;
  lhPi = pPi / pSum;

//   printf("---- mom = %f, lhEl = %f, lhPi = %f\n",mom,lhEl,lhPi);

  // Assign the likelihoods
  t->SetLikelihoodElectron(lhEl);

  delete [] charge;
  delete [] nCluster;
  return kTRUE;

}

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::CreateHistograms(const Int_t   nmom
                                   , const Float_t minmom
                                   , const Float_t maxmom)
{
  //
  // Creates the histograms
  //

  Int_t imom;
  Int_t ipid;

  fNMom   = nmom;
  fMinMom = minmom;
  fMaxMom = maxmom;
  fWidMom = (maxmom - minmom) / ((Float_t) nmom);

  fHist = new TObjArray(kNpid * nmom);
  for (imom = 0; imom < nmom;  imom++) {
    for (ipid = 0; ipid < kNpid; ipid++) {

      Int_t index = GetIndex(imom,ipid);
      Char_t name[10];
      Char_t title[80];
      sprintf(name ,"hQ%03d",index);
      if (ipid == kElectron) {
        sprintf(title,"Q electron p-bin %03d",imom);
      }
      else {
        sprintf(title,"Q pion p-bin %03d",imom);
      }
      TH1F *hTmp = new TH1F(name,title,fNLh,fMinLh,fMaxLh);
      fHist->AddAt(hTmp,index);

    }
  }

  return kTRUE;

}

// //_____________________________________________________________________________
// Bool_t AliTRDpidLQ::FillSpectra(const AliTRDtrack *t)
// {
//   //
//   // Fills the energy loss distributions with track <t>.
//   //

//   Bool_t status = kTRUE;

//   if (isnan(t->GetP())) return kFALSE;

//   Float_t        mom     = t->GetP();
//   Int_t          ipid    = MCpid(t);
//   TH1F          *hTmp    = NULL;
//   AliTRDcluster *cluster = NULL;

//   Int_t index = GetIndex(mom,ipid);
//   if (index > -1) {
//     hTmp = (TH1F *) fHist->UncheckedAt(index);
//     // Loop through all clusters associated to this track
//     Int_t nClus = t->GetNclusters();
//     for (Int_t iClus = 0; iClus < nClus; iClus++) {
//       // Get a cluster
//       Int_t idxClus = t->GetClusterIndex(iClus);
//       if (!(cluster = (AliTRDcluster *) fClusterArray->UncheckedAt(idxClus))) {
//         status = kFALSE;
//         break;
//       }
//       hTmp->Fill(cluster->GetQ());
//     }
//   }

//   return status;

// }

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::FillSpectra(const AliTRDtrack *t)
{
  //
  // Fills the energy loss distributions with track <t>.
  //

  const Int_t kNpla = AliTRDgeometry::Nplan();

  if (isnan(t->GetP())) return kFALSE;

  Float_t * charge = new Float_t[kNpla];
  Int_t   * nCluster = new Int_t[kNpla];
  Float_t mom  = t->GetP();
  Int_t   ipid = MCpid(t);
  TH1F   *hTmp = NULL;

  if (!SumCharge(t,charge,nCluster)) {
    delete [] charge;
    delete [] nCluster;
    return kFALSE;
  }

  Int_t index = GetIndex(mom,ipid);
  if (index > -1) {
    hTmp = (TH1F *) fHist->UncheckedAt(index);
    for (Int_t ipla = 0; ipla < kNpla; ipla++) {
      if ((charge[ipla]   >   fChargeMin) &&
          (nCluster[ipla] > fNClusterMin)){
        hTmp->Fill(charge[ipla] / ((Float_t) nCluster[ipla]));
      }
    }
  }

  delete [] charge;
  delete [] nCluster;
  return kTRUE;

}

//_____________________________________________________________________________
Int_t AliTRDpidLQ::GetIndex(const AliTRDtrack *t)
{
  //
  // Returns the histogram index
  //

  if (isnan(t->GetP())) return -1;
  Float_t mom  = t->GetP();
  Int_t   ipid = MCpid(t);

  return GetIndex(mom,ipid);

}

//_____________________________________________________________________________
Int_t AliTRDpidLQ::GetIndex(const Float_t mom, const Int_t ipid)
{
  //
  // Returns the histogram index
  //

  if ((mom < fMinMom) || (mom > fMaxMom))  return -1;
  Int_t imom = ((Int_t) ((mom - fMinMom) / fWidMom));
  return GetIndex(imom,ipid);

}

//_____________________________________________________________________________
Int_t AliTRDpidLQ::GetIndex(const Int_t imom, const Int_t ipid)
{
  //
  // Returns the histogram index
  //

  if ((ipid < 0) || (ipid >= kNpid)) return -1;
  return imom * kNpid + ipid;

}
<commit_msg>Using TMath functions<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//   The TRD particle identification class                                   //
//                                                                           //
//   Its main purposes are:                                                  //
//      - Creation and bookkeeping of the propability distributions          //
//      - Assignment of a e/pi propability to a given track based on         //
//        the LQ method                                                      //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <math.h>

#include <TROOT.h>
#include <TH1.h>
#include <TObjArray.h>
#include <TTree.h>
#include <TFile.h>
#include <TParticle.h>

#include "AliRun.h"
#include "AliTRD.h"
#include "AliTRDpidLQ.h"
#include "AliTRDcluster.h"
#include "AliTRDtrack.h"
#include "AliTRDtracker.h"
#include "AliTRDgeometry.h"

ClassImp(AliTRDpidLQ)

//_____________________________________________________________________________
AliTRDpidLQ::AliTRDpidLQ():AliTRDpid()
{
  //
  // AliTRDpidLQ default constructor
  //

  fNMom   = 0;
  fMinMom = 0;
  fMaxMom = 0;
  fWidMom = 0;

  fNLh    = 0;
  fMinLh  = 0;
  fMaxLh  = 0;

  fHist   = NULL;

  fChargeMin   = 0;
  fNClusterMin = 0;

}

//_____________________________________________________________________________
AliTRDpidLQ::AliTRDpidLQ(const char* name, const char* title)
            :AliTRDpid(name,title)
{
  //
  // AliTRDpidLQ constructor
  //

  fNMom   = 0;
  fMinMom = 0;
  fMaxMom = 0;
  fWidMom = 0;

  fNLh    = 0;
  fMinLh  = 0;
  fMaxLh  = 0;

  fHist   = NULL;

  Init();

}

//_____________________________________________________________________________
AliTRDpidLQ::AliTRDpidLQ(const AliTRDpidLQ &p)
{
  //
  // AliTRDpidLQ copy constructor
  //

  ((AliTRDpidLQ &) p).Copy(*this);

}

//_____________________________________________________________________________
AliTRDpidLQ::~AliTRDpidLQ()
{
  //
  // AliTRDpidLQ destructor
  //

  if (fHist) {
    fHist->Delete();
    delete fHist;
  }

}

//_____________________________________________________________________________
AliTRDpidLQ &AliTRDpidLQ::operator=(const AliTRDpidLQ &p)
{
  //
  // Assignment operator
  //

  if (this != &p) ((AliTRDpidLQ &) p).Copy(*this);
  return *this;

}

//_____________________________________________________________________________
void AliTRDpidLQ::Copy(TObject &p)
{
  //
  // Copy function
  //

  fHist->Copy(*((AliTRDpidLQ &) p).fHist);

  ((AliTRDpidLQ &) p).fNMom        = fNMom;
  ((AliTRDpidLQ &) p).fMinMom      = fMinMom;
  ((AliTRDpidLQ &) p).fMaxMom      = fMaxMom;
  ((AliTRDpidLQ &) p).fWidMom      = fWidMom;
  ((AliTRDpidLQ &) p).fChargeMin   = fChargeMin;
  ((AliTRDpidLQ &) p).fNClusterMin = fNClusterMin;
  ((AliTRDpidLQ &) p).fNLh         = fNLh;
  ((AliTRDpidLQ &) p).fMinLh       = fMinLh;
  ((AliTRDpidLQ &) p).fMaxLh       = fMaxLh;

  AliTRDpid::Copy(p);

}

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::Init()
{
  //
  // Initializes the PID object
  //

  fChargeMin   = 0.0;
  fNClusterMin = 10;

  fNLh         = 100;
  fMinLh       =   0.0;
  fMaxLh       = 500.0;

  return kTRUE;

}

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::AssignLikelihood(AliTRDtrack *t)
{
  //
  // Assigns the e / pi likelihood to a given track
  //

  const Int_t kNpla = AliTRDgeometry::Nplan();
  Float_t * charge = new Float_t[kNpla];
  Int_t   * nCluster = new Int_t[kNpla];

  Float_t  lhPi = 0;
  Float_t  lhEl = 0;

  Double_t pPi  = 1;
  Double_t pEl  = 1;
  Double_t pSum = 0;

  Int_t   indexEl;
  Int_t   indexPi;
  TH1F   *hTmpEl;
  TH1F   *hTmpPi;

  t->SetLikelihoodElectron(-1.);
  if (TMath::IsNaN(t->GetP())) return kFALSE;
  Float_t mom = t->GetP();

  // Calculate the total charge in each plane
  if (!SumCharge(t,charge,nCluster)) return kFALSE;

  indexEl = GetIndex(mom,kElectron);
  indexPi = GetIndex(mom,kPion);
  if ((indexEl > -1) && (indexPi > -1)) {
    hTmpEl = (TH1F *) fHist->UncheckedAt(indexEl);
    hTmpPi = (TH1F *) fHist->UncheckedAt(indexPi);
    for (Int_t ipla = 0; ipla < kNpla; ipla++) {
      Float_t chargePlane   = charge[ipla];
      Int_t   nClusterPlane = nCluster[ipla];
      if ((chargePlane   >   fChargeMin) &&
          (nClusterPlane > fNClusterMin)){
        Float_t chargeNorm = chargePlane / ((Float_t) nClusterPlane);
        if (chargeNorm < fMaxLh) {
          Int_t   ibinEl     = hTmpEl->FindBin(chargeNorm);
          Float_t pElPlane   = hTmpEl->GetBinContent(ibinEl);
          if (pElPlane > 0) {
            pEl  = pEl * pElPlane;
          }
          Int_t   ibinPi     = hTmpPi->FindBin(chargeNorm);
          Float_t pPiPlane   = hTmpPi->GetBinContent(ibinPi);
          if (pPiPlane > 0) {
            pPi  = pPi * pPiPlane;
          }
//           printf("          ipla = %d, nCluster = %d, charge = %f\n"
//                  ,ipla,nClusterPlane,chargeNorm);
//           printf("electron: pElPlane = %f, ibinEl = %d, pEl = %f\n"
// 	         ,pElPlane,ibinEl,pEl);
//           printf("    pion: pPiPlane = %f, ibinPi = %d, pPi = %f\n"
// 	         ,pPiPlane,ibinPi,pPi);
	}
      }
    }
  }
  else {
    delete [] charge;
    delete [] nCluster;
    return kTRUE;
  }

  pSum = pEl + pPi;
  if (pSum <= 0) {
    delete [] charge;
    delete [] nCluster;
    return kFALSE;
  }
  lhEl = pEl / pSum;
  lhPi = pPi / pSum;

//   printf("---- mom = %f, lhEl = %f, lhPi = %f\n",mom,lhEl,lhPi);

  // Assign the likelihoods
  t->SetLikelihoodElectron(lhEl);

  delete [] charge;
  delete [] nCluster;
  return kTRUE;

}

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::CreateHistograms(const Int_t   nmom
                                   , const Float_t minmom
                                   , const Float_t maxmom)
{
  //
  // Creates the histograms
  //

  Int_t imom;
  Int_t ipid;

  fNMom   = nmom;
  fMinMom = minmom;
  fMaxMom = maxmom;
  fWidMom = (maxmom - minmom) / ((Float_t) nmom);

  fHist = new TObjArray(kNpid * nmom);
  for (imom = 0; imom < nmom;  imom++) {
    for (ipid = 0; ipid < kNpid; ipid++) {

      Int_t index = GetIndex(imom,ipid);
      Char_t name[10];
      Char_t title[80];
      sprintf(name ,"hQ%03d",index);
      if (ipid == kElectron) {
        sprintf(title,"Q electron p-bin %03d",imom);
      }
      else {
        sprintf(title,"Q pion p-bin %03d",imom);
      }
      TH1F *hTmp = new TH1F(name,title,fNLh,fMinLh,fMaxLh);
      fHist->AddAt(hTmp,index);

    }
  }

  return kTRUE;

}

// //_____________________________________________________________________________
// Bool_t AliTRDpidLQ::FillSpectra(const AliTRDtrack *t)
// {
//   //
//   // Fills the energy loss distributions with track <t>.
//   //

//   Bool_t status = kTRUE;

//   if (TMath::IsNaN(t->GetP())) return kFALSE;

//   Float_t        mom     = t->GetP();
//   Int_t          ipid    = MCpid(t);
//   TH1F          *hTmp    = NULL;
//   AliTRDcluster *cluster = NULL;

//   Int_t index = GetIndex(mom,ipid);
//   if (index > -1) {
//     hTmp = (TH1F *) fHist->UncheckedAt(index);
//     // Loop through all clusters associated to this track
//     Int_t nClus = t->GetNclusters();
//     for (Int_t iClus = 0; iClus < nClus; iClus++) {
//       // Get a cluster
//       Int_t idxClus = t->GetClusterIndex(iClus);
//       if (!(cluster = (AliTRDcluster *) fClusterArray->UncheckedAt(idxClus))) {
//         status = kFALSE;
//         break;
//       }
//       hTmp->Fill(cluster->GetQ());
//     }
//   }

//   return status;

// }

//_____________________________________________________________________________
Bool_t AliTRDpidLQ::FillSpectra(const AliTRDtrack *t)
{
  //
  // Fills the energy loss distributions with track <t>.
  //

  const Int_t kNpla = AliTRDgeometry::Nplan();

  if (TMath::IsNaN(t->GetP())) return kFALSE;

  Float_t * charge = new Float_t[kNpla];
  Int_t   * nCluster = new Int_t[kNpla];
  Float_t mom  = t->GetP();
  Int_t   ipid = MCpid(t);
  TH1F   *hTmp = NULL;

  if (!SumCharge(t,charge,nCluster)) {
    delete [] charge;
    delete [] nCluster;
    return kFALSE;
  }

  Int_t index = GetIndex(mom,ipid);
  if (index > -1) {
    hTmp = (TH1F *) fHist->UncheckedAt(index);
    for (Int_t ipla = 0; ipla < kNpla; ipla++) {
      if ((charge[ipla]   >   fChargeMin) &&
          (nCluster[ipla] > fNClusterMin)){
        hTmp->Fill(charge[ipla] / ((Float_t) nCluster[ipla]));
      }
    }
  }

  delete [] charge;
  delete [] nCluster;
  return kTRUE;

}

//_____________________________________________________________________________
Int_t AliTRDpidLQ::GetIndex(const AliTRDtrack *t)
{
  //
  // Returns the histogram index
  //

  if (TMath::IsNaN(t->GetP())) return -1;
  Float_t mom  = t->GetP();
  Int_t   ipid = MCpid(t);

  return GetIndex(mom,ipid);

}

//_____________________________________________________________________________
Int_t AliTRDpidLQ::GetIndex(const Float_t mom, const Int_t ipid)
{
  //
  // Returns the histogram index
  //

  if ((mom < fMinMom) || (mom > fMaxMom))  return -1;
  Int_t imom = ((Int_t) ((mom - fMinMom) / fWidMom));
  return GetIndex(imom,ipid);

}

//_____________________________________________________________________________
Int_t AliTRDpidLQ::GetIndex(const Int_t imom, const Int_t ipid)
{
  //
  // Returns the histogram index
  //

  if ((ipid < 0) || (ipid >= kNpid)) return -1;
  return imom * kNpid + ipid;

}
<|endoftext|>


<commit_before>//
// OCCAM
//
// Copyright (c) 2019, SRI International
//
//  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of SRI International nor the names of its contributors may
//   be used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

/**
 * Force the inlining of special functions.
 *
 * The inlining of functions is performed by opt. Here, we force the
 * inlining of some functions even if the function is marked as
 * noninline, nonopt or even if the user disabled inlining. Currently,
 * we inline a function if it is either:
 *
 * 1) created by devirtualization, or
 *
 * 2) created by specialization.
 **/

#include "llvm/Pass.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"

#include "utils/Inliner.h"

using namespace llvm;
using namespace previrt;

static cl::opt<bool>
InlineBounceFunctions("Pinline-bounce-functions",
	       cl::init(false),
	       cl::Hidden,
	       cl::desc("Inline bounce functions generated by devirtualization"));

static cl::opt<bool>
InlineSpecializedFunctions("Pinline-specialized-functions",
	       cl::init(false),
	       cl::Hidden,
	       cl::desc("Inline specialized functions"));

static const StringRef bounce_prefix = "__occam.bounce";
static const StringRef spec_prefix = "__occam_spec.";

namespace previrt {
class InlinerPass : public llvm::ModulePass {
public:
  static char ID;

  InlinerPass(): ModulePass(ID) {}

  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
    if (!InlineBounceFunctions && !InlineSpecializedFunctions) {
      AU.setPreservesAll();
    } else {
    // TODO: update the call graph so the pass manager does not
    // re-calculate it again.
    }
  }

  virtual StringRef getPassName() const override {
    return "Force inlining of special functions";
  }

  virtual bool runOnModule(llvm::Module &M) override {
    if (!InlineBounceFunctions && !InlineSpecializedFunctions) {
      return false;
    } else {
      SmallPtrSet<Function*, 8> ToInline;
      for (auto &F: M) {
	if (!F.isDeclaration()) {
	  if (InlineBounceFunctions && F.getName().startswith(bounce_prefix)) {
	    ToInline.insert(&F);
	  } else if (InlineSpecializedFunctions && F.getName().startswith(spec_prefix)) {
	    ToInline.insert(&F);
	  }
	}
      }
      if (ToInline.empty()) {
	return false;
      } else {
	utils::inlineOnly(M, ToInline);
	return true;
      }
    }
  }
};

char InlinerPass::ID = 0;

} // end namespace previrt

static RegisterPass<previrt::InlinerPass>
X("Pinliner", "Force inlining of special functions", false, false);
<commit_msg>Added missing CommandLine.h include<commit_after>//
// OCCAM
//
// Copyright (c) 2019, SRI International
//
//  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of SRI International nor the names of its contributors may
//   be used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

/**
 * Force the inlining of special functions.
 *
 * The inlining of functions is performed by opt. Here, we force the
 * inlining of some functions even if the function is marked as
 * noninline, nonopt or even if the user disabled inlining. Currently,
 * we inline a function if it is either:
 *
 * 1) created by devirtualization, or
 *
 * 2) created by specialization.
 **/

#include "llvm/Pass.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"

#include "utils/Inliner.h"

using namespace llvm;
using namespace previrt;

static cl::opt<bool>
InlineBounceFunctions("Pinline-bounce-functions",
	       cl::init(false),
	       cl::Hidden,
	       cl::desc("Inline bounce functions generated by devirtualization"));

static cl::opt<bool>
InlineSpecializedFunctions("Pinline-specialized-functions",
	       cl::init(false),
	       cl::Hidden,
	       cl::desc("Inline specialized functions"));

static const StringRef bounce_prefix = "__occam.bounce";
static const StringRef spec_prefix = "__occam_spec.";

namespace previrt {
class InlinerPass : public llvm::ModulePass {
public:
  static char ID;

  InlinerPass(): ModulePass(ID) {}

  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
    if (!InlineBounceFunctions && !InlineSpecializedFunctions) {
      AU.setPreservesAll();
    } else {
    // TODO: update the call graph so the pass manager does not
    // re-calculate it again.
    }
  }

  virtual StringRef getPassName() const override {
    return "Force inlining of special functions";
  }

  virtual bool runOnModule(llvm::Module &M) override {
    if (!InlineBounceFunctions && !InlineSpecializedFunctions) {
      return false;
    } else {
      SmallPtrSet<Function*, 8> ToInline;
      for (auto &F: M) {
	if (!F.isDeclaration()) {
	  if (InlineBounceFunctions && F.getName().startswith(bounce_prefix)) {
	    ToInline.insert(&F);
	  } else if (InlineSpecializedFunctions && F.getName().startswith(spec_prefix)) {
	    ToInline.insert(&F);
	  }
	}
      }
      if (ToInline.empty()) {
	return false;
      } else {
	utils::inlineOnly(M, ToInline);
	return true;
      }
    }
  }
};

char InlinerPass::ID = 0;

} // end namespace previrt

static RegisterPass<previrt::InlinerPass>
X("Pinliner", "Force inlining of special functions", false, false);
<|endoftext|>