<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: customshapeproperties.cxx,v $
 * $Revision: 1.5 $
 *
 * 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.
 *
 ************************************************************************/

#include <comphelper/processfactory.hxx>
#include "oox/drawingml/customshapeproperties.hxx"
#include "oox/helper/helper.hxx"
#include "oox/helper/propertyset.hxx"
#include "oox/core/namespaces.hxx"
#include "tokens.hxx"
#include <tools/solar.h>
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/graphic/XGraphicTransformer.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/drawing/XEnhancedCustomShapeDefaulter.hpp>

using rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::graphic;
using namespace ::com::sun::star::drawing;

namespace oox { namespace drawingml {

CustomShapeProperties::CustomShapeProperties()
{
}
CustomShapeProperties::~CustomShapeProperties()
{
}

void CustomShapeProperties::apply( const CustomShapePropertiesPtr& /* rSourceCustomShapeProperties */ )
{
    // not sure if this needs to be implemented
}

void CustomShapeProperties::pushToPropSet( const ::oox::core::XmlFilterBase& /* rFilterBase */,
    const Reference < XPropertySet >& xPropSet, const Reference < XShape > & xShape ) const
{
    const OUString sType = CREATE_OUSTRING( "Type" );
    if ( maShapePresetType.getLength() )
    {
        //const uno::Reference < drawing::XShape > xShape( xPropSet, UNO_QUERY );
        Reference< drawing::XEnhancedCustomShapeDefaulter > xDefaulter( xShape, UNO_QUERY );
        if( xDefaulter.is() )
            xDefaulter->createCustomShapeDefaults( maShapePresetType );

        const rtl::OUString sCustomShapeGeometry( RTL_CONSTASCII_USTRINGPARAM( "CustomShapeGeometry" ) );
        uno::Any aGeoPropSet = xPropSet->getPropertyValue( sCustomShapeGeometry );
        uno::Sequence< beans::PropertyValue > aGeoPropSeq;
        if ( aGeoPropSet >>= aGeoPropSeq )
        {
            sal_Int32 i, nCount = aGeoPropSeq.getLength();
            for ( i = 0; i < nCount; i++ )
            {
                const rtl::OUString sAdjustmentValues( RTL_CONSTASCII_USTRINGPARAM( "AdjustmentValues" ) );
                if ( aGeoPropSeq[ i ].Name.equals( sAdjustmentValues ) )
                {
                    uno::Sequence< com::sun::star::drawing::EnhancedCustomShapeAdjustmentValue > aAdjustmentSeq;
                    if ( aGeoPropSeq[ i ].Value >>= aAdjustmentSeq )
                    {
                        sal_uInt32 j, nHighest = 0;
                        for( j = 0; j < maAdjustmentValues.size(); j++ )
                        {
                            const rtl::OUString& rS( maAdjustmentValues[ j ].maName );
                            if ( rS.getLength() > 3 )
                            {
                                sal_uInt32 nVal = rS.copy( 3 ).toInt32();
                                if ( ( nVal < 10 ) && ( nVal > nHighest ) )
                                    nHighest = nVal;
                            }
                        }
                        if ( nHighest > static_cast< sal_uInt32 >( aAdjustmentSeq.getLength() ) )
                            aAdjustmentSeq.realloc( nHighest );

                        for ( j = 0; j < maAdjustmentValues.size(); j++ )
                        {
                            sal_uInt32 nVal = maAdjustmentValues[ j ].maName.copy( 3 ).toInt32();
                            if ( nVal-- )
                            {
                                double fNewAdj = getValue( maAdjustmentValues, nVal );
                                aAdjustmentSeq[ nVal ].State = beans::PropertyState_DIRECT_VALUE;
                                aAdjustmentSeq[ nVal ].Value <<= fNewAdj;
                            }
                        }
                        aGeoPropSeq[ i ].Value <<= aAdjustmentSeq;
                        xPropSet->setPropertyValue( sCustomShapeGeometry, Any( aGeoPropSeq ) );
                    }
                }
                else if ( aGeoPropSeq[ i ].Name.equals( sType ) )
                {
                    aGeoPropSeq[ i ].Value <<= maShapePresetType;
                }
            }
        }
    }
    else
    {
        PropertyMap aPropertyMap;
        OUString sShapeType( CREATE_OUSTRING( "non-primitive" ) );
        aPropertyMap[ sType ] <<= sShapeType;

        // converting the vector to a sequence
        Sequence< PropertyValue > aSeq;
        aPropertyMap.makeSequence( aSeq );
        static const rtl::OUString sCustomShapeGeometry( RTL_CONSTASCII_USTRINGPARAM( "CustomShapeGeometry" ) );
        xPropSet->setPropertyValue( sCustomShapeGeometry, Any( aSeq ) );
    }
}

double CustomShapeProperties::getValue( const std::vector< CustomShapeGuide >& rGuideList, sal_uInt32 nIndex ) const
{
    double fRet = 0.0;
    if ( nIndex < rGuideList.size() )
    {

    }
    return fRet;
}

} }
<commit_msg>INTEGRATION: CWS xmlfilter05 (1.3.4); FILE MERGED 2008/05/21 12:55:44 dr 1.3.4.4: #i10000# new header 2008/04/25 08:57:33 dr 1.3.4.3: more cleanup 2008/04/02 12:41:55 hbrinkm 1.3.4.2: merged changes from xmlfilter04 to xmlfilter05 2008/04/01 15:38:02 hbrinkm 1.3.4.1: 'Merged xmlfilter04'<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: customshapeproperties.cxx,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.
 *
 ************************************************************************/

#include <comphelper/processfactory.hxx>
#include "oox/drawingml/customshapeproperties.hxx"
#include "oox/helper/helper.hxx"
#include "oox/helper/propertyset.hxx"
#include "oox/core/namespaces.hxx"
#include "tokens.hxx"
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/graphic/XGraphicTransformer.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/drawing/XEnhancedCustomShapeDefaulter.hpp>

using rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::graphic;
using namespace ::com::sun::star::drawing;

namespace oox { namespace drawingml {

CustomShapeProperties::CustomShapeProperties()
{
}
CustomShapeProperties::~CustomShapeProperties()
{
}

void CustomShapeProperties::apply( const CustomShapePropertiesPtr& /* rSourceCustomShapeProperties */ )
{
    // not sure if this needs to be implemented
}

void CustomShapeProperties::pushToPropSet( const ::oox::core::XmlFilterBase& /* rFilterBase */,
    const Reference < XPropertySet >& xPropSet, const Reference < XShape > & xShape ) const
{
    const OUString sType = CREATE_OUSTRING( "Type" );
    if ( maShapePresetType.getLength() )
    {
        //const uno::Reference < drawing::XShape > xShape( xPropSet, UNO_QUERY );
        Reference< drawing::XEnhancedCustomShapeDefaulter > xDefaulter( xShape, UNO_QUERY );
        if( xDefaulter.is() )
            xDefaulter->createCustomShapeDefaults( maShapePresetType );

        const rtl::OUString sCustomShapeGeometry( RTL_CONSTASCII_USTRINGPARAM( "CustomShapeGeometry" ) );
        uno::Any aGeoPropSet = xPropSet->getPropertyValue( sCustomShapeGeometry );
        uno::Sequence< beans::PropertyValue > aGeoPropSeq;
        if ( aGeoPropSet >>= aGeoPropSeq )
        {
            sal_Int32 i, nCount = aGeoPropSeq.getLength();
            for ( i = 0; i < nCount; i++ )
            {
                const rtl::OUString sAdjustmentValues( RTL_CONSTASCII_USTRINGPARAM( "AdjustmentValues" ) );
                if ( aGeoPropSeq[ i ].Name.equals( sAdjustmentValues ) )
                {
                    uno::Sequence< com::sun::star::drawing::EnhancedCustomShapeAdjustmentValue > aAdjustmentSeq;
                    if ( aGeoPropSeq[ i ].Value >>= aAdjustmentSeq )
                    {
                        sal_uInt32 j, nHighest = 0;
                        for( j = 0; j < maAdjustmentValues.size(); j++ )
                        {
                            const rtl::OUString& rS( maAdjustmentValues[ j ].maName );
                            if ( rS.getLength() > 3 )
                            {
                                sal_uInt32 nVal = rS.copy( 3 ).toInt32();
                                if ( ( nVal < 10 ) && ( nVal > nHighest ) )
                                    nHighest = nVal;
                            }
                        }
                        if ( nHighest > static_cast< sal_uInt32 >( aAdjustmentSeq.getLength() ) )
                            aAdjustmentSeq.realloc( nHighest );

                        for ( j = 0; j < maAdjustmentValues.size(); j++ )
                        {
                            sal_uInt32 nVal = maAdjustmentValues[ j ].maName.copy( 3 ).toInt32();
                            if ( nVal-- )
                            {
                                double fNewAdj = getValue( maAdjustmentValues, nVal );
                                aAdjustmentSeq[ nVal ].State = beans::PropertyState_DIRECT_VALUE;
                                aAdjustmentSeq[ nVal ].Value <<= fNewAdj;
                            }
                        }
                        aGeoPropSeq[ i ].Value <<= aAdjustmentSeq;
                        xPropSet->setPropertyValue( sCustomShapeGeometry, Any( aGeoPropSeq ) );
                    }
                }
                else if ( aGeoPropSeq[ i ].Name.equals( sType ) )
                {
                    aGeoPropSeq[ i ].Value <<= maShapePresetType;
                }
            }
        }
    }
    else
    {
        PropertyMap aPropertyMap;
        OUString sShapeType( CREATE_OUSTRING( "non-primitive" ) );
        aPropertyMap[ sType ] <<= sShapeType;

        // converting the vector to a sequence
        Sequence< PropertyValue > aSeq;
        aPropertyMap.makeSequence( aSeq );
        static const rtl::OUString sCustomShapeGeometry( RTL_CONSTASCII_USTRINGPARAM( "CustomShapeGeometry" ) );
        xPropSet->setPropertyValue( sCustomShapeGeometry, Any( aSeq ) );
    }
}

double CustomShapeProperties::getValue( const std::vector< CustomShapeGuide >& rGuideList, sal_uInt32 nIndex ) const
{
    double fRet = 0.0;
    if ( nIndex < rGuideList.size() )
    {

    }
    return fRet;
}

} }
<|endoftext|>


<commit_before>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Markus Fasel                                          *
 *                                                                        *
 * 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.                  *
 **************************************************************************/
#include <vector>

#include "AliEMCALTriggerTypes.h"
#include "AliEMCALGeometry.h"
#include "AliEMCALTriggerBitConfig.h"
#include "AliEMCALTriggerMapping.h"
#include "AliEMCALTriggerTypes.h"
#include "AliEMCALTriggerAlgorithm.h"
#include "AliEMCALTriggerDataGrid.h"
#include "AliEMCALTriggerPatchFinder.h"
#include "AliEMCALTriggerPatchInfo.h"
#include "AliEMCALTriggerRawPatch.h"
#include "AliEMCALTriggerConstants.h"

#include "AliHLTCaloDigitDataStruct.h"
#include "AliHLTCaloTriggerPatchContainerStruct.h"
#include "AliHLTCaloTriggerPatchDataStruct.h"
#include "AliHLTEMCALGeometry.h"
#include "AliHLTEMCALTriggerMaker.h"

ClassImp(AliHLTEMCALTriggerMaker)

AliHLTEMCALTriggerMaker::AliHLTEMCALTriggerMaker() :
  TObject(),
  AliHLTLogging(),
  fTriggerPatchDataPtr(NULL),
  fkGeometryPtr(NULL),
  fPatchFinder(NULL),
  fL0PatchFinder(NULL),
  fADCValues(NULL),
  fADCOfflineValues(NULL),
  fL0Amplitudes(NULL),
  fTriggerBitMasks(NULL),
  fLevel0TimeMap(NULL),
  fTriggerBitConfig(NULL),
  fJetPatchSize(8),
  fJetSubregionSize(4),
  fGammaPatchSize(2),
  fGammaSubregionSize(1),
  fBkgPatchSize(8),
  fBkgSubregionSize(4),
  fL0MinTime(7),
  fL0MaxTime(10),
  fBufferSize(0),
  fBkgThresholdOnline(-0.1),
  fBkgThresholdOffline(-0.1),
  fRunBkgAlgorithm(kTRUE),
  fLevel0ThresholdOnline(0),
  fLevel0ThresholdOffline(0)
{
  fTriggerBitConfig = new AliEMCALTriggerBitConfigNew;
  memset(fJetThresholdOnline, 0, sizeof(Float_t) * kNthresholds);
  memset(fJetThresholdOffline, 0, sizeof(Float_t) * kNthresholds);
  memset(fGammaThresholdOnline, 0, sizeof(Float_t) * kNthresholds);
  memset(fGammaThresholdOffline, 0, sizeof(Float_t) * kNthresholds);
}

AliHLTEMCALTriggerMaker::~AliHLTEMCALTriggerMaker() {
  if(fTriggerBitConfig) delete fTriggerBitConfig;
  if(fPatchFinder) delete fPatchFinder;
  if(fL0PatchFinder) delete fL0PatchFinder;
  if(fADCValues) delete fADCValues;
  if(fADCOfflineValues) delete fADCOfflineValues;
  if(fL0Amplitudes) delete fL0Amplitudes;
  if(fTriggerBitMasks) delete fTriggerBitMasks;
  if(fLevel0TimeMap) delete fLevel0TimeMap;
}

void AliHLTEMCALTriggerMaker::ResetADC(){
  fADCValues->Reset();
  fADCOfflineValues->Reset();
  fL0Amplitudes->Reset();
  fTriggerBitMasks->Reset();
  fLevel0TimeMap->Reset();
}

void AliHLTEMCALTriggerMaker::AddDigit(const AliHLTCaloDigitDataStruct *digit){
  /*
   * TODO Crosscheck
   */
  Int_t fastorIndex;
  fkGeometryPtr->GetGeometryPtr()->GetTriggerMapping()->GetFastORIndexFromCellIndex(fkGeometryPtr->GetGeometryPtr()->GetAbsCellIdFromCellIndexes(digit->fModule, digit->fX, digit->fZ), fastorIndex);
  int globCol, globRow;
  fkGeometryPtr->GetGeometryPtr()->GetTriggerMapping()->GetPositionInEMCALFromAbsFastORIndex(fastorIndex, globCol, globRow);
  (*fADCOfflineValues)(globCol, globRow) += digit->fEnergy;
}

void AliHLTEMCALTriggerMaker::SetADC(Int_t col, Int_t row, Float_t adc){
  (*fADCValues)(col, row) = adc;
}

void AliHLTEMCALTriggerMaker::SetL0Amplitude(Int_t col, Int_t row, Float_t amp){
  (*fL0Amplitudes)(col, row) = amp;
}

void AliHLTEMCALTriggerMaker::SetL0Time(Int_t col, Int_t row, UChar_t time){
  (*fLevel0TimeMap)(col, row) = time;
}

void AliHLTEMCALTriggerMaker::SetBitMask(Int_t col, Int_t row, Int_t bitMask){
  (*fTriggerBitMasks)(col, row) = bitMask;
}

Int_t AliHLTEMCALTriggerMaker::FindPatches(){
  /*
  if(availableSize < sizeof(AliHLTCaloTriggerPatchDataStruct)){
    HLTError("Not enough space to write new trigger patches");
    return -1;
  }
   */

  //AliHLTUInt32_t mysize = availableSize;
  std::vector<AliEMCALTriggerRawPatch> foundpatches = fPatchFinder->FindPatches(*fADCValues, *fADCOfflineValues);
  Int_t patchcount = 0;
  AliHLTCaloTriggerPatchDataStruct *next = NULL;
  for(std::vector<AliEMCALTriggerRawPatch>::iterator patchiter = foundpatches.begin(); patchiter != foundpatches.end(); ++patchiter){
    if(fBufferSize < sizeof(AliHLTCaloTriggerPatchDataStruct)){
      HLTWarning("Buffer exceeded after %d trigger patches", patchcount);
      break;
    }
    next = fTriggerPatchDataPtr + 1;
    // Set offline bits
    // Note: trigger patch can contain more than one patch type
    Int_t offlinebits = 0;
    if(patchiter->GetPatchSize() == fGammaPatchSize){
      if(patchiter->GetADC() > fGammaThresholdOnline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetGammaHighBit());
      if(patchiter->GetOfflineADC() > fGammaThresholdOffline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetGammaHighBit());
      if(patchiter->GetADC() > fGammaThresholdOnline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetGammaLowBit());
      if(patchiter->GetOfflineADC() > fGammaThresholdOffline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetGammaLowBit());
    }
    if (patchiter->GetPatchSize() == fJetPatchSize){
      if(patchiter->GetADC() > fJetThresholdOnline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetJetHighBit());
      if(patchiter->GetOfflineADC() > fJetThresholdOffline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetJetHighBit());
      if(patchiter->GetADC() > fJetThresholdOnline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetJetLowBit());
      if(patchiter->GetOfflineADC() > fJetThresholdOffline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetJetLowBit());
    }
    if (patchiter->GetPatchSize() == fBkgPatchSize){
      if(patchiter->GetADC() > fBkgThresholdOnline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetBkgBit());
      if(patchiter->GetOfflineADC() > fBkgThresholdOffline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetBkgBit());
    }
    MakeHLTPatch(*patchiter, *fTriggerPatchDataPtr, offlinebits);
    fTriggerPatchDataPtr = next;
    patchcount++;
    fBufferSize -= sizeof(AliHLTCaloTriggerPatchDataStruct);
  }

  // Do Level0 patches as well
  std::vector<AliEMCALTriggerRawPatch> l0patches = fL0PatchFinder->FindPatches(*fL0Amplitudes, *fADCOfflineValues);
  for(std::vector<AliEMCALTriggerRawPatch>::iterator patchit = l0patches.begin(); patchit != l0patches.end(); ++patchit){
    ELevel0TriggerStatus_t L0trigger = CheckForL0(patchit->GetColStart(), patchit->GetRowStart());
    if (L0trigger == kNotLevel0) continue;
    Int_t onlinebits = 0;
    if (L0trigger == kLevel0Fired) SETBIT(onlinebits, fTriggerBitConfig->GetLevel0Bit());
    Int_t offlinebits = 0;
    if(patchit->GetADC() > fLevel0ThresholdOnline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetLevel0Bit());
    if(patchit->GetOfflineADC() > fLevel0ThresholdOffline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetLevel0Bit());
    if(!offlinebits) continue;
    next = fTriggerPatchDataPtr + 1;
    MakeHLTPatch(*patchit, *fTriggerPatchDataPtr, offlinebits);
    fTriggerPatchDataPtr = next;
    patchcount++;
    fBufferSize -= sizeof(AliHLTCaloTriggerPatchDataStruct);
  }
  return patchcount;
}

void AliHLTEMCALTriggerMaker::Initialise(const AliHLTEMCALGeometry *geo){
  fkGeometryPtr = geo;

  // Allocate
  fADCValues = new AliEMCALTriggerDataGrid<float>;
  fADCValues->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fADCOfflineValues = new AliEMCALTriggerDataGrid<float>;
  fADCOfflineValues->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fL0Amplitudes = new AliEMCALTriggerDataGrid<float>;
  fL0Amplitudes->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fTriggerBitMasks = new AliEMCALTriggerDataGrid<int>;
  fTriggerBitMasks->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fLevel0TimeMap = new AliEMCALTriggerDataGrid<unsigned char>;
  fLevel0TimeMap->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fPatchFinder = new AliEMCALTriggerPatchFinder<float>;
  InitializeLevel1PatchFinders(false);
  if(fkGeometryPtr->GetGeometryPtr()->GetNumberOfSuperModules() > 12){
    InitializeLevel1PatchFinders(true);
  }

  fL0PatchFinder = new AliEMCALTriggerPatchFinder<float>;
  InitializeLevel0PatchFinders(false);
  if(fkGeometryPtr->GetGeometryPtr()->GetNumberOfSuperModules() > 12){
    InitializeLevel0PatchFinders(true);
  }

}

void AliHLTEMCALTriggerMaker::InitializeLevel1PatchFinders(Bool_t isDCAL){
  Int_t rowMin = isDCAL ? 64 : 0, rowMax =  isDCAL ? 103 : 63;
  AliEMCALTriggerAlgorithm<float> *gammatrigger = new AliEMCALTriggerAlgorithm<float>(rowMin, rowMax, 0);
  gammatrigger->SetThresholds(0, 0);
  gammatrigger->SetPatchSize(fGammaPatchSize);
  gammatrigger->SetSubregionSize(fGammaSubregionSize);
  fPatchFinder->AddTriggerAlgorithm(gammatrigger);
  AliEMCALTriggerAlgorithm<float> *jettrigger = new AliEMCALTriggerAlgorithm<float>(rowMin, rowMax, 0);
  jettrigger->SetThresholds(0, 0);
  jettrigger->SetPatchSize(fJetPatchSize);
  jettrigger->SetSubregionSize(fJetSubregionSize);
  fPatchFinder->AddTriggerAlgorithm(jettrigger);
  if(fRunBkgAlgorithm){
    AliEMCALTriggerAlgorithm<float> *jetmedian = new AliEMCALTriggerAlgorithm<float>(rowMin, rowMax, 0);
    jetmedian->SetThresholds(-1, -1);
    jetmedian->SetPatchSize(fBkgPatchSize);
    jetmedian->SetSubregionSize(fBkgSubregionSize);
    fPatchFinder->AddTriggerAlgorithm(jetmedian);
  }
}

void AliHLTEMCALTriggerMaker::InitializeLevel0PatchFinders(Bool_t isDCAL){
  AliEMCALTriggerAlgorithm<float> *l0trigger =  new AliEMCALTriggerAlgorithm<float>(isDCAL ? 64 : 0, isDCAL ? 103 : 63, 0);
  l0trigger->SetThresholds(0, 0);
  l0trigger->SetPatchSize(2);
  l0trigger->SetSubregionSize(1);
  fL0PatchFinder->AddTriggerAlgorithm(l0trigger);
}

void AliHLTEMCALTriggerMaker::MakeHLTPatch(const AliEMCALTriggerRawPatch &input, AliHLTCaloTriggerPatchDataStruct &output, UInt_t offlinebits) const {
  output.fCol = input.GetColStart();
  output.fRow = input.GetRowStart();
  output.fSize = input.GetPatchSize();
  output.fADC = input.GetADC();
  output.fOfflineADC = input.GetOfflineADC();
  output.fBitMask = input.GetBitmask() | (*fTriggerBitMasks)(output.fCol, output.fRow) | offlinebits;
}

AliHLTEMCALTriggerMaker::ELevel0TriggerStatus_t AliHLTEMCALTriggerMaker::CheckForL0(Int_t col, Int_t row) const {
  ELevel0TriggerStatus_t result = kLevel0Candidate;

  if(col < 0 || row < 0){
    AliError(Form("Patch outside range [col %d, row %d]", col, row));
    return kNotLevel0;
  }
  Int_t truref(-1), trumod(-1), absFastor(-1), adc(-1);
  fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(col, row, absFastor);
  fkGeometryPtr->GetGeometryPtr()->GetTRUFromAbsFastORIndex(absFastor, truref, adc);
  int nvalid(0);
  const Int_t kColsEta = 48;
  const int kNRowsPhi = fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2;
  for(int ipos = 0; ipos < 2; ipos++){
    if(row + ipos >= kNRowsPhi) continue;    // boundary check
    for(int jpos = 0; jpos < 2; jpos++){
      if(col + jpos >= kColsEta) continue;  // boundary check
      // Check whether we are in the same TRU
      trumod = -1;
      fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(col+jpos, row+ipos, absFastor);
      fkGeometryPtr->GetGeometryPtr()->GetTRUFromAbsFastORIndex(absFastor, trumod, adc);
      if(trumod != truref) {
        result = kNotLevel0;
        return result;
      }
      if(col + jpos >= kColsEta) AliError(Form("Boundary error in col [%d, %d + %d]", col + jpos, col, jpos));
      if(row + ipos >= kNRowsPhi) AliError(Form("Boundary error in row [%d, %d + %d]", row + ipos, row, ipos));
      Char_t l0times = (*fLevel0TimeMap)(col + jpos,row + ipos);
      if(l0times > fL0MinTime && l0times < fL0MaxTime) nvalid++;
    }
  }
  if (nvalid == 4) result = kLevel0Fired;
  return result;
}
<commit_msg>Convert offline energy to ADC counts before making offline patches<commit_after>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Markus Fasel                                          *
 *                                                                        *
 * 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.                  *
 **************************************************************************/
#include <vector>

#include "AliEMCALTriggerTypes.h"
#include "AliEMCALGeometry.h"
#include "AliEMCALTriggerBitConfig.h"
#include "AliEMCALTriggerMapping.h"
#include "AliEMCALTriggerTypes.h"
#include "AliEMCALTriggerAlgorithm.h"
#include "AliEMCALTriggerDataGrid.h"
#include "AliEMCALTriggerPatchFinder.h"
#include "AliEMCALTriggerPatchInfo.h"
#include "AliEMCALTriggerRawPatch.h"
#include "AliEMCALTriggerConstants.h"

#include "AliHLTCaloDigitDataStruct.h"
#include "AliHLTCaloTriggerPatchContainerStruct.h"
#include "AliHLTCaloTriggerPatchDataStruct.h"
#include "AliHLTEMCALGeometry.h"
#include "AliHLTEMCALTriggerMaker.h"

ClassImp(AliHLTEMCALTriggerMaker)

AliHLTEMCALTriggerMaker::AliHLTEMCALTriggerMaker() :
  TObject(),
  AliHLTLogging(),
  fTriggerPatchDataPtr(NULL),
  fkGeometryPtr(NULL),
  fPatchFinder(NULL),
  fL0PatchFinder(NULL),
  fADCValues(NULL),
  fADCOfflineValues(NULL),
  fL0Amplitudes(NULL),
  fTriggerBitMasks(NULL),
  fLevel0TimeMap(NULL),
  fTriggerBitConfig(NULL),
  fJetPatchSize(8),
  fJetSubregionSize(4),
  fGammaPatchSize(2),
  fGammaSubregionSize(1),
  fBkgPatchSize(8),
  fBkgSubregionSize(4),
  fL0MinTime(7),
  fL0MaxTime(10),
  fBufferSize(0),
  fBkgThresholdOnline(-0.1),
  fBkgThresholdOffline(-0.1),
  fRunBkgAlgorithm(kTRUE),
  fLevel0ThresholdOnline(0),
  fLevel0ThresholdOffline(0)
{
  fTriggerBitConfig = new AliEMCALTriggerBitConfigNew;
  memset(fJetThresholdOnline, 0, sizeof(Float_t) * kNthresholds);
  memset(fJetThresholdOffline, 0, sizeof(Float_t) * kNthresholds);
  memset(fGammaThresholdOnline, 0, sizeof(Float_t) * kNthresholds);
  memset(fGammaThresholdOffline, 0, sizeof(Float_t) * kNthresholds);
}

AliHLTEMCALTriggerMaker::~AliHLTEMCALTriggerMaker() {
  if(fTriggerBitConfig) delete fTriggerBitConfig;
  if(fPatchFinder) delete fPatchFinder;
  if(fL0PatchFinder) delete fL0PatchFinder;
  if(fADCValues) delete fADCValues;
  if(fADCOfflineValues) delete fADCOfflineValues;
  if(fL0Amplitudes) delete fL0Amplitudes;
  if(fTriggerBitMasks) delete fTriggerBitMasks;
  if(fLevel0TimeMap) delete fLevel0TimeMap;
}

void AliHLTEMCALTriggerMaker::ResetADC(){
  fADCValues->Reset();
  fADCOfflineValues->Reset();
  fL0Amplitudes->Reset();
  fTriggerBitMasks->Reset();
  fLevel0TimeMap->Reset();
}

void AliHLTEMCALTriggerMaker::AddDigit(const AliHLTCaloDigitDataStruct *digit){
  /*
   * TODO Crosscheck
   */
  Int_t fastorIndex;
  fkGeometryPtr->GetGeometryPtr()->GetTriggerMapping()->GetFastORIndexFromCellIndex(fkGeometryPtr->GetGeometryPtr()->GetAbsCellIdFromCellIndexes(digit->fModule, digit->fX, digit->fZ), fastorIndex);
  int globCol, globRow;
  fkGeometryPtr->GetGeometryPtr()->GetTriggerMapping()->GetPositionInEMCALFromAbsFastORIndex(fastorIndex, globCol, globRow);
  (*fADCOfflineValues)(globCol, globRow) += digit->fEnergy/EMCALTrigger::kEMCL1ADCtoGeV;
}

void AliHLTEMCALTriggerMaker::SetADC(Int_t col, Int_t row, Float_t adc){
  (*fADCValues)(col, row) = adc;
}

void AliHLTEMCALTriggerMaker::SetL0Amplitude(Int_t col, Int_t row, Float_t amp){
  (*fL0Amplitudes)(col, row) = amp;
}

void AliHLTEMCALTriggerMaker::SetL0Time(Int_t col, Int_t row, UChar_t time){
  (*fLevel0TimeMap)(col, row) = time;
}

void AliHLTEMCALTriggerMaker::SetBitMask(Int_t col, Int_t row, Int_t bitMask){
  (*fTriggerBitMasks)(col, row) = bitMask;
}

Int_t AliHLTEMCALTriggerMaker::FindPatches(){
  /*
  if(availableSize < sizeof(AliHLTCaloTriggerPatchDataStruct)){
    HLTError("Not enough space to write new trigger patches");
    return -1;
  }
   */

  //AliHLTUInt32_t mysize = availableSize;
  std::vector<AliEMCALTriggerRawPatch> foundpatches = fPatchFinder->FindPatches(*fADCValues, *fADCOfflineValues);
  Int_t patchcount = 0;
  AliHLTCaloTriggerPatchDataStruct *next = NULL;
  for(std::vector<AliEMCALTriggerRawPatch>::iterator patchiter = foundpatches.begin(); patchiter != foundpatches.end(); ++patchiter){
    if(fBufferSize < sizeof(AliHLTCaloTriggerPatchDataStruct)){
      HLTWarning("Buffer exceeded after %d trigger patches", patchcount);
      break;
    }
    next = fTriggerPatchDataPtr + 1;
    // Set offline bits
    // Note: trigger patch can contain more than one patch type
    Int_t offlinebits = 0;
    if(patchiter->GetPatchSize() == fGammaPatchSize){
      if(patchiter->GetADC() > fGammaThresholdOnline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetGammaHighBit());
      if(patchiter->GetOfflineADC() > fGammaThresholdOffline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetGammaHighBit());
      if(patchiter->GetADC() > fGammaThresholdOnline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetGammaLowBit());
      if(patchiter->GetOfflineADC() > fGammaThresholdOffline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetGammaLowBit());
    }
    if (patchiter->GetPatchSize() == fJetPatchSize){
      if(patchiter->GetADC() > fJetThresholdOnline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetJetHighBit());
      if(patchiter->GetOfflineADC() > fJetThresholdOffline[kHighThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetJetHighBit());
      if(patchiter->GetADC() > fJetThresholdOnline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetJetLowBit());
      if(patchiter->GetOfflineADC() > fJetThresholdOffline[kLowThreshold]) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetJetLowBit());
    }
    if (patchiter->GetPatchSize() == fBkgPatchSize){
      if(patchiter->GetADC() > fBkgThresholdOnline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetBkgBit());
      if(patchiter->GetOfflineADC() > fBkgThresholdOffline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetBkgBit());
    }
    MakeHLTPatch(*patchiter, *fTriggerPatchDataPtr, offlinebits);
    fTriggerPatchDataPtr = next;
    patchcount++;
    fBufferSize -= sizeof(AliHLTCaloTriggerPatchDataStruct);
  }

  // Do Level0 patches as well
  std::vector<AliEMCALTriggerRawPatch> l0patches = fL0PatchFinder->FindPatches(*fL0Amplitudes, *fADCOfflineValues);
  for(std::vector<AliEMCALTriggerRawPatch>::iterator patchit = l0patches.begin(); patchit != l0patches.end(); ++patchit){
    ELevel0TriggerStatus_t L0trigger = CheckForL0(patchit->GetColStart(), patchit->GetRowStart());
    if (L0trigger == kNotLevel0) continue;
    Int_t onlinebits = 0;
    if (L0trigger == kLevel0Fired) SETBIT(onlinebits, fTriggerBitConfig->GetLevel0Bit());
    Int_t offlinebits = 0;
    if(patchit->GetADC() > fLevel0ThresholdOnline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kRecalcOffset + fTriggerBitConfig->GetLevel0Bit());
    if(patchit->GetOfflineADC() > fLevel0ThresholdOffline) SETBIT(offlinebits, AliEMCALTriggerPatchInfo::kOfflineOffset + fTriggerBitConfig->GetLevel0Bit());
    if(!offlinebits) continue;
    next = fTriggerPatchDataPtr + 1;
    MakeHLTPatch(*patchit, *fTriggerPatchDataPtr, offlinebits);
    fTriggerPatchDataPtr = next;
    patchcount++;
    fBufferSize -= sizeof(AliHLTCaloTriggerPatchDataStruct);
  }
  return patchcount;
}

void AliHLTEMCALTriggerMaker::Initialise(const AliHLTEMCALGeometry *geo){
  fkGeometryPtr = geo;

  // Allocate
  fADCValues = new AliEMCALTriggerDataGrid<float>;
  fADCValues->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fADCOfflineValues = new AliEMCALTriggerDataGrid<float>;
  fADCOfflineValues->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fL0Amplitudes = new AliEMCALTriggerDataGrid<float>;
  fL0Amplitudes->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fTriggerBitMasks = new AliEMCALTriggerDataGrid<int>;
  fTriggerBitMasks->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fLevel0TimeMap = new AliEMCALTriggerDataGrid<unsigned char>;
  fLevel0TimeMap->Allocate(48, fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2);

  fPatchFinder = new AliEMCALTriggerPatchFinder<float>;
  InitializeLevel1PatchFinders(false);
  if(fkGeometryPtr->GetGeometryPtr()->GetNumberOfSuperModules() > 12){
    InitializeLevel1PatchFinders(true);
  }

  fL0PatchFinder = new AliEMCALTriggerPatchFinder<float>;
  InitializeLevel0PatchFinders(false);
  if(fkGeometryPtr->GetGeometryPtr()->GetNumberOfSuperModules() > 12){
    InitializeLevel0PatchFinders(true);
  }

}

void AliHLTEMCALTriggerMaker::InitializeLevel1PatchFinders(Bool_t isDCAL){
  Int_t rowMin = isDCAL ? 64 : 0, rowMax =  isDCAL ? 103 : 63;
  AliEMCALTriggerAlgorithm<float> *gammatrigger = new AliEMCALTriggerAlgorithm<float>(rowMin, rowMax, 0);
  gammatrigger->SetThresholds(0, 0);
  gammatrigger->SetPatchSize(fGammaPatchSize);
  gammatrigger->SetSubregionSize(fGammaSubregionSize);
  fPatchFinder->AddTriggerAlgorithm(gammatrigger);
  AliEMCALTriggerAlgorithm<float> *jettrigger = new AliEMCALTriggerAlgorithm<float>(rowMin, rowMax, 0);
  jettrigger->SetThresholds(0, 0);
  jettrigger->SetPatchSize(fJetPatchSize);
  jettrigger->SetSubregionSize(fJetSubregionSize);
  fPatchFinder->AddTriggerAlgorithm(jettrigger);
  if(fRunBkgAlgorithm){
    AliEMCALTriggerAlgorithm<float> *jetmedian = new AliEMCALTriggerAlgorithm<float>(rowMin, rowMax, 0);
    jetmedian->SetThresholds(-1, -1);
    jetmedian->SetPatchSize(fBkgPatchSize);
    jetmedian->SetSubregionSize(fBkgSubregionSize);
    fPatchFinder->AddTriggerAlgorithm(jetmedian);
  }
}

void AliHLTEMCALTriggerMaker::InitializeLevel0PatchFinders(Bool_t isDCAL){
  AliEMCALTriggerAlgorithm<float> *l0trigger =  new AliEMCALTriggerAlgorithm<float>(isDCAL ? 64 : 0, isDCAL ? 103 : 63, 0);
  l0trigger->SetThresholds(0, 0);
  l0trigger->SetPatchSize(2);
  l0trigger->SetSubregionSize(1);
  fL0PatchFinder->AddTriggerAlgorithm(l0trigger);
}

void AliHLTEMCALTriggerMaker::MakeHLTPatch(const AliEMCALTriggerRawPatch &input, AliHLTCaloTriggerPatchDataStruct &output, UInt_t offlinebits) const {
  output.fCol = input.GetColStart();
  output.fRow = input.GetRowStart();
  output.fSize = input.GetPatchSize();
  output.fADC = input.GetADC();
  output.fOfflineADC = input.GetOfflineADC();
  output.fBitMask = input.GetBitmask() | (*fTriggerBitMasks)(output.fCol, output.fRow) | offlinebits;
}

AliHLTEMCALTriggerMaker::ELevel0TriggerStatus_t AliHLTEMCALTriggerMaker::CheckForL0(Int_t col, Int_t row) const {
  ELevel0TriggerStatus_t result = kLevel0Candidate;

  if(col < 0 || row < 0){
    AliError(Form("Patch outside range [col %d, row %d]", col, row));
    return kNotLevel0;
  }
  Int_t truref(-1), trumod(-1), absFastor(-1), adc(-1);
  fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(col, row, absFastor);
  fkGeometryPtr->GetGeometryPtr()->GetTRUFromAbsFastORIndex(absFastor, truref, adc);
  int nvalid(0);
  const Int_t kColsEta = 48;
  const int kNRowsPhi = fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU() * 2;
  for(int ipos = 0; ipos < 2; ipos++){
    if(row + ipos >= kNRowsPhi) continue;    // boundary check
    for(int jpos = 0; jpos < 2; jpos++){
      if(col + jpos >= kColsEta) continue;  // boundary check
      // Check whether we are in the same TRU
      trumod = -1;
      fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(col+jpos, row+ipos, absFastor);
      fkGeometryPtr->GetGeometryPtr()->GetTRUFromAbsFastORIndex(absFastor, trumod, adc);
      if(trumod != truref) {
        result = kNotLevel0;
        return result;
      }
      if(col + jpos >= kColsEta) AliError(Form("Boundary error in col [%d, %d + %d]", col + jpos, col, jpos));
      if(row + ipos >= kNRowsPhi) AliError(Form("Boundary error in row [%d, %d + %d]", row + ipos, row, ipos));
      Char_t l0times = (*fLevel0TimeMap)(col + jpos,row + ipos);
      if(l0times > fL0MinTime && l0times < fL0MaxTime) nvalid++;
    }
  }
  if (nvalid == 4) result = kLevel0Fired;
  return result;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <ncurses.h>
#include <stdlib.h>
#include <string>

#include "key_aliases.hh"
#include "contents.hh"
#include "file_contents.hh"
#include "show_message.hh"

boost::optional<std::string> prompt(const std::string& message)
{
    std::string text;
    int b_y, b_x, x, y;
    getyx(stdscr, b_y, b_x);
    getmaxyx(stdscr, y, x);

    --y; x = 0;
    move(y, x);
    printw("%s", message.c_str());
    x += message.length();
    move(y, x);

    while (true) {
        char c = getch();
        switch (c) {
            case ERR:
                std::cout << "ERROR character: " << ERR;
                endwin();
                exit(2);
                break;
            case _escape:
                move(b_y, b_x);
                return boost::none;
            case _backspace:
            case _control_h:
                if (text.size()) text.erase(text.begin() + --x);
                move(y, 0);
                clrtoeol();
                for (size_t i = 0; i < message.size(); i++) {
                    move(y, i);
                    addch(message[i]);
                }
                for (size_t i = 0; i < text.size(); i++) {
                    move(y, i + message.size());
                    addch(text[i]);
                }
                break;
            case '\n':
                move(b_y, b_x);
                return text;
            default:
                move(y, x++ + message.length());
                addch(c);
                text += c;
                break;
        }
    }

    return text;
}
<commit_msg>Clear prompt line before start ``prompt()``ing<commit_after>#include <iostream>
#include <ncurses.h>
#include <stdlib.h>
#include <string>

#include "key_aliases.hh"
#include "contents.hh"
#include "file_contents.hh"
#include "show_message.hh"

boost::optional<std::string> prompt(const std::string& message)
{
    std::string text;
    int b_y, b_x, x, y;
    getyx(stdscr, b_y, b_x);
    getmaxyx(stdscr, y, x);

    --y; x = 0;
    move(y, x);
    clrtoeol();
    printw("%s", message.c_str());
    x += message.length();
    move(y, x);

    while (true) {
        char c = getch();
        switch (c) {
            case ERR:
                std::cout << "ERROR character: " << ERR;
                endwin();
                exit(2);
                break;
            case _escape:
                move(b_y, b_x);
                return boost::none;
            case _backspace:
            case _control_h:
                if (text.size()) text.erase(text.begin() + --x);
                move(y, 0);
                clrtoeol();
                for (size_t i = 0; i < message.size(); i++) {
                    move(y, i);
                    addch(message[i]);
                }
                for (size_t i = 0; i < text.size(); i++) {
                    move(y, i + message.size());
                    addch(text[i]);
                }
                break;
            case '\n':
                move(b_y, b_x);
                return text;
            default:
                move(y, x++ + message.length());
                addch(c);
                text += c;
                break;
        }
    }

    return text;
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#if !defined(CPPLINQ_LINQ_ITERATORS_HPP)
#define CPPLINQ_LINQ_ITERATORS_HPP
#pragma once

namespace cpplinq {

    // if a member, provides the straightforward implementation of various redundant operators. For example,
    //   providing -> for any iterator providing *, and so forth.
    struct use_default_iterator_operators {};

    #define CPPLINQ_USE_DEFAULT_ITERATOR_OPERATORS \
    operator ::cpplinq::use_default_iterator_operators() const { return ::cpplinq::use_default_iterator_operators(); }

    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        Iter
        >::type
    operator+(const Iter& it, typename std::iterator_traits<Iter>::distance_type n) {
        return it += n;
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        Iter
        >::type
    operator-(const Iter& it, typename std::iterator_traits<Iter>::distance_type n) {
        return it -= n;
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        Iter
        >::type
    operator-=(const Iter& it, typename std::iterator_traits<Iter>::distance_type n) {
        return it += (-n);
    }

    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator!=(const Iter& it, const Iter& it2) {
        return !(it == it2);
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator>(const Iter& it, const Iter& it2) {
        return it2 < it;
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator<=(const Iter& it, const Iter& it2) {
        return !(it2 < it);
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator>=(const Iter& it, const Iter& it2) {
        return !(it < it2);
    }

    namespace util {
        template <class Iter, class T>
        typename std::iterator_traits<Iter>::pointer deref_iterator(const Iter& it) {
            return deref_iterator(it, util::identity<typename std::iterator_traits<Iter>::reference>());
        }

        template <class Iter, class T>
        T* deref_iterator(const Iter& it, util::identity<T&>) {
            return &*it;
        }

        template <class Iter, class T>
        util::value_ptr<T> deref_iterator(const Iter& it, util::identity<T>) {
            return util::value_ptr<T>(*it);
        }
    }

    template <class Iter>
    class iter_range
    {
        Iter start, finish;
    public:

        CPPLINQ_USE_DEFAULT_ITERATOR_OPERATORS

        typedef Iter iterator;
        typedef typename iterator::value_type value_type;

        explicit iter_range(Iter start, Iter finish) : start(start), finish(finish) {}
        iterator begin() const { return start; }
        iterator end() const { return finish; }
    };
    template <class Iter>
    iter_range<Iter> make_range(Iter start, Iter finish) {
        return iter_range<Iter>(start, finish);
    }

    // decays into a onepass/forward iterator
    template <class Cursor>
    class cursor_iterator
        : public std::iterator<std::forward_iterator_tag,
                typename Cursor::element_type,
                std::ptrdiff_t,
                typename std::conditional<std::is_reference<typename Cursor::reference_type>::value,
                                          typename std::add_pointer<typename Cursor::element_type>::type,
                                          util::value_ptr<typename Cursor::element_type>>::type,
                typename Cursor::reference_type>
    {
    public:
        CPPLINQ_USE_DEFAULT_ITERATOR_OPERATORS;

        cursor_iterator(Cursor cur) : cur(cur) {
        }

        cursor_iterator() : cur() {
        }

        bool operator==(const cursor_iterator& other) const {
            return !cur && !other.cur;
        }

        typename Cursor::reference_type operator*() const {
            return cur->get();
        }

        typename cursor_iterator::pointer operator->() const {
            auto& v = **this;
            return &v;
        }

        cursor_iterator& operator++() {
            cur->inc();

            if (cur->empty()) { cur.reset(); }
            return *this;
        }

        cursor_iterator& operator+=(std::ptrdiff_t n) {
            cur->skip(n);

            if (cur->empty()) { cur.reset(); }
            return *this;
        }

    private:
        bool empty() const {
            !cur || cur->empty();
        }

        util::maybe<Cursor> cur;
    };

    template <class Container>
    class container_range
    {
        Container c;

    public:
        typedef cursor_iterator<typename Container::cursor> iterator;

        container_range(Container c) : c(c)
        {
        }

        iterator begin() const
        {
            return iterator(c.get_cursor());
        }

        iterator end() const
        {
            return iterator();
        }
    };

}

#endif
<commit_msg>Update linq_iterators.hpp<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#if !defined(CPPLINQ_LINQ_ITERATORS_HPP)
#define CPPLINQ_LINQ_ITERATORS_HPP
#pragma once

#include <cstddef>

namespace cpplinq {

    // if a member, provides the straightforward implementation of various redundant operators. For example,
    //   providing -> for any iterator providing *, and so forth.
    struct use_default_iterator_operators {};

    #define CPPLINQ_USE_DEFAULT_ITERATOR_OPERATORS \
    operator ::cpplinq::use_default_iterator_operators() const { return ::cpplinq::use_default_iterator_operators(); }

    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        Iter
        >::type
    operator+(const Iter& it, typename std::iterator_traits<Iter>::distance_type n) {
        return it += n;
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        Iter
        >::type
    operator-(const Iter& it, typename std::iterator_traits<Iter>::distance_type n) {
        return it -= n;
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        Iter
        >::type
    operator-=(const Iter& it, typename std::iterator_traits<Iter>::distance_type n) {
        return it += (-n);
    }

    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator!=(const Iter& it, const Iter& it2) {
        return !(it == it2);
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator>(const Iter& it, const Iter& it2) {
        return it2 < it;
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator<=(const Iter& it, const Iter& it2) {
        return !(it2 < it);
    }
    template <class Iter>
    typename std::enable_if<
        std::is_convertible<Iter, use_default_iterator_operators>::value,
        bool
        >::type
    operator>=(const Iter& it, const Iter& it2) {
        return !(it < it2);
    }

    namespace util {
        template <class Iter, class T>
        typename std::iterator_traits<Iter>::pointer deref_iterator(const Iter& it) {
            return deref_iterator(it, util::identity<typename std::iterator_traits<Iter>::reference>());
        }

        template <class Iter, class T>
        T* deref_iterator(const Iter& it, util::identity<T&>) {
            return &*it;
        }

        template <class Iter, class T>
        util::value_ptr<T> deref_iterator(const Iter& it, util::identity<T>) {
            return util::value_ptr<T>(*it);
        }
    }

    template <class Iter>
    class iter_range
    {
        Iter start, finish;
    public:

        CPPLINQ_USE_DEFAULT_ITERATOR_OPERATORS

        typedef Iter iterator;
        typedef typename iterator::value_type value_type;

        explicit iter_range(Iter start, Iter finish) : start(start), finish(finish) {}
        iterator begin() const { return start; }
        iterator end() const { return finish; }
    };
    template <class Iter>
    iter_range<Iter> make_range(Iter start, Iter finish) {
        return iter_range<Iter>(start, finish);
    }

    // decays into a onepass/forward iterator
    template <class Cursor>
    class cursor_iterator
        : public std::iterator<std::forward_iterator_tag,
                typename Cursor::element_type,
                std::ptrdiff_t,
                typename std::conditional<std::is_reference<typename Cursor::reference_type>::value,
                                          typename std::add_pointer<typename Cursor::element_type>::type,
                                          util::value_ptr<typename Cursor::element_type>>::type,
                typename Cursor::reference_type>
    {
    public:
        CPPLINQ_USE_DEFAULT_ITERATOR_OPERATORS;

        cursor_iterator(Cursor cur) : cur(cur) {
        }

        cursor_iterator() : cur() {
        }

        bool operator==(const cursor_iterator& other) const {
            return !cur && !other.cur;
        }

        typename Cursor::reference_type operator*() const {
            return cur->get();
        }

        typename cursor_iterator::pointer operator->() const {
            auto& v = **this;
            return &v;
        }

        cursor_iterator& operator++() {
            cur->inc();

            if (cur->empty()) { cur.reset(); }
            return *this;
        }

        cursor_iterator& operator+=(std::ptrdiff_t n) {
            cur->skip(n);

            if (cur->empty()) { cur.reset(); }
            return *this;
        }

    private:
        bool empty() const {
            !cur || cur->empty();
        }

        util::maybe<Cursor> cur;
    };

    template <class Container>
    class container_range
    {
        Container c;

    public:
        typedef cursor_iterator<typename Container::cursor> iterator;

        container_range(Container c) : c(c)
        {
        }

        iterator begin() const
        {
            return iterator(c.get_cursor());
        }

        iterator end() const
        {
            return iterator();
        }
    };

}

#endif
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetTaskExecutor.cpp
 */

#include "JPetTaskExecutor.h"
#include <cassert>
#include "../JPetTaskInterface/JPetTaskInterface.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTaskLoader/JPetTaskLoader.h"
#include "../JPetParamGetterAscii/JPetParamGetterAscii.h"
#include "../JPetParamGetterAscii/JPetParamSaverAscii.h"
#include "../JPetLoggerInclude.h"

JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :
  fProcessedFile(processedFileId),
  ftaskGeneratorChain(taskGeneratorChain),
  fOptions(opt)
{
  if (fOptions.isLocalDB()) {
    fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));
  } else {
    fParamManager = new JPetParamManager();
  }
  if (taskGeneratorChain) {
    for (auto taskGenerator : *ftaskGeneratorChain) {
      auto task = taskGenerator();
      task->setParamManager(fParamManager); // maybe that should not be here
      fTasks.push_back(task);
    }
  } else {
    ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor");
  }
}

bool JPetTaskExecutor::process()
{
  if(!processFromCmdLineArgs(fProcessedFile)) {
    ERROR("Error in processFromCmdLineArgs");
    return false;
  }
  for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {
    JPetOptions::Options currOpts = fOptions.getOptions();
    if (currentTask != fTasks.begin()) {
    /// Ignore the event range options for all but the first task.
      currOpts = JPetOptions::resetEventRange(currOpts);
   /// For all but the first task,
   /// the input path must be changed if
   /// the output path argument -o was given, because the input
   /// data for them will lay in the location defined by -o.
      auto outPath  = currOpts.at("outputPath");
      if (!outPath.empty()) {
        currOpts.at("inputFile") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at("inputFile")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at("inputFile"));
      }
    }

    INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
    (*currentTask)->init(currOpts);
    (*currentTask)->exec();
    (*currentTask)->terminate();
    INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
  }
  return true;
}

void* JPetTaskExecutor::processProxy(void* runner)
{
  assert(runner);
  static_cast<JPetTaskExecutor*>(runner)->process();
  return 0;
}

TThread* JPetTaskExecutor::run()
{
  TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this);
  assert(thread);
  thread->Run();
  return thread;
}

bool JPetTaskExecutor::processFromCmdLineArgs(int)
{
  auto runNum = fOptions.getRunNumber();
  if (runNum >= 0) {
    try {
      fParamManager->fillParameterBank(runNum);
    } catch (...) {
      ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum));
      return false;
    }
    if (fOptions.isLocalDBCreate()) {
      JPetParamSaverAscii saver;
      saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());
    }
  }

  auto inputFileType = fOptions.getInputFileType();
  auto inputFile = fOptions.getInputFile();
  if (inputFileType == JPetOptions::kScope) {
    createScopeTaskAndAddToTaskList();
  } else if (inputFileType == JPetOptions::kHld) {
    long long nevents = fOptions.getTotalEvents();
    unpackFile(inputFile, nevents);
  }
  //Assumption that only HLD files can be zipped!!!!!! - Sz.N.
  else if( inputFileType == JPetOptions::kZip){
    INFO( std::string("Unzipping file before unpacking") );
    JPetCommonTools::unzipFile(inputFile);
    long long nevents = fOptions.getTotalEvents();
    INFO( std::string("Unpacking") );
    unpackFile( JPetCommonTools::stripFileNameSuffix( std::string(inputFile) ).c_str(), nevents);
  }

  if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)
    ERROR( Form("Unknown file type provided for file: %s", fOptions.getInputFile()) );

  return true;
}

void JPetTaskExecutor::createScopeTaskAndAddToTaskList()
{
  JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures."));
  assert(module);
  module->setParamManager(fParamManager);
  auto scopeFile = fOptions.getScopeConfigFile();
  if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {
    ERROR("Unable to generate Param Bank from Scope Config");
  }
  fTasks.push_front(module);
}

void JPetTaskExecutor::unpackFile(const char* filename, const long long nevents)
{
    if (nevents > 0) {
      fUnpacker.setParams( filename, nevents);
      WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file."));
    } else {
      fUnpacker.setParams( filename );
    }
    fUnpacker.exec();
}

JPetTaskExecutor::~JPetTaskExecutor()
{
  for (auto & task : fTasks) {
    if (task) {
      delete task;
      task = 0;
    }
  }
}
<commit_msg>Added ERROR message when unzipping file goes wrong<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetTaskExecutor.cpp
 */

#include "JPetTaskExecutor.h"
#include <cassert>
#include "../JPetTaskInterface/JPetTaskInterface.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTaskLoader/JPetTaskLoader.h"
#include "../JPetParamGetterAscii/JPetParamGetterAscii.h"
#include "../JPetParamGetterAscii/JPetParamSaverAscii.h"
#include "../JPetLoggerInclude.h"

JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :
  fProcessedFile(processedFileId),
  ftaskGeneratorChain(taskGeneratorChain),
  fOptions(opt)
{
  if (fOptions.isLocalDB()) {
    fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));
  } else {
    fParamManager = new JPetParamManager();
  }
  if (taskGeneratorChain) {
    for (auto taskGenerator : *ftaskGeneratorChain) {
      auto task = taskGenerator();
      task->setParamManager(fParamManager); // maybe that should not be here
      fTasks.push_back(task);
    }
  } else {
    ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor");
  }
}

bool JPetTaskExecutor::process()
{
  if(!processFromCmdLineArgs(fProcessedFile)) {
    ERROR("Error in processFromCmdLineArgs");
    return false;
  }
  for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {
    JPetOptions::Options currOpts = fOptions.getOptions();
    if (currentTask != fTasks.begin()) {
    /// Ignore the event range options for all but the first task.
      currOpts = JPetOptions::resetEventRange(currOpts);
   /// For all but the first task,
   /// the input path must be changed if
   /// the output path argument -o was given, because the input
   /// data for them will lay in the location defined by -o.
      auto outPath  = currOpts.at("outputPath");
      if (!outPath.empty()) {
        currOpts.at("inputFile") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at("inputFile")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at("inputFile"));
      }
    }

    INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
    (*currentTask)->init(currOpts);
    (*currentTask)->exec();
    (*currentTask)->terminate();
    INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
  }
  return true;
}

void* JPetTaskExecutor::processProxy(void* runner)
{
  assert(runner);
  static_cast<JPetTaskExecutor*>(runner)->process();
  return 0;
}

TThread* JPetTaskExecutor::run()
{
  TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this);
  assert(thread);
  thread->Run();
  return thread;
}

bool JPetTaskExecutor::processFromCmdLineArgs(int)
{
  auto runNum = fOptions.getRunNumber();
  if (runNum >= 0) {
    try {
      fParamManager->fillParameterBank(runNum);
    } catch (...) {
      ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum));
      return false;
    }
    if (fOptions.isLocalDBCreate()) {
      JPetParamSaverAscii saver;
      saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());
    }
  }

  auto inputFileType = fOptions.getInputFileType();
  auto inputFile = fOptions.getInputFile();
  if (inputFileType == JPetOptions::kScope) {
    createScopeTaskAndAddToTaskList();
  } else if (inputFileType == JPetOptions::kHld) {
    long long nevents = fOptions.getTotalEvents();
    unpackFile(inputFile, nevents);
  }
  //Assumption that only HLD files can be zipped!!!!!! - Sz.N.
  else if( inputFileType == JPetOptions::kZip){
    INFO( std::string("Unzipping file before unpacking") );
    if( !JPetCommonTools::unzipFile(inputFile) )
      ERROR( std::string("Problem with unpacking file: ") + inputFile );
    long long nevents = fOptions.getTotalEvents();
    INFO( std::string("Unpacking") );
    unpackFile( JPetCommonTools::stripFileNameSuffix( std::string(inputFile) ).c_str(), nevents);
  }

  if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)
    ERROR( Form("Unknown file type provided for file: %s", fOptions.getInputFile()) );

  return true;
}

void JPetTaskExecutor::createScopeTaskAndAddToTaskList()
{
  JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures."));
  assert(module);
  module->setParamManager(fParamManager);
  auto scopeFile = fOptions.getScopeConfigFile();
  if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {
    ERROR("Unable to generate Param Bank from Scope Config");
  }
  fTasks.push_front(module);
}

void JPetTaskExecutor::unpackFile(const char* filename, const long long nevents)
{
    if (nevents > 0) {
      fUnpacker.setParams( filename, nevents);
      WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file."));
    } else {
      fUnpacker.setParams( filename );
    }
    fUnpacker.exec();
}

JPetTaskExecutor::~JPetTaskExecutor()
{
  for (auto & task : fTasks) {
    if (task) {
      delete task;
      task = 0;
    }
  }
}
<|endoftext|>


<commit_before>// $Id: CycleCreators.py 173 2010-05-12 15:49:33Z krasznaa $

// Local include(s):
#include "../include/Filter.h"
#include <iostream>

ClassImp( Filter );

Filter::Filter()
   : SCycleBase() {

   SetLogName( GetName() );
   DeclareProperty("InTreeName",InTreeName);

   DeclareProperty("ElectronTriggerName", doubEle);
		DeclareProperty("ElectronTriggerName2", doubEle2);

		DeclareProperty("MuonTriggerName1", doubMu);
		DeclareProperty("MuonTriggerName2", doubMu2);
		DeclareProperty("MuonTriggerName3", doubMu3);

		DeclareProperty("is2011",is2011);
		DeclareProperty("is2012_52",is2012_52);
		DeclareProperty("is2012_53",is2012_53);
		DeclareProperty("useTruePileUp",useTruePileUp);
		DeclareProperty("vetoMuonTrigger",vetoMuonTrigger);
		DeclareProperty("vetoElectronTrigger", vetoElectronTrigger);

		DeclareProperty("N_ALL",N_ALL);
		DeclareProperty("N_ELMU",N_ELMU);

		DeclareProperty("cut_mu_pt",cut_mu_pt);
		DeclareProperty("cut_mu_eta",cut_mu_eta);
		DeclareProperty("cut_el_pt",cut_el_pt);
		DeclareProperty("cut_el_eta",cut_el_eta);
		DeclareProperty("cut_tau_pt",cut_tau_pt);
		DeclareProperty("cut_tau_eta",cut_tau_eta);
		DeclareProperty("cut_dR", cut_dR);
		DeclareProperty("lepton_mass_min", lepton_mass_min);
		DeclareProperty("lepton_mass_max", lepton_mass_max);
}

Filter::~Filter() {

}

void Filter::BeginCycle() throw( SError ) {

   return;

}

void Filter::EndCycle() throw( SError ) {

   return;

}

void Filter::BeginInputData( const SInputData& ) throw( SError ) {

	//DeclareVariable(out,"myevent");
	outFile = new TFile("output.root","recreate");
	outTree = new TTree("t","filtered tree");
	outTree->Branch("myevent",&out);
   return;

}

void Filter::EndInputData( const SInputData& ) throw( SError ) {
	outTree->Write();
	outFile->Close();
   return;

}

void Filter::BeginInputFile( const SInputData& ) throw( SError ) {
	ConnectVariable(InTreeName.c_str(),"myevent",m);
   return;

}

double Filter::deltaR(double eta1, double phi1, double eta2, double phi2){
	double dR, dPhi, dEta;
	dR=dPhi=dEta=0.0;
	dPhi = phi1-phi2;
	if (dPhi < -TMath::Pi()) dPhi += TMath::TwoPi();
	if (dPhi > +TMath::Pi()) dPhi -= TMath::TwoPi();
	dEta = eta1-eta2;
	dR = sqrt(dPhi*dPhi+dEta*dEta);

	return dR;
}

double Filter::deltaR(myobject o1, myobject o2)
{
	return deltaR(o1.eta,o1.phi,o2.eta,o2.phi);
}

bool Filter::Trg_MC_12(myevent* m) {
	map<string, int> myHLT = m->HLT;
	bool Trigger = false;
	bool TriggerEle = false;
	bool TriggerMu = false;

	for (map<string, int> ::iterator ihlt = myHLT.begin(); ihlt != myHLT.end(); ihlt++) {
		//	std::cout << ihlt->first << std::endl;
		size_t foundEl=(ihlt->first).find(doubEle);
		size_t foundEl2=(ihlt->first).find(doubEle2);
		if(!is2011) foundEl2=foundEl;

		size_t foundMu1=(ihlt->first).find(doubMu);
		size_t foundMu2=(ihlt->first).find(doubMu2);
		size_t foundMu3=(ihlt->first).find(doubMu3);
		if(!is2011) foundMu3=foundMu2;

		if (foundEl!=string::npos || foundEl2!=string::npos)
			TriggerEle = ihlt->second;
		if (foundMu1!=string::npos || foundMu2!=string::npos || foundMu3!=string::npos)
			TriggerMu = ihlt->second;
	}
	Trigger = TriggerEle || TriggerMu;
	if(vetoElectronTrigger && TriggerEle) Trigger = false;
	if(vetoMuonTrigger && TriggerMu) Trigger = false;
	return Trigger;
}

void Filter::ExecuteEvent( const SInputData&, Double_t ) throw( SError ) {

	m_logger << DEBUG << " Now executing event " << m->eventNumber << " in a run " << m->runNumber << SLogger::endmsg;
	double event_number=1652920;
	bool printout = false;
	if(m->eventNumber==event_number) printout=true;
	if(printout) std::cout << "Here!" << std::endl;

	bool trigPass = Trg_MC_12(m);
	m_logger << DEBUG << " Trigger decision " << trigPass << SLogger::endmsg;
	if(!trigPass)
	{
		if(printout) std::cout << "Trigger!" << std::endl;
		return;
	}
	if(printout) std::cout << "Here2!" << std::endl;

	std::vector<myobject> vertex = m->Vertex;
	bool goodVertex = false;
	for (uint i = 0; i < vertex.size() && !goodVertex; i++) {
		if (vertex[i].isValid && vertex[i].normalizedChi2 > 0 && vertex[i].ndof > 4 && fabs(vertex[i].z) < 24)
		goodVertex=true;
	}

	if(!goodVertex){
		if(printout) std::cout << "vertex!" << std::endl;
		return;
	}

	std::vector<myobject> muon = m->PreSelectedMuons;
	m_logger << VERBOSE << " There are " << muon.size() << " preselected muons " << SLogger::endmsg;

	std::vector<myobject> goodMuon;
	goodMuon.clear();

	for (uint i = 0; i < muon.size(); i++) {

		double muPt = muon[i].pt;
		double muEta = muon[i].eta;
		if (muPt > cut_mu_pt && fabs(muEta) < cut_mu_eta)
		{
				goodMuon.push_back(muon[i]);
		}

	}

	uint N_MU=goodMuon.size();

	std::vector<myobject> electron = m->PreSelectedElectrons;
	m_logger << VERBOSE << " There are " << electron.size() << " preselected electrons " << SLogger::endmsg;

	std::vector<myobject> goodElectron;
	goodElectron.clear();

	for (uint i = 0; i < electron.size(); i++) {

		double elPt = electron[i].pt;
		double elEta = electron[i].eta;

		if (elPt > cut_el_pt && fabs(elEta) < cut_el_eta )
		{
			goodElectron.push_back(electron[i]);
		}
	}

	uint N_EL=goodElectron.size();

	std::vector<myobject> tau = m->PreSelectedHPSTaus;

	m_logger << DEBUG << " There are " << tau.size() << " preselected taus " << SLogger::endmsg;

	std::vector<myobject> goodTau;
	goodTau.clear();

	for (uint i = 0; i < tau.size(); i++) {

		double tauPt = tau[i].pt;
		double tauEta = tau[i].eta;
		bool DecayMode = (tau[i].discriminationByDecayModeFinding > 0.5);

		if (tauPt > cut_tau_pt && fabs(tauEta) < cut_tau_eta && DecayMode)
			goodTau.push_back(tau[i]);
	}

	uint N_TAU=goodTau.size();
	m_logger << DEBUG << " There are " << N_MU << " muons " << N_EL << " electrons and " << N_TAU << " taus." << SLogger::endmsg;

	if(N_ALL > 0 && (N_MU+N_EL+N_TAU) < N_ALL){		if(printout) std::cout << "N_ALL!" << std::endl; return;}
	if(N_ELMU > 0 && (N_MU+N_EL) < N_ELMU){		if(printout) std::cout << "N_ELMU!" << std::endl; return;}

	if(printout) std::cout << "Here3!" << std::endl;

	bool failDR = false;
	if(cut_dR > 0){
		if(N_MU > 0)
		{
			for(uint iMu=0; iMu < N_MU && !failDR; iMu++)
			{
				for(uint jMu =iMu+1; jMu < N_MU && !failDR; jMu++)
				{
					double dR=deltaR(goodMuon[iMu],goodMuon[jMu]);
					m_logger << VERBOSE << " MuMu: " << iMu << " " << jMu << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}

				for(uint iEl =0; iEl < N_EL && !failDR; iEl++)
				{
					double dR=deltaR(goodMuon[iMu],goodElectron[iEl]);
					m_logger << VERBOSE << " MuEl: " << iMu << " " << iEl << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}

				for(uint iTau =0; iTau < N_TAU && !failDR; iTau++)
				{
					double dR=deltaR(goodMuon[iMu],goodTau[iTau]);
					m_logger << VERBOSE << " MuTau: " << iMu << " " << iTau << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}
			}
		}else if(N_EL > 0)
		{
			for(uint iEl=0; iEl < N_EL && !failDR; iEl++)
			{
				for(uint jEl =iEl+1; jEl < N_EL && !failDR; jEl++)
				{
					double dR=deltaR(goodElectron[iEl],goodElectron[jEl]);
					m_logger << VERBOSE << " ElEl: " << iEl << " " << jEl << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}

				for(uint iTau =0; iTau < N_TAU && !failDR; iTau++)
				{
					double dR=deltaR(goodElectron[iEl],goodTau[iTau]);
					m_logger << VERBOSE << " ElTau: " << iEl << " " << iTau << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}
			}

		}else if(N_TAU > 0)
		{
			for(uint iTau=0; iTau < N_TAU && !failDR; iTau++)
			{
				for(uint jTau =iTau+1; jTau < N_TAU && !failDR; jTau++)
				{
					double dR=deltaR(goodTau[iTau],goodTau[jTau]);
					m_logger << VERBOSE << " TauTau: " << iTau << " " << jTau << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}
			}
		}
	}

	if(failDR){		if(printout) std::cout << "dR" << std::endl; return;}
	if(printout) std::cout << "Here4!" << std::endl;

	// dMass cut

	bool passMass = false;

	for (uint i = 0; i < goodMuon.size() && !passMass; i++) {
		for (uint j = i+1; j < goodMuon.size() && !passMass; j++) {
			TLorentzVector cand;
			cand.SetPxPyPzE(goodMuon[i].px+goodMuon[j].px,
					goodMuon[i].py+goodMuon[j].py,
					goodMuon[i].pz+goodMuon[j].pz,
					goodMuon[i].E+goodMuon[j].E);
			double mass = cand.M();
			if(printout) std::cout << mass << std::cout;
			if(mass > lepton_mass_min && mass < lepton_mass_max ) passMass=true;
			if(passMass) m_logger << DEBUG << " Passed mass cut with value " << mass << SLogger::endmsg;
			else m_logger << VERBOSE << " Failed mass cut with value " << mass << SLogger::endmsg;
		}
	}

	for (uint i = 0; i < goodElectron.size() && !passMass; i++) {
		for (uint j = i+1; j < goodElectron.size() && !passMass; j++) {
			TLorentzVector cand;
			cand.SetPxPyPzE(goodElectron[i].px+goodElectron[j].px,
					goodElectron[i].py+goodElectron[j].py,
					goodElectron[i].pz+goodElectron[j].pz,
					goodElectron[i].E+goodElectron[j].E);
			double mass = cand.M();
			if(printout) std::cout << mass << std::cout;
			if(mass > lepton_mass_min && mass < lepton_mass_max ) passMass=true;
			if(passMass) m_logger << DEBUG << " Passed mass cut with value " << mass << SLogger::endmsg;
			else m_logger << VERBOSE << " Failed mass cut with value " << mass << SLogger::endmsg;
		}
	}

	if(!passMass){		if(printout) std::cout << "Mass" << std::endl; return;}
	if(printout) std::cout << "Here5!" << std::endl;

	m_logger << INFO << " Passed!" << SLogger::endmsg;

	out=*m;
	outTree->Fill();

	if(printout) std::cout << "Pass!" << std::endl;

   return;

}

<commit_msg>filter update<commit_after>// $Id: CycleCreators.py 173 2010-05-12 15:49:33Z krasznaa $

// Local include(s):
#include "../include/Filter.h"
#include <iostream>

ClassImp( Filter );

Filter::Filter()
   : SCycleBase(), m_allEvents( "allEvents", this )
   {

   SetLogName( GetName() );
   DeclareProperty("InTreeName",InTreeName);

   DeclareProperty("ElectronTriggerName", doubEle);
		DeclareProperty("ElectronTriggerName2", doubEle2);

		DeclareProperty("MuonTriggerName1", doubMu);
		DeclareProperty("MuonTriggerName2", doubMu2);
		DeclareProperty("MuonTriggerName3", doubMu3);

		DeclareProperty("is2011",is2011);
		DeclareProperty("is2012_52",is2012_52);
		DeclareProperty("is2012_53",is2012_53);
		DeclareProperty("useTruePileUp",useTruePileUp);
		DeclareProperty("vetoMuonTrigger",vetoMuonTrigger);
		DeclareProperty("vetoElectronTrigger", vetoElectronTrigger);

		DeclareProperty("N_ALL",N_ALL);
		DeclareProperty("N_ELMU",N_ELMU);

		DeclareProperty("cut_mu_pt",cut_mu_pt);
		DeclareProperty("cut_mu_eta",cut_mu_eta);
		DeclareProperty("cut_el_pt",cut_el_pt);
		DeclareProperty("cut_el_eta",cut_el_eta);
		DeclareProperty("cut_tau_pt",cut_tau_pt);
		DeclareProperty("cut_tau_eta",cut_tau_eta);
		DeclareProperty("cut_dR", cut_dR);
		DeclareProperty("lepton_mass_min", lepton_mass_min);
		DeclareProperty("lepton_mass_max", lepton_mass_max);
}

Filter::~Filter() {

}

void Filter::BeginCycle() throw( SError ) {

   return;

}

void Filter::EndCycle() throw( SError ) {

   return;

}

void Filter::BeginInputData( const SInputData& ) throw( SError ) {

	//DeclareVariable(out,"myevent");
	outFile = new TFile("output.root","recreate");
	outTree = new TTree("t","filtered tree");
	outTree->Branch("myevent",&out);
	lumi.open("lumi.csv");

	current_run=current_lumi=-999;
   return;

}

void Filter::EndInputData( const SInputData& ) throw( SError ) {
	lumi.close();
	outTree->Write();
	outFile->Close();
	 m_logger << INFO << "Number of all processed events: "
            << *m_allEvents
            << SLogger::endmsg;
     ofstream log1;
     log1.open("total.txt");
     log1 << *m_allEvents << std::endl;
     log1.close();

   return;

}

void Filter::BeginInputFile( const SInputData& ) throw( SError ) {
	ConnectVariable(InTreeName.c_str(),"myevent",m);
   return;

}

double Filter::deltaR(double eta1, double phi1, double eta2, double phi2){
	double dR, dPhi, dEta;
	dR=dPhi=dEta=0.0;
	dPhi = phi1-phi2;
	if (dPhi < -TMath::Pi()) dPhi += TMath::TwoPi();
	if (dPhi > +TMath::Pi()) dPhi -= TMath::TwoPi();
	dEta = eta1-eta2;
	dR = sqrt(dPhi*dPhi+dEta*dEta);

	return dR;
}

double Filter::deltaR(myobject o1, myobject o2)
{
	return deltaR(o1.eta,o1.phi,o2.eta,o2.phi);
}

bool Filter::Trg_MC_12(myevent* m) {
	map<string, int> myHLT = m->HLT;
	bool Trigger = false;
	bool TriggerEle = false;
	bool TriggerMu = false;

	for (map<string, int> ::iterator ihlt = myHLT.begin(); ihlt != myHLT.end() && !TriggerEle && !TriggerMu; ihlt++) {
		//	std::cout << ihlt->first << std::endl;
		size_t foundEl=(ihlt->first).find(doubEle);
		size_t foundEl2=(ihlt->first).find(doubEle2);
		if(!is2011) foundEl2=foundEl;

		size_t foundMu1=(ihlt->first).find(doubMu);
		size_t foundMu2=(ihlt->first).find(doubMu2);
		size_t foundMu3=(ihlt->first).find(doubMu3);
		if(!is2011) foundMu3=foundMu2;

		if (foundEl!=string::npos || foundEl2!=string::npos)
			TriggerEle = ihlt->second;
		if (foundMu1!=string::npos || foundMu2!=string::npos || foundMu3!=string::npos)
			TriggerMu = ihlt->second;
	}
	Trigger = TriggerEle || TriggerMu;
	if(vetoElectronTrigger && TriggerEle) Trigger = false;
	if(vetoMuonTrigger && TriggerMu) Trigger = false;
	return Trigger;
}

void Filter::ExecuteEvent( const SInputData&, Double_t ) throw( SError ) {

	++m_allEvents;
	if(m->runNumber!=current_run || m->lumiNumber!=current_lumi){
		lumi << m->runNumber << " " << m->lumiNumber << std::endl;
		current_run=m->runNumber;
		current_lumi=m->lumiNumber;
	}
	m_logger << DEBUG << " Now executing event " << m->eventNumber << " in a run " << m->runNumber << SLogger::endmsg;
	double event_number=9612;
	bool printout = false;
	if(m->eventNumber==event_number) printout=true;
	if(printout) std::cout << "Here!" << std::endl;

	bool trigPass = Trg_MC_12(m);
	m_logger << DEBUG << " Trigger decision " << trigPass << SLogger::endmsg;
	if(!trigPass)
	{
		if(printout) std::cout << "Trigger!" << std::endl;
		return;
	}
	if(printout) std::cout << "Here2!" << std::endl;

	std::vector<myobject> vertex = m->Vertex;
	bool goodVertex = false;
	for (uint i = 0; i < vertex.size() && !goodVertex; i++) {
		if (vertex[i].isValid && vertex[i].normalizedChi2 > 0 && vertex[i].ndof > 4 && fabs(vertex[i].z) < 24)
		goodVertex=true;
	}

	if(!goodVertex){
		if(printout) std::cout << "vertex!" << std::endl;
		return;
	}

	std::vector<myobject> muon = m->PreSelectedMuons;
	m_logger << VERBOSE << " There are " << muon.size() << " preselected muons " << SLogger::endmsg;

	std::vector<myobject> goodMuon;
	goodMuon.clear();

	for (uint i = 0; i < muon.size(); i++) {

		double muPt = muon[i].pt;
		double muEta = muon[i].eta;
		if (muPt > cut_mu_pt && fabs(muEta) < cut_mu_eta)
		{
				goodMuon.push_back(muon[i]);
		}

	}

	uint N_MU=goodMuon.size();

	std::vector<myobject> electron = m->PreSelectedElectrons;
	m_logger << VERBOSE << " There are " << electron.size() << " preselected electrons " << SLogger::endmsg;

	std::vector<myobject> goodElectron;
	goodElectron.clear();

	for (uint i = 0; i < electron.size(); i++) {

		double elPt = electron[i].pt;
		double elEta = electron[i].eta;

		if (elPt > cut_el_pt && fabs(elEta) < cut_el_eta )
		{
			goodElectron.push_back(electron[i]);
		}
	}

	uint N_EL=goodElectron.size();

	std::vector<myobject> tau = m->PreSelectedHPSTaus;

	m_logger << DEBUG << " There are " << tau.size() << " preselected taus " << SLogger::endmsg;

	std::vector<myobject> goodTau;
	goodTau.clear();

	for (uint i = 0; i < tau.size(); i++) {

		double tauPt = tau[i].pt;
		double tauEta = tau[i].eta;
		bool DecayMode = (tau[i].discriminationByDecayModeFinding > 0.5);

		if (tauPt > cut_tau_pt && fabs(tauEta) < cut_tau_eta && DecayMode)
			goodTau.push_back(tau[i]);
	}

	uint N_TAU=goodTau.size();
	m_logger << DEBUG << " There are " << N_MU << " muons " << N_EL << " electrons and " << N_TAU << " taus." << SLogger::endmsg;

	if(N_ALL > 0 && (N_MU+N_EL+N_TAU) < N_ALL){		if(printout) std::cout << "N_ALL!" << std::endl; return;}
	if(N_ELMU > 0 && (N_MU+N_EL) < N_ELMU){		if(printout) std::cout << "N_ELMU!" << std::endl; return;}

	if(printout) std::cout << "Here3!" << std::endl;

	bool failDR = false;
	if(cut_dR > 0){
		if(N_MU > 0)
		{
			for(uint iMu=0; iMu < N_MU && !failDR; iMu++)
			{
				for(uint jMu =iMu+1; jMu < N_MU && !failDR; jMu++)
				{
					double dR=deltaR(goodMuon[iMu],goodMuon[jMu]);
					m_logger << VERBOSE << " MuMu: " << iMu << " " << jMu << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}

				for(uint iEl =0; iEl < N_EL && !failDR; iEl++)
				{
					double dR=deltaR(goodMuon[iMu],goodElectron[iEl]);
					m_logger << VERBOSE << " MuEl: " << iMu << " " << iEl << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}

				for(uint iTau =0; iTau < N_TAU && !failDR; iTau++)
				{
					double dR=deltaR(goodMuon[iMu],goodTau[iTau]);
					m_logger << VERBOSE << " MuTau: " << iMu << " " << iTau << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}
			}
		}else if(N_EL > 0)
		{
			for(uint iEl=0; iEl < N_EL && !failDR; iEl++)
			{
				for(uint jEl =iEl+1; jEl < N_EL && !failDR; jEl++)
				{
					double dR=deltaR(goodElectron[iEl],goodElectron[jEl]);
					m_logger << VERBOSE << " ElEl: " << iEl << " " << jEl << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}

				for(uint iTau =0; iTau < N_TAU && !failDR; iTau++)
				{
					double dR=deltaR(goodElectron[iEl],goodTau[iTau]);
					m_logger << VERBOSE << " ElTau: " << iEl << " " << iTau << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}
			}

		}else if(N_TAU > 0)
		{
			for(uint iTau=0; iTau < N_TAU && !failDR; iTau++)
			{
				for(uint jTau =iTau+1; jTau < N_TAU && !failDR; jTau++)
				{
					double dR=deltaR(goodTau[iTau],goodTau[jTau]);
					m_logger << VERBOSE << " TauTau: " << iTau << " " << jTau << " :" << dR << SLogger::endmsg;
					if(dR < cut_dR) failDR=true;
				}
			}
		}
	}

	if(failDR){		if(printout) std::cout << "dR" << std::endl; return;}
	if(printout) std::cout << "Here4!" << std::endl;

	// dMass cut

	bool passMass = false;

	for (uint i = 0; i < goodMuon.size() && !passMass; i++) {
		for (uint j = i+1; j < goodMuon.size() && !passMass; j++) {
			TLorentzVector cand;
			cand.SetPxPyPzE(goodMuon[i].px+goodMuon[j].px,
					goodMuon[i].py+goodMuon[j].py,
					goodMuon[i].pz+goodMuon[j].pz,
					goodMuon[i].E+goodMuon[j].E);
			double mass = cand.M();
			if(printout) std::cout << mass << std::endl;
			if(mass > lepton_mass_min && mass < lepton_mass_max ) passMass=true;
			if(passMass) m_logger << DEBUG << " Passed mass cut with value " << mass << SLogger::endmsg;
			else m_logger << VERBOSE << " Failed mass cut with value " << mass << SLogger::endmsg;
		}
	}

	for (uint i = 0; i < goodElectron.size() && !passMass; i++) {
		for (uint j = i+1; j < goodElectron.size() && !passMass; j++) {
			TLorentzVector cand;
			cand.SetPxPyPzE(goodElectron[i].px+goodElectron[j].px,
					goodElectron[i].py+goodElectron[j].py,
					goodElectron[i].pz+goodElectron[j].pz,
					goodElectron[i].E+goodElectron[j].E);
			double mass = cand.M();
			if(printout) std::cout << mass << std::endl;
			if(mass > lepton_mass_min && mass < lepton_mass_max ) passMass=true;
			if(passMass) m_logger << DEBUG << " Passed mass cut with value " << mass << SLogger::endmsg;
			else m_logger << VERBOSE << " Failed mass cut with value " << mass << SLogger::endmsg;
		}
	}

	if(!passMass){		if(printout) std::cout << "Mass" << std::endl; return;}
	if(printout) std::cout << "Here5!" << std::endl;

	m_logger << DEBUG << " Passed!" << SLogger::endmsg;

	out=*m;
	outTree->Fill();

	if(printout) std::cout << "Pass!" << std::endl;

   return;

}

<|endoftext|>